##// END OF EJS Templates
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
adityausathe -
Show More
@@ -1,3263 +1,3259 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 def __init__(self, ipython_dir=None, profile_dir=None,
434 def __init__(self, ipython_dir=None, profile_dir=None,
435 user_module=None, user_ns=None,
435 user_module=None, user_ns=None,
436 custom_exceptions=((), None), **kwargs):
436 custom_exceptions=((), None), **kwargs):
437
437
438 # This is where traits with a config_key argument are updated
438 # This is where traits with a config_key argument are updated
439 # from the values on config.
439 # from the values on config.
440 super(InteractiveShell, self).__init__(**kwargs)
440 super(InteractiveShell, self).__init__(**kwargs)
441 if 'PromptManager' in self.config:
441 if 'PromptManager' in self.config:
442 warn('As of IPython 5.0 `PromptManager` config will have no effect'
442 warn('As of IPython 5.0 `PromptManager` config will have no effect'
443 ' and has been replaced by TerminalInteractiveShell.prompts_class')
443 ' and has been replaced by TerminalInteractiveShell.prompts_class')
444 self.configurables = [self]
444 self.configurables = [self]
445
445
446 # These are relatively independent and stateless
446 # These are relatively independent and stateless
447 self.init_ipython_dir(ipython_dir)
447 self.init_ipython_dir(ipython_dir)
448 self.init_profile_dir(profile_dir)
448 self.init_profile_dir(profile_dir)
449 self.init_instance_attrs()
449 self.init_instance_attrs()
450 self.init_environment()
450 self.init_environment()
451
451
452 # Check if we're in a virtualenv, and set up sys.path.
452 # Check if we're in a virtualenv, and set up sys.path.
453 self.init_virtualenv()
453 self.init_virtualenv()
454
454
455 # Create namespaces (user_ns, user_global_ns, etc.)
455 # Create namespaces (user_ns, user_global_ns, etc.)
456 self.init_create_namespaces(user_module, user_ns)
456 self.init_create_namespaces(user_module, user_ns)
457 # This has to be done after init_create_namespaces because it uses
457 # This has to be done after init_create_namespaces because it uses
458 # something in self.user_ns, but before init_sys_modules, which
458 # something in self.user_ns, but before init_sys_modules, which
459 # is the first thing to modify sys.
459 # is the first thing to modify sys.
460 # TODO: When we override sys.stdout and sys.stderr before this class
460 # 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
461 # is created, we are saving the overridden ones here. Not sure if this
462 # is what we want to do.
462 # is what we want to do.
463 self.save_sys_module_state()
463 self.save_sys_module_state()
464 self.init_sys_modules()
464 self.init_sys_modules()
465
465
466 # While we're trying to have each part of the code directly access what
466 # 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
467 # it needs without keeping redundant references to objects, we have too
468 # much legacy code that expects ip.db to exist.
468 # much legacy code that expects ip.db to exist.
469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
470
470
471 self.init_history()
471 self.init_history()
472 self.init_encoding()
472 self.init_encoding()
473 self.init_prefilter()
473 self.init_prefilter()
474
474
475 self.init_syntax_highlighting()
475 self.init_syntax_highlighting()
476 self.init_hooks()
476 self.init_hooks()
477 self.init_events()
477 self.init_events()
478 self.init_pushd_popd_magic()
478 self.init_pushd_popd_magic()
479 self.init_user_ns()
479 self.init_user_ns()
480 self.init_logger()
480 self.init_logger()
481 self.init_builtins()
481 self.init_builtins()
482
482
483 # The following was in post_config_initialization
483 # The following was in post_config_initialization
484 self.init_inspector()
484 self.init_inspector()
485 self.raw_input_original = input
485 self.raw_input_original = input
486 self.init_completer()
486 self.init_completer()
487 # TODO: init_io() needs to happen before init_traceback handlers
487 # TODO: init_io() needs to happen before init_traceback handlers
488 # because the traceback handlers hardcode the stdout/stderr streams.
488 # because the traceback handlers hardcode the stdout/stderr streams.
489 # This logic in in debugger.Pdb and should eventually be changed.
489 # This logic in in debugger.Pdb and should eventually be changed.
490 self.init_io()
490 self.init_io()
491 self.init_traceback_handlers(custom_exceptions)
491 self.init_traceback_handlers(custom_exceptions)
492 self.init_prompts()
492 self.init_prompts()
493 self.init_display_formatter()
493 self.init_display_formatter()
494 self.init_display_pub()
494 self.init_display_pub()
495 self.init_data_pub()
495 self.init_data_pub()
496 self.init_displayhook()
496 self.init_displayhook()
497 self.init_magics()
497 self.init_magics()
498 self.init_alias()
498 self.init_alias()
499 self.init_logstart()
499 self.init_logstart()
500 self.init_pdb()
500 self.init_pdb()
501 self.init_extension_manager()
501 self.init_extension_manager()
502 self.init_payload()
502 self.init_payload()
503 self.init_deprecation_warnings()
503 self.init_deprecation_warnings()
504 self.hooks.late_startup_hook()
504 self.hooks.late_startup_hook()
505 self.events.trigger('shell_initialized', self)
505 self.events.trigger('shell_initialized', self)
506 atexit.register(self.atexit_operations)
506 atexit.register(self.atexit_operations)
507
507
508 def get_ipython(self):
508 def get_ipython(self):
509 """Return the currently running IPython instance."""
509 """Return the currently running IPython instance."""
510 return self
510 return self
511
511
512 #-------------------------------------------------------------------------
512 #-------------------------------------------------------------------------
513 # Trait changed handlers
513 # Trait changed handlers
514 #-------------------------------------------------------------------------
514 #-------------------------------------------------------------------------
515 @observe('ipython_dir')
515 @observe('ipython_dir')
516 def _ipython_dir_changed(self, change):
516 def _ipython_dir_changed(self, change):
517 ensure_dir_exists(change['new'])
517 ensure_dir_exists(change['new'])
518
518
519 def set_autoindent(self,value=None):
519 def set_autoindent(self,value=None):
520 """Set the autoindent flag.
520 """Set the autoindent flag.
521
521
522 If called with no arguments, it acts as a toggle."""
522 If called with no arguments, it acts as a toggle."""
523 if value is None:
523 if value is None:
524 self.autoindent = not self.autoindent
524 self.autoindent = not self.autoindent
525 else:
525 else:
526 self.autoindent = value
526 self.autoindent = value
527
527
528 #-------------------------------------------------------------------------
528 #-------------------------------------------------------------------------
529 # init_* methods called by __init__
529 # init_* methods called by __init__
530 #-------------------------------------------------------------------------
530 #-------------------------------------------------------------------------
531
531
532 def init_ipython_dir(self, ipython_dir):
532 def init_ipython_dir(self, ipython_dir):
533 if ipython_dir is not None:
533 if ipython_dir is not None:
534 self.ipython_dir = ipython_dir
534 self.ipython_dir = ipython_dir
535 return
535 return
536
536
537 self.ipython_dir = get_ipython_dir()
537 self.ipython_dir = get_ipython_dir()
538
538
539 def init_profile_dir(self, profile_dir):
539 def init_profile_dir(self, profile_dir):
540 if profile_dir is not None:
540 if profile_dir is not None:
541 self.profile_dir = profile_dir
541 self.profile_dir = profile_dir
542 return
542 return
543 self.profile_dir =\
543 self.profile_dir =\
544 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
544 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
545
545
546 def init_instance_attrs(self):
546 def init_instance_attrs(self):
547 self.more = False
547 self.more = False
548
548
549 # command compiler
549 # command compiler
550 self.compile = CachingCompiler()
550 self.compile = CachingCompiler()
551
551
552 # Make an empty namespace, which extension writers can rely on both
552 # Make an empty namespace, which extension writers can rely on both
553 # existing and NEVER being used by ipython itself. This gives them a
553 # existing and NEVER being used by ipython itself. This gives them a
554 # convenient location for storing additional information and state
554 # convenient location for storing additional information and state
555 # their extensions may require, without fear of collisions with other
555 # their extensions may require, without fear of collisions with other
556 # ipython names that may develop later.
556 # ipython names that may develop later.
557 self.meta = Struct()
557 self.meta = Struct()
558
558
559 # Temporary files used for various purposes. Deleted at exit.
559 # Temporary files used for various purposes. Deleted at exit.
560 self.tempfiles = []
560 self.tempfiles = []
561 self.tempdirs = []
561 self.tempdirs = []
562
562
563 # keep track of where we started running (mainly for crash post-mortem)
563 # keep track of where we started running (mainly for crash post-mortem)
564 # This is not being used anywhere currently.
564 # This is not being used anywhere currently.
565 self.starting_dir = os.getcwd()
565 self.starting_dir = os.getcwd()
566
566
567 # Indentation management
567 # Indentation management
568 self.indent_current_nsp = 0
568 self.indent_current_nsp = 0
569
569
570 # Dict to track post-execution functions that have been registered
570 # Dict to track post-execution functions that have been registered
571 self._post_execute = {}
571 self._post_execute = {}
572
572
573 def init_environment(self):
573 def init_environment(self):
574 """Any changes we need to make to the user's environment."""
574 """Any changes we need to make to the user's environment."""
575 pass
575 pass
576
576
577 def init_encoding(self):
577 def init_encoding(self):
578 # Get system encoding at startup time. Certain terminals (like Emacs
578 # 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
579 # under Win32 have it set to None, and we need to have a known valid
580 # encoding to use in the raw_input() method
580 # encoding to use in the raw_input() method
581 try:
581 try:
582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
583 except AttributeError:
583 except AttributeError:
584 self.stdin_encoding = 'ascii'
584 self.stdin_encoding = 'ascii'
585
585
586
586
587 @observe('colors')
587 @observe('colors')
588 def init_syntax_highlighting(self, changes=None):
588 def init_syntax_highlighting(self, changes=None):
589 # Python source parser/formatter for syntax highlighting
589 # Python source parser/formatter for syntax highlighting
590 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
590 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
591 self.pycolorize = lambda src: pyformat(src,'str')
591 self.pycolorize = lambda src: pyformat(src,'str')
592
592
593 def refresh_style(self):
593 def refresh_style(self):
594 # No-op here, used in subclass
594 # No-op here, used in subclass
595 pass
595 pass
596
596
597 def init_pushd_popd_magic(self):
597 def init_pushd_popd_magic(self):
598 # for pushd/popd management
598 # for pushd/popd management
599 self.home_dir = get_home_dir()
599 self.home_dir = get_home_dir()
600
600
601 self.dir_stack = []
601 self.dir_stack = []
602
602
603 def init_logger(self):
603 def init_logger(self):
604 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
604 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
605 logmode='rotate')
605 logmode='rotate')
606
606
607 def init_logstart(self):
607 def init_logstart(self):
608 """Initialize logging in case it was requested at the command line.
608 """Initialize logging in case it was requested at the command line.
609 """
609 """
610 if self.logappend:
610 if self.logappend:
611 self.magic('logstart %s append' % self.logappend)
611 self.magic('logstart %s append' % self.logappend)
612 elif self.logfile:
612 elif self.logfile:
613 self.magic('logstart %s' % self.logfile)
613 self.magic('logstart %s' % self.logfile)
614 elif self.logstart:
614 elif self.logstart:
615 self.magic('logstart')
615 self.magic('logstart')
616
616
617 def init_deprecation_warnings(self):
617 def init_deprecation_warnings(self):
618 """
618 """
619 register default filter for deprecation warning.
619 register default filter for deprecation warning.
620
620
621 This will allow deprecation warning of function used interactively to show
621 This will allow deprecation warning of function used interactively to show
622 warning to users, and still hide deprecation warning from libraries import.
622 warning to users, and still hide deprecation warning from libraries import.
623 """
623 """
624 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
624 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
625
625
626 def init_builtins(self):
626 def init_builtins(self):
627 # A single, static flag that we set to True. Its presence indicates
627 # 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
628 # 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
629 # removing on exit or representing the existence of more than one
630 # IPython at a time.
630 # IPython at a time.
631 builtin_mod.__dict__['__IPYTHON__'] = True
631 builtin_mod.__dict__['__IPYTHON__'] = True
632 builtin_mod.__dict__['display'] = display
632 builtin_mod.__dict__['display'] = display
633
633
634 self.builtin_trap = BuiltinTrap(shell=self)
634 self.builtin_trap = BuiltinTrap(shell=self)
635
635
636 def init_inspector(self):
636 def init_inspector(self):
637 # Object inspector
637 # Object inspector
638 self.inspector = oinspect.Inspector(oinspect.InspectColors,
638 self.inspector = oinspect.Inspector(oinspect.InspectColors,
639 PyColorize.ANSICodeColors,
639 PyColorize.ANSICodeColors,
640 self.colors,
640 self.colors,
641 self.object_info_string_level)
641 self.object_info_string_level)
642
642
643 def init_io(self):
643 def init_io(self):
644 # This will just use sys.stdout and sys.stderr. If you want to
644 # 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
645 # override sys.stdout and sys.stderr themselves, you need to do that
646 # *before* instantiating this class, because io holds onto
646 # *before* instantiating this class, because io holds onto
647 # references to the underlying streams.
647 # references to the underlying streams.
648 # io.std* are deprecated, but don't show our own deprecation warnings
648 # io.std* are deprecated, but don't show our own deprecation warnings
649 # during initialization of the deprecated API.
649 # during initialization of the deprecated API.
650 with warnings.catch_warnings():
650 with warnings.catch_warnings():
651 warnings.simplefilter('ignore', DeprecationWarning)
651 warnings.simplefilter('ignore', DeprecationWarning)
652 io.stdout = io.IOStream(sys.stdout)
652 io.stdout = io.IOStream(sys.stdout)
653 io.stderr = io.IOStream(sys.stderr)
653 io.stderr = io.IOStream(sys.stderr)
654
654
655 def init_prompts(self):
655 def init_prompts(self):
656 # Set system prompts, so that scripts can decide if they are running
656 # Set system prompts, so that scripts can decide if they are running
657 # interactively.
657 # interactively.
658 sys.ps1 = 'In : '
658 sys.ps1 = 'In : '
659 sys.ps2 = '...: '
659 sys.ps2 = '...: '
660 sys.ps3 = 'Out: '
660 sys.ps3 = 'Out: '
661
661
662 def init_display_formatter(self):
662 def init_display_formatter(self):
663 self.display_formatter = DisplayFormatter(parent=self)
663 self.display_formatter = DisplayFormatter(parent=self)
664 self.configurables.append(self.display_formatter)
664 self.configurables.append(self.display_formatter)
665
665
666 def init_display_pub(self):
666 def init_display_pub(self):
667 self.display_pub = self.display_pub_class(parent=self)
667 self.display_pub = self.display_pub_class(parent=self)
668 self.configurables.append(self.display_pub)
668 self.configurables.append(self.display_pub)
669
669
670 def init_data_pub(self):
670 def init_data_pub(self):
671 if not self.data_pub_class:
671 if not self.data_pub_class:
672 self.data_pub = None
672 self.data_pub = None
673 return
673 return
674 self.data_pub = self.data_pub_class(parent=self)
674 self.data_pub = self.data_pub_class(parent=self)
675 self.configurables.append(self.data_pub)
675 self.configurables.append(self.data_pub)
676
676
677 def init_displayhook(self):
677 def init_displayhook(self):
678 # Initialize displayhook, set in/out prompts and printing system
678 # Initialize displayhook, set in/out prompts and printing system
679 self.displayhook = self.displayhook_class(
679 self.displayhook = self.displayhook_class(
680 parent=self,
680 parent=self,
681 shell=self,
681 shell=self,
682 cache_size=self.cache_size,
682 cache_size=self.cache_size,
683 )
683 )
684 self.configurables.append(self.displayhook)
684 self.configurables.append(self.displayhook)
685 # This is a context manager that installs/revmoes the displayhook at
685 # This is a context manager that installs/revmoes the displayhook at
686 # the appropriate time.
686 # the appropriate time.
687 self.display_trap = DisplayTrap(hook=self.displayhook)
687 self.display_trap = DisplayTrap(hook=self.displayhook)
688
688
689 def init_virtualenv(self):
689 def init_virtualenv(self):
690 """Add a virtualenv to sys.path so the user can import modules from it.
690 """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
691 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
692 virtualenv was built, and it ignores the --no-site-packages option. A
693 warning will appear suggesting the user installs IPython in the
693 warning will appear suggesting the user installs IPython in the
694 virtualenv, but for many cases, it probably works well enough.
694 virtualenv, but for many cases, it probably works well enough.
695
695
696 Adapted from code snippets online.
696 Adapted from code snippets online.
697
697
698 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
698 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
699 """
699 """
700 if 'VIRTUAL_ENV' not in os.environ:
700 if 'VIRTUAL_ENV' not in os.environ:
701 # Not in a virtualenv
701 # Not in a virtualenv
702 return
702 return
703
703
704 # venv detection:
704 # venv detection:
705 # stdlib venv may symlink sys.executable, so we can't use realpath.
705 # 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.
706 # 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)
707 # So we just check every item in the symlink tree (generally <= 3)
708 p = os.path.normcase(sys.executable)
708 p = os.path.normcase(sys.executable)
709 paths = [p]
709 paths = [p]
710 while os.path.islink(p):
710 while os.path.islink(p):
711 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
711 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
712 paths.append(p)
712 paths.append(p)
713 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
713 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
714
714
715 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
715 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
716 if p_venv.startswith('\\cygdrive'):
716 if p_venv.startswith('\\cygdrive'):
717 p_venv = p_venv[11:]
717 p_venv = p_venv[11:]
718 elif p_venv[1] == ':':
718 elif p_venv[1] == ':':
719 p_venv = p_venv[2:]
719 p_venv = p_venv[2:]
720
720
721 if any(p_venv in p for p in paths):
721 if any(p_venv in p for p in paths):
722 # Running properly in the virtualenv, don't need to do anything
722 # Running properly in the virtualenv, don't need to do anything
723 return
723 return
724
724
725 warn("Attempting to work in a virtualenv. If you encounter problems, please "
725 warn("Attempting to work in a virtualenv. If you encounter problems, please "
726 "install IPython inside the virtualenv.")
726 "install IPython inside the virtualenv.")
727 if sys.platform == "win32":
727 if sys.platform == "win32":
728 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
728 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
729 else:
729 else:
730 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
730 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
731 'python%d.%d' % sys.version_info[:2], 'site-packages')
731 'python%d.%d' % sys.version_info[:2], 'site-packages')
732
732
733 import site
733 import site
734 sys.path.insert(0, virtual_env)
734 sys.path.insert(0, virtual_env)
735 site.addsitedir(virtual_env)
735 site.addsitedir(virtual_env)
736
736
737 #-------------------------------------------------------------------------
737 #-------------------------------------------------------------------------
738 # Things related to injections into the sys module
738 # Things related to injections into the sys module
739 #-------------------------------------------------------------------------
739 #-------------------------------------------------------------------------
740
740
741 def save_sys_module_state(self):
741 def save_sys_module_state(self):
742 """Save the state of hooks in the sys module.
742 """Save the state of hooks in the sys module.
743
743
744 This has to be called after self.user_module is created.
744 This has to be called after self.user_module is created.
745 """
745 """
746 self._orig_sys_module_state = {'stdin': sys.stdin,
746 self._orig_sys_module_state = {'stdin': sys.stdin,
747 'stdout': sys.stdout,
747 'stdout': sys.stdout,
748 'stderr': sys.stderr,
748 'stderr': sys.stderr,
749 'excepthook': sys.excepthook}
749 'excepthook': sys.excepthook}
750 self._orig_sys_modules_main_name = self.user_module.__name__
750 self._orig_sys_modules_main_name = self.user_module.__name__
751 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
751 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
752
752
753 def restore_sys_module_state(self):
753 def restore_sys_module_state(self):
754 """Restore the state of the sys module."""
754 """Restore the state of the sys module."""
755 try:
755 try:
756 for k, v in self._orig_sys_module_state.items():
756 for k, v in self._orig_sys_module_state.items():
757 setattr(sys, k, v)
757 setattr(sys, k, v)
758 except AttributeError:
758 except AttributeError:
759 pass
759 pass
760 # Reset what what done in self.init_sys_modules
760 # Reset what what done in self.init_sys_modules
761 if self._orig_sys_modules_main_mod is not None:
761 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
762 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
763
763
764 #-------------------------------------------------------------------------
764 #-------------------------------------------------------------------------
765 # Things related to the banner
765 # Things related to the banner
766 #-------------------------------------------------------------------------
766 #-------------------------------------------------------------------------
767
767
768 @property
768 @property
769 def banner(self):
769 def banner(self):
770 banner = self.banner1
770 banner = self.banner1
771 if self.profile and self.profile != 'default':
771 if self.profile and self.profile != 'default':
772 banner += '\nIPython profile: %s\n' % self.profile
772 banner += '\nIPython profile: %s\n' % self.profile
773 if self.banner2:
773 if self.banner2:
774 banner += '\n' + self.banner2
774 banner += '\n' + self.banner2
775 return banner
775 return banner
776
776
777 def show_banner(self, banner=None):
777 def show_banner(self, banner=None):
778 if banner is None:
778 if banner is None:
779 banner = self.banner
779 banner = self.banner
780 sys.stdout.write(banner)
780 sys.stdout.write(banner)
781
781
782 #-------------------------------------------------------------------------
782 #-------------------------------------------------------------------------
783 # Things related to hooks
783 # Things related to hooks
784 #-------------------------------------------------------------------------
784 #-------------------------------------------------------------------------
785
785
786 def init_hooks(self):
786 def init_hooks(self):
787 # hooks holds pointers used for user-side customizations
787 # hooks holds pointers used for user-side customizations
788 self.hooks = Struct()
788 self.hooks = Struct()
789
789
790 self.strdispatchers = {}
790 self.strdispatchers = {}
791
791
792 # Set all default hooks, defined in the IPython.hooks module.
792 # Set all default hooks, defined in the IPython.hooks module.
793 hooks = IPython.core.hooks
793 hooks = IPython.core.hooks
794 for hook_name in hooks.__all__:
794 for hook_name in hooks.__all__:
795 # default hooks have priority 100, i.e. low; user hooks should have
795 # default hooks have priority 100, i.e. low; user hooks should have
796 # 0-100 priority
796 # 0-100 priority
797 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
797 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
798
798
799 if self.display_page:
799 if self.display_page:
800 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
800 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
801
801
802 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
802 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
803 _warn_deprecated=True):
803 _warn_deprecated=True):
804 """set_hook(name,hook) -> sets an internal IPython hook.
804 """set_hook(name,hook) -> sets an internal IPython hook.
805
805
806 IPython exposes some of its internal API as user-modifiable hooks. By
806 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
807 adding your function to one of these hooks, you can modify IPython's
808 behavior to call at runtime your own routines."""
808 behavior to call at runtime your own routines."""
809
809
810 # At some point in the future, this should validate the hook before it
810 # 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
811 # accepts it. Probably at least check that the hook takes the number
812 # of args it's supposed to.
812 # of args it's supposed to.
813
813
814 f = types.MethodType(hook,self)
814 f = types.MethodType(hook,self)
815
815
816 # check if the hook is for strdispatcher first
816 # check if the hook is for strdispatcher first
817 if str_key is not None:
817 if str_key is not None:
818 sdp = self.strdispatchers.get(name, StrDispatch())
818 sdp = self.strdispatchers.get(name, StrDispatch())
819 sdp.add_s(str_key, f, priority )
819 sdp.add_s(str_key, f, priority )
820 self.strdispatchers[name] = sdp
820 self.strdispatchers[name] = sdp
821 return
821 return
822 if re_key is not None:
822 if re_key is not None:
823 sdp = self.strdispatchers.get(name, StrDispatch())
823 sdp = self.strdispatchers.get(name, StrDispatch())
824 sdp.add_re(re.compile(re_key), f, priority )
824 sdp.add_re(re.compile(re_key), f, priority )
825 self.strdispatchers[name] = sdp
825 self.strdispatchers[name] = sdp
826 return
826 return
827
827
828 dp = getattr(self.hooks, name, None)
828 dp = getattr(self.hooks, name, None)
829 if name not in IPython.core.hooks.__all__:
829 if name not in IPython.core.hooks.__all__:
830 print("Warning! Hook '%s' is not one of %s" % \
830 print("Warning! Hook '%s' is not one of %s" % \
831 (name, IPython.core.hooks.__all__ ))
831 (name, IPython.core.hooks.__all__ ))
832
832
833 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
833 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
834 alternative = IPython.core.hooks.deprecated[name]
834 alternative = IPython.core.hooks.deprecated[name]
835 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
835 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
836
836
837 if not dp:
837 if not dp:
838 dp = IPython.core.hooks.CommandChainDispatcher()
838 dp = IPython.core.hooks.CommandChainDispatcher()
839
839
840 try:
840 try:
841 dp.add(f,priority)
841 dp.add(f,priority)
842 except AttributeError:
842 except AttributeError:
843 # it was not commandchain, plain old func - replace
843 # it was not commandchain, plain old func - replace
844 dp = f
844 dp = f
845
845
846 setattr(self.hooks,name, dp)
846 setattr(self.hooks,name, dp)
847
847
848 #-------------------------------------------------------------------------
848 #-------------------------------------------------------------------------
849 # Things related to events
849 # Things related to events
850 #-------------------------------------------------------------------------
850 #-------------------------------------------------------------------------
851
851
852 def init_events(self):
852 def init_events(self):
853 self.events = EventManager(self, available_events)
853 self.events = EventManager(self, available_events)
854
854
855 self.events.register("pre_execute", self._clear_warning_registry)
855 self.events.register("pre_execute", self._clear_warning_registry)
856
856
857 def register_post_execute(self, func):
857 def register_post_execute(self, func):
858 """DEPRECATED: Use ip.events.register('post_run_cell', func)
858 """DEPRECATED: Use ip.events.register('post_run_cell', func)
859
859
860 Register a function for calling after code execution.
860 Register a function for calling after code execution.
861 """
861 """
862 warn("ip.register_post_execute is deprecated, use "
862 warn("ip.register_post_execute is deprecated, use "
863 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
863 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
864 self.events.register('post_run_cell', func)
864 self.events.register('post_run_cell', func)
865
865
866 def _clear_warning_registry(self):
866 def _clear_warning_registry(self):
867 # clear the warning registry, so that different code blocks with
867 # clear the warning registry, so that different code blocks with
868 # overlapping line number ranges don't cause spurious suppression of
868 # overlapping line number ranges don't cause spurious suppression of
869 # warnings (see gh-6611 for details)
869 # warnings (see gh-6611 for details)
870 if "__warningregistry__" in self.user_global_ns:
870 if "__warningregistry__" in self.user_global_ns:
871 del self.user_global_ns["__warningregistry__"]
871 del self.user_global_ns["__warningregistry__"]
872
872
873 #-------------------------------------------------------------------------
873 #-------------------------------------------------------------------------
874 # Things related to the "main" module
874 # Things related to the "main" module
875 #-------------------------------------------------------------------------
875 #-------------------------------------------------------------------------
876
876
877 def new_main_mod(self, filename, modname):
877 def new_main_mod(self, filename, modname):
878 """Return a new 'main' module object for user code execution.
878 """Return a new 'main' module object for user code execution.
879
879
880 ``filename`` should be the path of the script which will be run in the
880 ``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
881 module. Requests with the same filename will get the same module, with
882 its namespace cleared.
882 its namespace cleared.
883
883
884 ``modname`` should be the module name - normally either '__main__' or
884 ``modname`` should be the module name - normally either '__main__' or
885 the basename of the file without the extension.
885 the basename of the file without the extension.
886
886
887 When scripts are executed via %run, we must keep a reference to their
887 When scripts are executed via %run, we must keep a reference to their
888 __main__ module around so that Python doesn't
888 __main__ module around so that Python doesn't
889 clear it, rendering references to module globals useless.
889 clear it, rendering references to module globals useless.
890
890
891 This method keeps said reference in a private dict, keyed by the
891 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
892 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),
893 same script we only keep one copy of the namespace (the last one),
894 thus preventing memory leaks from old references while allowing the
894 thus preventing memory leaks from old references while allowing the
895 objects from the last execution to be accessible.
895 objects from the last execution to be accessible.
896 """
896 """
897 filename = os.path.abspath(filename)
897 filename = os.path.abspath(filename)
898 try:
898 try:
899 main_mod = self._main_mod_cache[filename]
899 main_mod = self._main_mod_cache[filename]
900 except KeyError:
900 except KeyError:
901 main_mod = self._main_mod_cache[filename] = types.ModuleType(
901 main_mod = self._main_mod_cache[filename] = types.ModuleType(
902 modname,
902 modname,
903 doc="Module created for script run in IPython")
903 doc="Module created for script run in IPython")
904 else:
904 else:
905 main_mod.__dict__.clear()
905 main_mod.__dict__.clear()
906 main_mod.__name__ = modname
906 main_mod.__name__ = modname
907
907
908 main_mod.__file__ = filename
908 main_mod.__file__ = filename
909 # It seems pydoc (and perhaps others) needs any module instance to
909 # It seems pydoc (and perhaps others) needs any module instance to
910 # implement a __nonzero__ method
910 # implement a __nonzero__ method
911 main_mod.__nonzero__ = lambda : True
911 main_mod.__nonzero__ = lambda : True
912
912
913 return main_mod
913 return main_mod
914
914
915 def clear_main_mod_cache(self):
915 def clear_main_mod_cache(self):
916 """Clear the cache of main modules.
916 """Clear the cache of main modules.
917
917
918 Mainly for use by utilities like %reset.
918 Mainly for use by utilities like %reset.
919
919
920 Examples
920 Examples
921 --------
921 --------
922
922
923 In [15]: import IPython
923 In [15]: import IPython
924
924
925 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
925 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
926
926
927 In [17]: len(_ip._main_mod_cache) > 0
927 In [17]: len(_ip._main_mod_cache) > 0
928 Out[17]: True
928 Out[17]: True
929
929
930 In [18]: _ip.clear_main_mod_cache()
930 In [18]: _ip.clear_main_mod_cache()
931
931
932 In [19]: len(_ip._main_mod_cache) == 0
932 In [19]: len(_ip._main_mod_cache) == 0
933 Out[19]: True
933 Out[19]: True
934 """
934 """
935 self._main_mod_cache.clear()
935 self._main_mod_cache.clear()
936
936
937 #-------------------------------------------------------------------------
937 #-------------------------------------------------------------------------
938 # Things related to debugging
938 # Things related to debugging
939 #-------------------------------------------------------------------------
939 #-------------------------------------------------------------------------
940
940
941 def init_pdb(self):
941 def init_pdb(self):
942 # Set calling of pdb on exceptions
942 # Set calling of pdb on exceptions
943 # self.call_pdb is a property
943 # self.call_pdb is a property
944 self.call_pdb = self.pdb
944 self.call_pdb = self.pdb
945
945
946 def _get_call_pdb(self):
946 def _get_call_pdb(self):
947 return self._call_pdb
947 return self._call_pdb
948
948
949 def _set_call_pdb(self,val):
949 def _set_call_pdb(self,val):
950
950
951 if val not in (0,1,False,True):
951 if val not in (0,1,False,True):
952 raise ValueError('new call_pdb value must be boolean')
952 raise ValueError('new call_pdb value must be boolean')
953
953
954 # store value in instance
954 # store value in instance
955 self._call_pdb = val
955 self._call_pdb = val
956
956
957 # notify the actual exception handlers
957 # notify the actual exception handlers
958 self.InteractiveTB.call_pdb = val
958 self.InteractiveTB.call_pdb = val
959
959
960 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
960 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
961 'Control auto-activation of pdb at exceptions')
961 'Control auto-activation of pdb at exceptions')
962
962
963 def debugger(self,force=False):
963 def debugger(self,force=False):
964 """Call the pdb debugger.
964 """Call the pdb debugger.
965
965
966 Keywords:
966 Keywords:
967
967
968 - force(False): by default, this routine checks the instance call_pdb
968 - 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.
969 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
970 The 'force' option forces the debugger to activate even if the flag
971 is false.
971 is false.
972 """
972 """
973
973
974 if not (force or self.call_pdb):
974 if not (force or self.call_pdb):
975 return
975 return
976
976
977 if not hasattr(sys,'last_traceback'):
977 if not hasattr(sys,'last_traceback'):
978 error('No traceback has been produced, nothing to debug.')
978 error('No traceback has been produced, nothing to debug.')
979 return
979 return
980
980
981 self.InteractiveTB.debugger(force=True)
981 self.InteractiveTB.debugger(force=True)
982
982
983 #-------------------------------------------------------------------------
983 #-------------------------------------------------------------------------
984 # Things related to IPython's various namespaces
984 # Things related to IPython's various namespaces
985 #-------------------------------------------------------------------------
985 #-------------------------------------------------------------------------
986 default_user_namespaces = True
986 default_user_namespaces = True
987
987
988 def init_create_namespaces(self, user_module=None, user_ns=None):
988 def init_create_namespaces(self, user_module=None, user_ns=None):
989 # Create the namespace where the user will operate. user_ns is
989 # 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
990 # 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
991 # the locals argument. But we do carry a user_global_ns namespace
992 # given as the exec 'globals' argument, This is useful in embedding
992 # given as the exec 'globals' argument, This is useful in embedding
993 # situations where the ipython shell opens in a context where the
993 # situations where the ipython shell opens in a context where the
994 # distinction between locals and globals is meaningful. For
994 # distinction between locals and globals is meaningful. For
995 # non-embedded contexts, it is just the same object as the user_ns dict.
995 # non-embedded contexts, it is just the same object as the user_ns dict.
996
996
997 # FIXME. For some strange reason, __builtins__ is showing up at user
997 # 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
998 # 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
999 # should really track down where the problem is coming from. Alex
1000 # Schmolck reported this problem first.
1000 # Schmolck reported this problem first.
1001
1001
1002 # A useful post by Alex Martelli on this topic:
1002 # A useful post by Alex Martelli on this topic:
1003 # Re: inconsistent value from __builtins__
1003 # Re: inconsistent value from __builtins__
1004 # Von: Alex Martelli <aleaxit@yahoo.com>
1004 # Von: Alex Martelli <aleaxit@yahoo.com>
1005 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1005 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1006 # Gruppen: comp.lang.python
1006 # Gruppen: comp.lang.python
1007
1007
1008 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1008 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1009 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1009 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1010 # > <type 'dict'>
1010 # > <type 'dict'>
1011 # > >>> print type(__builtins__)
1011 # > >>> print type(__builtins__)
1012 # > <type 'module'>
1012 # > <type 'module'>
1013 # > Is this difference in return value intentional?
1013 # > Is this difference in return value intentional?
1014
1014
1015 # Well, it's documented that '__builtins__' can be either a dictionary
1015 # 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
1016 # 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
1017 # 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
1018 # that if you need to access the built-in namespace directly, you
1019 # should start with "import __builtin__" (note, no 's') which will
1019 # should start with "import __builtin__" (note, no 's') which will
1020 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1020 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1021
1021
1022 # These routines return a properly built module and dict as needed by
1022 # 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
1023 # the rest of the code, and can also be used by extension writers to
1024 # generate properly initialized namespaces.
1024 # generate properly initialized namespaces.
1025 if (user_ns is not None) or (user_module is not None):
1025 if (user_ns is not None) or (user_module is not None):
1026 self.default_user_namespaces = False
1026 self.default_user_namespaces = False
1027 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1027 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1028
1028
1029 # A record of hidden variables we have added to the user namespace, so
1029 # 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.
1030 # we can list later only variables defined in actual interactive use.
1031 self.user_ns_hidden = {}
1031 self.user_ns_hidden = {}
1032
1032
1033 # Now that FakeModule produces a real module, we've run into a nasty
1033 # 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
1034 # 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
1035 # code ran is deleted. Now that this object is a true module (needed
1036 # so doctest and other tools work correctly), the Python module
1036 # so doctest and other tools work correctly), the Python module
1037 # teardown mechanism runs over it, and sets to None every variable
1037 # teardown mechanism runs over it, and sets to None every variable
1038 # present in that module. Top-level references to objects from the
1038 # present in that module. Top-level references to objects from the
1039 # script survive, because the user_ns is updated with them. However,
1039 # script survive, because the user_ns is updated with them. However,
1040 # calling functions defined in the script that use other things from
1040 # calling functions defined in the script that use other things from
1041 # the script will fail, because the function's closure had references
1041 # 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
1042 # to the original objects, which are now all None. So we must protect
1043 # these modules from deletion by keeping a cache.
1043 # these modules from deletion by keeping a cache.
1044 #
1044 #
1045 # To avoid keeping stale modules around (we only need the one from the
1045 # 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
1046 # 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,
1047 # only the last version of the module is held in the cache. Note,
1048 # however, that we must cache the module *namespace contents* (their
1048 # however, that we must cache the module *namespace contents* (their
1049 # __dict__). Because if we try to cache the actual modules, old ones
1049 # __dict__). Because if we try to cache the actual modules, old ones
1050 # (uncached) could be destroyed while still holding references (such as
1050 # (uncached) could be destroyed while still holding references (such as
1051 # those held by GUI objects that tend to be long-lived)>
1051 # those held by GUI objects that tend to be long-lived)>
1052 #
1052 #
1053 # The %reset command will flush this cache. See the cache_main_mod()
1053 # The %reset command will flush this cache. See the cache_main_mod()
1054 # and clear_main_mod_cache() methods for details on use.
1054 # and clear_main_mod_cache() methods for details on use.
1055
1055
1056 # This is the cache used for 'main' namespaces
1056 # This is the cache used for 'main' namespaces
1057 self._main_mod_cache = {}
1057 self._main_mod_cache = {}
1058
1058
1059 # A table holding all the namespaces IPython deals with, so that
1059 # A table holding all the namespaces IPython deals with, so that
1060 # introspection facilities can search easily.
1060 # introspection facilities can search easily.
1061 self.ns_table = {'user_global':self.user_module.__dict__,
1061 self.ns_table = {'user_global':self.user_module.__dict__,
1062 'user_local':self.user_ns,
1062 'user_local':self.user_ns,
1063 'builtin':builtin_mod.__dict__
1063 'builtin':builtin_mod.__dict__
1064 }
1064 }
1065
1065
1066 @property
1066 @property
1067 def user_global_ns(self):
1067 def user_global_ns(self):
1068 return self.user_module.__dict__
1068 return self.user_module.__dict__
1069
1069
1070 def prepare_user_module(self, user_module=None, user_ns=None):
1070 def prepare_user_module(self, user_module=None, user_ns=None):
1071 """Prepare the module and namespace in which user code will be run.
1071 """Prepare the module and namespace in which user code will be run.
1072
1072
1073 When IPython is started normally, both parameters are None: a new module
1073 When IPython is started normally, both parameters are None: a new module
1074 is created automatically, and its __dict__ used as the namespace.
1074 is created automatically, and its __dict__ used as the namespace.
1075
1075
1076 If only user_module is provided, its __dict__ is used as the namespace.
1076 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
1077 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
1078 becomes the global namespace. If both are provided (as they may be
1079 when embedding), user_ns is the local namespace, and user_module
1079 when embedding), user_ns is the local namespace, and user_module
1080 provides the global namespace.
1080 provides the global namespace.
1081
1081
1082 Parameters
1082 Parameters
1083 ----------
1083 ----------
1084 user_module : module, optional
1084 user_module : module, optional
1085 The current user module in which IPython is being run. If None,
1085 The current user module in which IPython is being run. If None,
1086 a clean module will be created.
1086 a clean module will be created.
1087 user_ns : dict, optional
1087 user_ns : dict, optional
1088 A namespace in which to run interactive commands.
1088 A namespace in which to run interactive commands.
1089
1089
1090 Returns
1090 Returns
1091 -------
1091 -------
1092 A tuple of user_module and user_ns, each properly initialised.
1092 A tuple of user_module and user_ns, each properly initialised.
1093 """
1093 """
1094 if user_module is None and user_ns is not None:
1094 if user_module is None and user_ns is not None:
1095 user_ns.setdefault("__name__", "__main__")
1095 user_ns.setdefault("__name__", "__main__")
1096 user_module = DummyMod()
1096 user_module = DummyMod()
1097 user_module.__dict__ = user_ns
1097 user_module.__dict__ = user_ns
1098
1098
1099 if user_module is None:
1099 if user_module is None:
1100 user_module = types.ModuleType("__main__",
1100 user_module = types.ModuleType("__main__",
1101 doc="Automatically created module for IPython interactive environment")
1101 doc="Automatically created module for IPython interactive environment")
1102
1102
1103 # We must ensure that __builtin__ (without the final 's') is always
1103 # We must ensure that __builtin__ (without the final 's') is always
1104 # available and pointing to the __builtin__ *module*. For more details:
1104 # available and pointing to the __builtin__ *module*. For more details:
1105 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1105 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1106 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1106 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1107 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1107 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1108
1108
1109 if user_ns is None:
1109 if user_ns is None:
1110 user_ns = user_module.__dict__
1110 user_ns = user_module.__dict__
1111
1111
1112 return user_module, user_ns
1112 return user_module, user_ns
1113
1113
1114 def init_sys_modules(self):
1114 def init_sys_modules(self):
1115 # We need to insert into sys.modules something that looks like a
1115 # We need to insert into sys.modules something that looks like a
1116 # module but which accesses the IPython namespace, for shelve and
1116 # module but which accesses the IPython namespace, for shelve and
1117 # pickle to work interactively. Normally they rely on getting
1117 # pickle to work interactively. Normally they rely on getting
1118 # everything out of __main__, but for embedding purposes each IPython
1118 # everything out of __main__, but for embedding purposes each IPython
1119 # instance has its own private namespace, so we can't go shoving
1119 # instance has its own private namespace, so we can't go shoving
1120 # everything into __main__.
1120 # everything into __main__.
1121
1121
1122 # note, however, that we should only do this for non-embedded
1122 # note, however, that we should only do this for non-embedded
1123 # ipythons, which really mimic the __main__.__dict__ with their own
1123 # ipythons, which really mimic the __main__.__dict__ with their own
1124 # namespace. Embedded instances, on the other hand, should not do
1124 # namespace. Embedded instances, on the other hand, should not do
1125 # this because they need to manage the user local/global namespaces
1125 # this because they need to manage the user local/global namespaces
1126 # only, but they live within a 'normal' __main__ (meaning, they
1126 # only, but they live within a 'normal' __main__ (meaning, they
1127 # shouldn't overtake the execution environment of the script they're
1127 # shouldn't overtake the execution environment of the script they're
1128 # embedded in).
1128 # embedded in).
1129
1129
1130 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1130 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1131 main_name = self.user_module.__name__
1131 main_name = self.user_module.__name__
1132 sys.modules[main_name] = self.user_module
1132 sys.modules[main_name] = self.user_module
1133
1133
1134 def init_user_ns(self):
1134 def init_user_ns(self):
1135 """Initialize all user-visible namespaces to their minimum defaults.
1135 """Initialize all user-visible namespaces to their minimum defaults.
1136
1136
1137 Certain history lists are also initialized here, as they effectively
1137 Certain history lists are also initialized here, as they effectively
1138 act as user namespaces.
1138 act as user namespaces.
1139
1139
1140 Notes
1140 Notes
1141 -----
1141 -----
1142 All data structures here are only filled in, they are NOT reset by this
1142 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
1143 method. If they were not empty before, data will simply be added to
1144 therm.
1144 therm.
1145 """
1145 """
1146 # This function works in two parts: first we put a few things in
1146 # 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
1147 # 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
1148 # 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
1149 # 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)
1150 # session (probably nothing, so they really only see their own stuff)
1151
1151
1152 # The user dict must *always* have a __builtin__ reference to the
1152 # The user dict must *always* have a __builtin__ reference to the
1153 # Python standard __builtin__ namespace, which must be imported.
1153 # Python standard __builtin__ namespace, which must be imported.
1154 # This is so that certain operations in prompt evaluation can be
1154 # This is so that certain operations in prompt evaluation can be
1155 # reliably executed with builtins. Note that we can NOT use
1155 # reliably executed with builtins. Note that we can NOT use
1156 # __builtins__ (note the 's'), because that can either be a dict or a
1156 # __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
1157 # module, and can even mutate at runtime, depending on the context
1158 # (Python makes no guarantees on it). In contrast, __builtin__ is
1158 # (Python makes no guarantees on it). In contrast, __builtin__ is
1159 # always a module object, though it must be explicitly imported.
1159 # always a module object, though it must be explicitly imported.
1160
1160
1161 # For more details:
1161 # For more details:
1162 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1162 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1163 ns = {}
1163 ns = {}
1164
1164
1165 # make global variables for user access to the histories
1165 # make global variables for user access to the histories
1166 ns['_ih'] = self.history_manager.input_hist_parsed
1166 ns['_ih'] = self.history_manager.input_hist_parsed
1167 ns['_oh'] = self.history_manager.output_hist
1167 ns['_oh'] = self.history_manager.output_hist
1168 ns['_dh'] = self.history_manager.dir_hist
1168 ns['_dh'] = self.history_manager.dir_hist
1169
1169
1170 # user aliases to input and output histories. These shouldn't show up
1170 # user aliases to input and output histories. These shouldn't show up
1171 # in %who, as they can have very large reprs.
1171 # in %who, as they can have very large reprs.
1172 ns['In'] = self.history_manager.input_hist_parsed
1172 ns['In'] = self.history_manager.input_hist_parsed
1173 ns['Out'] = self.history_manager.output_hist
1173 ns['Out'] = self.history_manager.output_hist
1174
1174
1175 # Store myself as the public api!!!
1175 # Store myself as the public api!!!
1176 ns['get_ipython'] = self.get_ipython
1176 ns['get_ipython'] = self.get_ipython
1177
1177
1178 ns['exit'] = self.exiter
1178 ns['exit'] = self.exiter
1179 ns['quit'] = self.exiter
1179 ns['quit'] = self.exiter
1180
1180
1181 # Sync what we've added so far to user_ns_hidden so these aren't seen
1181 # Sync what we've added so far to user_ns_hidden so these aren't seen
1182 # by %who
1182 # by %who
1183 self.user_ns_hidden.update(ns)
1183 self.user_ns_hidden.update(ns)
1184
1184
1185 # Anything put into ns now would show up in %who. Think twice before
1185 # 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
1186 # putting anything here, as we really want %who to show the user their
1187 # stuff, not our variables.
1187 # stuff, not our variables.
1188
1188
1189 # Finally, update the real user's namespace
1189 # Finally, update the real user's namespace
1190 self.user_ns.update(ns)
1190 self.user_ns.update(ns)
1191
1191
1192 @property
1192 @property
1193 def all_ns_refs(self):
1193 def all_ns_refs(self):
1194 """Get a list of references to all the namespace dictionaries in which
1194 """Get a list of references to all the namespace dictionaries in which
1195 IPython might store a user-created object.
1195 IPython might store a user-created object.
1196
1196
1197 Note that this does not include the displayhook, which also caches
1197 Note that this does not include the displayhook, which also caches
1198 objects from the output."""
1198 objects from the output."""
1199 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1199 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1200 [m.__dict__ for m in self._main_mod_cache.values()]
1200 [m.__dict__ for m in self._main_mod_cache.values()]
1201
1201
1202 def reset(self, new_session=True):
1202 def reset(self, new_session=True):
1203 """Clear all internal namespaces, and attempt to release references to
1203 """Clear all internal namespaces, and attempt to release references to
1204 user objects.
1204 user objects.
1205
1205
1206 If new_session is True, a new history session will be opened.
1206 If new_session is True, a new history session will be opened.
1207 """
1207 """
1208 # Clear histories
1208 # Clear histories
1209 self.history_manager.reset(new_session)
1209 self.history_manager.reset(new_session)
1210 # Reset counter used to index all histories
1210 # Reset counter used to index all histories
1211 if new_session:
1211 if new_session:
1212 self.execution_count = 1
1212 self.execution_count = 1
1213
1213
1214 # Flush cached output items
1214 # Flush cached output items
1215 if self.displayhook.do_full_cache:
1215 if self.displayhook.do_full_cache:
1216 self.displayhook.flush()
1216 self.displayhook.flush()
1217
1217
1218 # The main execution namespaces must be cleared very carefully,
1218 # The main execution namespaces must be cleared very carefully,
1219 # skipping the deletion of the builtin-related keys, because doing so
1219 # skipping the deletion of the builtin-related keys, because doing so
1220 # would cause errors in many object's __del__ methods.
1220 # would cause errors in many object's __del__ methods.
1221 if self.user_ns is not self.user_global_ns:
1221 if self.user_ns is not self.user_global_ns:
1222 self.user_ns.clear()
1222 self.user_ns.clear()
1223 ns = self.user_global_ns
1223 ns = self.user_global_ns
1224 drop_keys = set(ns.keys())
1224 drop_keys = set(ns.keys())
1225 drop_keys.discard('__builtin__')
1225 drop_keys.discard('__builtin__')
1226 drop_keys.discard('__builtins__')
1226 drop_keys.discard('__builtins__')
1227 drop_keys.discard('__name__')
1227 drop_keys.discard('__name__')
1228 for k in drop_keys:
1228 for k in drop_keys:
1229 del ns[k]
1229 del ns[k]
1230
1230
1231 self.user_ns_hidden.clear()
1231 self.user_ns_hidden.clear()
1232
1232
1233 # Restore the user namespaces to minimal usability
1233 # Restore the user namespaces to minimal usability
1234 self.init_user_ns()
1234 self.init_user_ns()
1235
1235
1236 # Restore the default and user aliases
1236 # Restore the default and user aliases
1237 self.alias_manager.clear_aliases()
1237 self.alias_manager.clear_aliases()
1238 self.alias_manager.init_aliases()
1238 self.alias_manager.init_aliases()
1239
1239
1240 # Flush the private list of module references kept for script
1240 # Flush the private list of module references kept for script
1241 # execution protection
1241 # execution protection
1242 self.clear_main_mod_cache()
1242 self.clear_main_mod_cache()
1243
1243
1244 def del_var(self, varname, by_name=False):
1244 def del_var(self, varname, by_name=False):
1245 """Delete a variable from the various namespaces, so that, as
1245 """Delete a variable from the various namespaces, so that, as
1246 far as possible, we're not keeping any hidden references to it.
1246 far as possible, we're not keeping any hidden references to it.
1247
1247
1248 Parameters
1248 Parameters
1249 ----------
1249 ----------
1250 varname : str
1250 varname : str
1251 The name of the variable to delete.
1251 The name of the variable to delete.
1252 by_name : bool
1252 by_name : bool
1253 If True, delete variables with the given name in each
1253 If True, delete variables with the given name in each
1254 namespace. If False (default), find the variable in the user
1254 namespace. If False (default), find the variable in the user
1255 namespace, and delete references to it.
1255 namespace, and delete references to it.
1256 """
1256 """
1257 if varname in ('__builtin__', '__builtins__'):
1257 if varname in ('__builtin__', '__builtins__'):
1258 raise ValueError("Refusing to delete %s" % varname)
1258 raise ValueError("Refusing to delete %s" % varname)
1259
1259
1260 ns_refs = self.all_ns_refs
1260 ns_refs = self.all_ns_refs
1261
1261
1262 if by_name: # Delete by name
1262 if by_name: # Delete by name
1263 for ns in ns_refs:
1263 for ns in ns_refs:
1264 try:
1264 try:
1265 del ns[varname]
1265 del ns[varname]
1266 except KeyError:
1266 except KeyError:
1267 pass
1267 pass
1268 else: # Delete by object
1268 else: # Delete by object
1269 try:
1269 try:
1270 obj = self.user_ns[varname]
1270 obj = self.user_ns[varname]
1271 except KeyError:
1271 except KeyError:
1272 raise NameError("name '%s' is not defined" % varname)
1272 raise NameError("name '%s' is not defined" % varname)
1273 # Also check in output history
1273 # Also check in output history
1274 ns_refs.append(self.history_manager.output_hist)
1274 ns_refs.append(self.history_manager.output_hist)
1275 for ns in ns_refs:
1275 for ns in ns_refs:
1276 to_delete = [n for n, o in ns.items() if o is obj]
1276 to_delete = [n for n, o in ns.items() if o is obj]
1277 for name in to_delete:
1277 for name in to_delete:
1278 del ns[name]
1278 del ns[name]
1279
1279
1280 # displayhook keeps extra references, but not in a dictionary
1280 # displayhook keeps extra references, but not in a dictionary
1281 for name in ('_', '__', '___'):
1281 for name in ('_', '__', '___'):
1282 if getattr(self.displayhook, name) is obj:
1282 if getattr(self.displayhook, name) is obj:
1283 setattr(self.displayhook, name, None)
1283 setattr(self.displayhook, name, None)
1284
1284
1285 def reset_selective(self, regex=None):
1285 def reset_selective(self, regex=None):
1286 """Clear selective variables from internal namespaces based on a
1286 """Clear selective variables from internal namespaces based on a
1287 specified regular expression.
1287 specified regular expression.
1288
1288
1289 Parameters
1289 Parameters
1290 ----------
1290 ----------
1291 regex : string or compiled pattern, optional
1291 regex : string or compiled pattern, optional
1292 A regular expression pattern that will be used in searching
1292 A regular expression pattern that will be used in searching
1293 variable names in the users namespaces.
1293 variable names in the users namespaces.
1294 """
1294 """
1295 if regex is not None:
1295 if regex is not None:
1296 try:
1296 try:
1297 m = re.compile(regex)
1297 m = re.compile(regex)
1298 except TypeError:
1298 except TypeError:
1299 raise TypeError('regex must be a string or compiled pattern')
1299 raise TypeError('regex must be a string or compiled pattern')
1300 # Search for keys in each namespace that match the given regex
1300 # Search for keys in each namespace that match the given regex
1301 # If a match is found, delete the key/value pair.
1301 # If a match is found, delete the key/value pair.
1302 for ns in self.all_ns_refs:
1302 for ns in self.all_ns_refs:
1303 for var in ns:
1303 for var in ns:
1304 if m.search(var):
1304 if m.search(var):
1305 del ns[var]
1305 del ns[var]
1306
1306
1307 def push(self, variables, interactive=True):
1307 def push(self, variables, interactive=True):
1308 """Inject a group of variables into the IPython user namespace.
1308 """Inject a group of variables into the IPython user namespace.
1309
1309
1310 Parameters
1310 Parameters
1311 ----------
1311 ----------
1312 variables : dict, str or list/tuple of str
1312 variables : dict, str or list/tuple of str
1313 The variables to inject into the user's namespace. If a dict, a
1313 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
1314 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
1315 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
1316 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
1317 give (list/tuple/str) then the variable values looked up in the
1318 callers frame.
1318 callers frame.
1319 interactive : bool
1319 interactive : bool
1320 If True (default), the variables will be listed with the ``who``
1320 If True (default), the variables will be listed with the ``who``
1321 magic.
1321 magic.
1322 """
1322 """
1323 vdict = None
1323 vdict = None
1324
1324
1325 # We need a dict of name/value pairs to do namespace updates.
1325 # We need a dict of name/value pairs to do namespace updates.
1326 if isinstance(variables, dict):
1326 if isinstance(variables, dict):
1327 vdict = variables
1327 vdict = variables
1328 elif isinstance(variables, (str, list, tuple)):
1328 elif isinstance(variables, (str, list, tuple)):
1329 if isinstance(variables, str):
1329 if isinstance(variables, str):
1330 vlist = variables.split()
1330 vlist = variables.split()
1331 else:
1331 else:
1332 vlist = variables
1332 vlist = variables
1333 vdict = {}
1333 vdict = {}
1334 cf = sys._getframe(1)
1334 cf = sys._getframe(1)
1335 for name in vlist:
1335 for name in vlist:
1336 try:
1336 try:
1337 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1337 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1338 except:
1338 except:
1339 print('Could not get variable %s from %s' %
1339 print('Could not get variable %s from %s' %
1340 (name,cf.f_code.co_name))
1340 (name,cf.f_code.co_name))
1341 else:
1341 else:
1342 raise ValueError('variables must be a dict/str/list/tuple')
1342 raise ValueError('variables must be a dict/str/list/tuple')
1343
1343
1344 # Propagate variables to user namespace
1344 # Propagate variables to user namespace
1345 self.user_ns.update(vdict)
1345 self.user_ns.update(vdict)
1346
1346
1347 # And configure interactive visibility
1347 # And configure interactive visibility
1348 user_ns_hidden = self.user_ns_hidden
1348 user_ns_hidden = self.user_ns_hidden
1349 if interactive:
1349 if interactive:
1350 for name in vdict:
1350 for name in vdict:
1351 user_ns_hidden.pop(name, None)
1351 user_ns_hidden.pop(name, None)
1352 else:
1352 else:
1353 user_ns_hidden.update(vdict)
1353 user_ns_hidden.update(vdict)
1354
1354
1355 def drop_by_id(self, variables):
1355 def drop_by_id(self, variables):
1356 """Remove a dict of variables from the user namespace, if they are the
1356 """Remove a dict of variables from the user namespace, if they are the
1357 same as the values in the dictionary.
1357 same as the values in the dictionary.
1358
1358
1359 This is intended for use by extensions: variables that they've added can
1359 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
1360 be taken back out if they are unloaded, without removing any that the
1361 user has overwritten.
1361 user has overwritten.
1362
1362
1363 Parameters
1363 Parameters
1364 ----------
1364 ----------
1365 variables : dict
1365 variables : dict
1366 A dictionary mapping object names (as strings) to the objects.
1366 A dictionary mapping object names (as strings) to the objects.
1367 """
1367 """
1368 for name, obj in variables.items():
1368 for name, obj in variables.items():
1369 if name in self.user_ns and self.user_ns[name] is obj:
1369 if name in self.user_ns and self.user_ns[name] is obj:
1370 del self.user_ns[name]
1370 del self.user_ns[name]
1371 self.user_ns_hidden.pop(name, None)
1371 self.user_ns_hidden.pop(name, None)
1372
1372
1373 #-------------------------------------------------------------------------
1373 #-------------------------------------------------------------------------
1374 # Things related to object introspection
1374 # Things related to object introspection
1375 #-------------------------------------------------------------------------
1375 #-------------------------------------------------------------------------
1376
1376
1377 def _ofind(self, oname, namespaces=None):
1377 def _ofind(self, oname, namespaces=None):
1378 """Find an object in the available namespaces.
1378 """Find an object in the available namespaces.
1379
1379
1380 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1380 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1381
1381
1382 Has special code to detect magic functions.
1382 Has special code to detect magic functions.
1383 """
1383 """
1384 oname = oname.strip()
1384 oname = oname.strip()
1385 if not oname.startswith(ESC_MAGIC) and \
1385 if not oname.startswith(ESC_MAGIC) and \
1386 not oname.startswith(ESC_MAGIC2) and \
1386 not oname.startswith(ESC_MAGIC2) and \
1387 not all(a.isidentifier() for a in oname.split(".")):
1387 not all(a.isidentifier() for a in oname.split(".")):
1388 return {'found': False}
1388 return {'found': False}
1389
1389
1390 if namespaces is None:
1390 if namespaces is None:
1391 # Namespaces to search in:
1391 # Namespaces to search in:
1392 # Put them in a list. The order is important so that we
1392 # Put them in a list. The order is important so that we
1393 # find things in the same order that Python finds them.
1393 # find things in the same order that Python finds them.
1394 namespaces = [ ('Interactive', self.user_ns),
1394 namespaces = [ ('Interactive', self.user_ns),
1395 ('Interactive (global)', self.user_global_ns),
1395 ('Interactive (global)', self.user_global_ns),
1396 ('Python builtin', builtin_mod.__dict__),
1396 ('Python builtin', builtin_mod.__dict__),
1397 ]
1397 ]
1398
1398
1399 ismagic = False
1399 ismagic = False
1400 isalias = False
1400 isalias = False
1401 found = False
1401 found = False
1402 ospace = None
1402 ospace = None
1403 parent = None
1403 parent = None
1404 obj = None
1404 obj = None
1405
1405
1406 # Look for the given name by splitting it in parts. If the head is
1406 # 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
1407 # found, then we look for all the remaining parts as members, and only
1408 # declare success if we can find them all.
1408 # declare success if we can find them all.
1409 oname_parts = oname.split('.')
1409 oname_parts = oname.split('.')
1410 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1410 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1411 for nsname,ns in namespaces:
1411 for nsname,ns in namespaces:
1412 try:
1412 try:
1413 obj = ns[oname_head]
1413 obj = ns[oname_head]
1414 except KeyError:
1414 except KeyError:
1415 continue
1415 continue
1416 else:
1416 else:
1417 for idx, part in enumerate(oname_rest):
1417 for idx, part in enumerate(oname_rest):
1418 try:
1418 try:
1419 parent = obj
1419 parent = obj
1420 # The last part is looked up in a special way to avoid
1420 # The last part is looked up in a special way to avoid
1421 # descriptor invocation as it may raise or have side
1421 # descriptor invocation as it may raise or have side
1422 # effects.
1422 # effects.
1423 if idx == len(oname_rest) - 1:
1423 if idx == len(oname_rest) - 1:
1424 obj = self._getattr_property(obj, part)
1424 obj = self._getattr_property(obj, part)
1425 else:
1425 else:
1426 obj = getattr(obj, part)
1426 obj = getattr(obj, part)
1427 except:
1427 except:
1428 # Blanket except b/c some badly implemented objects
1428 # Blanket except b/c some badly implemented objects
1429 # allow __getattr__ to raise exceptions other than
1429 # allow __getattr__ to raise exceptions other than
1430 # AttributeError, which then crashes IPython.
1430 # AttributeError, which then crashes IPython.
1431 break
1431 break
1432 else:
1432 else:
1433 # If we finish the for loop (no break), we got all members
1433 # If we finish the for loop (no break), we got all members
1434 found = True
1434 found = True
1435 ospace = nsname
1435 ospace = nsname
1436 break # namespace loop
1436 break # namespace loop
1437
1437
1438 # Try to see if it's magic
1438 # Try to see if it's magic
1439 if not found:
1439 if not found:
1440 obj = None
1440 obj = None
1441 if oname.startswith(ESC_MAGIC2):
1441 if oname.startswith(ESC_MAGIC2):
1442 oname = oname.lstrip(ESC_MAGIC2)
1442 oname = oname.lstrip(ESC_MAGIC2)
1443 obj = self.find_cell_magic(oname)
1443 obj = self.find_cell_magic(oname)
1444 elif oname.startswith(ESC_MAGIC):
1444 elif oname.startswith(ESC_MAGIC):
1445 oname = oname.lstrip(ESC_MAGIC)
1445 oname = oname.lstrip(ESC_MAGIC)
1446 obj = self.find_line_magic(oname)
1446 obj = self.find_line_magic(oname)
1447 else:
1447 else:
1448 # search without prefix, so run? will find %run?
1448 # search without prefix, so run? will find %run?
1449 obj = self.find_line_magic(oname)
1449 obj = self.find_line_magic(oname)
1450 if obj is None:
1450 if obj is None:
1451 obj = self.find_cell_magic(oname)
1451 obj = self.find_cell_magic(oname)
1452 if obj is not None:
1452 if obj is not None:
1453 found = True
1453 found = True
1454 ospace = 'IPython internal'
1454 ospace = 'IPython internal'
1455 ismagic = True
1455 ismagic = True
1456 isalias = isinstance(obj, Alias)
1456 isalias = isinstance(obj, Alias)
1457
1457
1458 # Last try: special-case some literals like '', [], {}, etc:
1458 # Last try: special-case some literals like '', [], {}, etc:
1459 if not found and oname_head in ["''",'""','[]','{}','()']:
1459 if not found and oname_head in ["''",'""','[]','{}','()']:
1460 obj = eval(oname_head)
1460 obj = eval(oname_head)
1461 found = True
1461 found = True
1462 ospace = 'Interactive'
1462 ospace = 'Interactive'
1463
1463
1464 return {
1464 return {
1465 'obj':obj,
1465 'obj':obj,
1466 'found':found,
1466 'found':found,
1467 'parent':parent,
1467 'parent':parent,
1468 'ismagic':ismagic,
1468 'ismagic':ismagic,
1469 'isalias':isalias,
1469 'isalias':isalias,
1470 'namespace':ospace
1470 'namespace':ospace
1471 }
1471 }
1472
1472
1473 @staticmethod
1473 @staticmethod
1474 def _getattr_property(obj, attrname):
1474 def _getattr_property(obj, attrname):
1475 """Property-aware getattr to use in object finding.
1475 """Property-aware getattr to use in object finding.
1476
1476
1477 If attrname represents a property, return it unevaluated (in case it has
1477 If attrname represents a property, return it unevaluated (in case it has
1478 side effects or raises an error.
1478 side effects or raises an error.
1479
1479
1480 """
1480 """
1481 if not isinstance(obj, type):
1481 if not isinstance(obj, type):
1482 try:
1482 try:
1483 # `getattr(type(obj), attrname)` is not guaranteed to return
1483 # `getattr(type(obj), attrname)` is not guaranteed to return
1484 # `obj`, but does so for property:
1484 # `obj`, but does so for property:
1485 #
1485 #
1486 # property.__get__(self, None, cls) -> self
1486 # property.__get__(self, None, cls) -> self
1487 #
1487 #
1488 # The universal alternative is to traverse the mro manually
1488 # The universal alternative is to traverse the mro manually
1489 # searching for attrname in class dicts.
1489 # searching for attrname in class dicts.
1490 attr = getattr(type(obj), attrname)
1490 attr = getattr(type(obj), attrname)
1491 except AttributeError:
1491 except AttributeError:
1492 pass
1492 pass
1493 else:
1493 else:
1494 # This relies on the fact that data descriptors (with both
1494 # This relies on the fact that data descriptors (with both
1495 # __get__ & __set__ magic methods) take precedence over
1495 # __get__ & __set__ magic methods) take precedence over
1496 # instance-level attributes:
1496 # instance-level attributes:
1497 #
1497 #
1498 # class A(object):
1498 # class A(object):
1499 # @property
1499 # @property
1500 # def foobar(self): return 123
1500 # def foobar(self): return 123
1501 # a = A()
1501 # a = A()
1502 # a.__dict__['foobar'] = 345
1502 # a.__dict__['foobar'] = 345
1503 # a.foobar # == 123
1503 # a.foobar # == 123
1504 #
1504 #
1505 # So, a property may be returned right away.
1505 # So, a property may be returned right away.
1506 if isinstance(attr, property):
1506 if isinstance(attr, property):
1507 return attr
1507 return attr
1508
1508
1509 # Nothing helped, fall back.
1509 # Nothing helped, fall back.
1510 return getattr(obj, attrname)
1510 return getattr(obj, attrname)
1511
1511
1512 def _object_find(self, oname, namespaces=None):
1512 def _object_find(self, oname, namespaces=None):
1513 """Find an object and return a struct with info about it."""
1513 """Find an object and return a struct with info about it."""
1514 return Struct(self._ofind(oname, namespaces))
1514 return Struct(self._ofind(oname, namespaces))
1515
1515
1516 def _inspect(self, meth, oname, namespaces=None, **kw):
1516 def _inspect(self, meth, oname, namespaces=None, **kw):
1517 """Generic interface to the inspector system.
1517 """Generic interface to the inspector system.
1518
1518
1519 This function is meant to be called by pdef, pdoc & friends.
1519 This function is meant to be called by pdef, pdoc & friends.
1520 """
1520 """
1521 info = self._object_find(oname, namespaces)
1521 info = self._object_find(oname, namespaces)
1522 docformat = sphinxify if self.sphinxify_docstring else None
1522 docformat = sphinxify if self.sphinxify_docstring else None
1523 if info.found:
1523 if info.found:
1524 pmethod = getattr(self.inspector, meth)
1524 pmethod = getattr(self.inspector, meth)
1525 # TODO: only apply format_screen to the plain/text repr of the mime
1525 # TODO: only apply format_screen to the plain/text repr of the mime
1526 # bundle.
1526 # bundle.
1527 formatter = format_screen if info.ismagic else docformat
1527 formatter = format_screen if info.ismagic else docformat
1528 if meth == 'pdoc':
1528 if meth == 'pdoc':
1529 pmethod(info.obj, oname, formatter)
1529 pmethod(info.obj, oname, formatter)
1530 elif meth == 'pinfo':
1530 elif meth == 'pinfo':
1531 pmethod(info.obj, oname, formatter, info,
1531 pmethod(info.obj, oname, formatter, info,
1532 enable_html_pager=self.enable_html_pager, **kw)
1532 enable_html_pager=self.enable_html_pager, **kw)
1533 else:
1533 else:
1534 pmethod(info.obj, oname)
1534 pmethod(info.obj, oname)
1535 else:
1535 else:
1536 print('Object `%s` not found.' % oname)
1536 print('Object `%s` not found.' % oname)
1537 return 'not found' # so callers can take other action
1537 return 'not found' # so callers can take other action
1538
1538
1539 def object_inspect(self, oname, detail_level=0):
1539 def object_inspect(self, oname, detail_level=0):
1540 """Get object info about oname"""
1540 """Get object info about oname"""
1541 with self.builtin_trap:
1541 with self.builtin_trap:
1542 info = self._object_find(oname)
1542 info = self._object_find(oname)
1543 if info.found:
1543 if info.found:
1544 return self.inspector.info(info.obj, oname, info=info,
1544 return self.inspector.info(info.obj, oname, info=info,
1545 detail_level=detail_level
1545 detail_level=detail_level
1546 )
1546 )
1547 else:
1547 else:
1548 return oinspect.object_info(name=oname, found=False)
1548 return oinspect.object_info(name=oname, found=False)
1549
1549
1550 def object_inspect_text(self, oname, detail_level=0):
1550 def object_inspect_text(self, oname, detail_level=0):
1551 """Get object info as formatted text"""
1551 """Get object info as formatted text"""
1552 return self.object_inspect_mime(oname, detail_level)['text/plain']
1552 return self.object_inspect_mime(oname, detail_level)['text/plain']
1553
1553
1554 def object_inspect_mime(self, oname, detail_level=0):
1554 def object_inspect_mime(self, oname, detail_level=0):
1555 """Get object info as a mimebundle of formatted representations.
1555 """Get object info as a mimebundle of formatted representations.
1556
1556
1557 A mimebundle is a dictionary, keyed by mime-type.
1557 A mimebundle is a dictionary, keyed by mime-type.
1558 It must always have the key `'text/plain'`.
1558 It must always have the key `'text/plain'`.
1559 """
1559 """
1560 with self.builtin_trap:
1560 with self.builtin_trap:
1561 info = self._object_find(oname)
1561 info = self._object_find(oname)
1562 if info.found:
1562 if info.found:
1563 return self.inspector._get_info(info.obj, oname, info=info,
1563 return self.inspector._get_info(info.obj, oname, info=info,
1564 detail_level=detail_level
1564 detail_level=detail_level
1565 )
1565 )
1566 else:
1566 else:
1567 raise KeyError(oname)
1567 raise KeyError(oname)
1568
1568
1569 #-------------------------------------------------------------------------
1569 #-------------------------------------------------------------------------
1570 # Things related to history management
1570 # Things related to history management
1571 #-------------------------------------------------------------------------
1571 #-------------------------------------------------------------------------
1572
1572
1573 def init_history(self):
1573 def init_history(self):
1574 """Sets up the command history, and starts regular autosaves."""
1574 """Sets up the command history, and starts regular autosaves."""
1575 self.history_manager = HistoryManager(shell=self, parent=self)
1575 self.history_manager = HistoryManager(shell=self, parent=self)
1576 self.configurables.append(self.history_manager)
1576 self.configurables.append(self.history_manager)
1577
1577
1578 #-------------------------------------------------------------------------
1578 #-------------------------------------------------------------------------
1579 # Things related to exception handling and tracebacks (not debugging)
1579 # Things related to exception handling and tracebacks (not debugging)
1580 #-------------------------------------------------------------------------
1580 #-------------------------------------------------------------------------
1581
1581
1582 debugger_cls = Pdb
1582 debugger_cls = Pdb
1583
1583
1584 def init_traceback_handlers(self, custom_exceptions):
1584 def init_traceback_handlers(self, custom_exceptions):
1585 # Syntax error handler.
1585 # Syntax error handler.
1586 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1586 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1587
1587
1588 # The interactive one is initialized with an offset, meaning we always
1588 # 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
1589 # want to remove the topmost item in the traceback, which is our own
1590 # internal code. Valid modes: ['Plain','Context','Verbose']
1590 # internal code. Valid modes: ['Plain','Context','Verbose']
1591 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1591 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1592 color_scheme='NoColor',
1592 color_scheme='NoColor',
1593 tb_offset = 1,
1593 tb_offset = 1,
1594 check_cache=check_linecache_ipython,
1594 check_cache=check_linecache_ipython,
1595 debugger_cls=self.debugger_cls, parent=self)
1595 debugger_cls=self.debugger_cls, parent=self)
1596
1596
1597 # The instance will store a pointer to the system-wide exception hook,
1597 # 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
1598 # so that runtime code (such as magics) can access it. This is because
1599 # during the read-eval loop, it may get temporarily overwritten.
1599 # during the read-eval loop, it may get temporarily overwritten.
1600 self.sys_excepthook = sys.excepthook
1600 self.sys_excepthook = sys.excepthook
1601
1601
1602 # and add any custom exception handlers the user may have specified
1602 # and add any custom exception handlers the user may have specified
1603 self.set_custom_exc(*custom_exceptions)
1603 self.set_custom_exc(*custom_exceptions)
1604
1604
1605 # Set the exception mode
1605 # Set the exception mode
1606 self.InteractiveTB.set_mode(mode=self.xmode)
1606 self.InteractiveTB.set_mode(mode=self.xmode)
1607
1607
1608 def set_custom_exc(self, exc_tuple, handler):
1608 def set_custom_exc(self, exc_tuple, handler):
1609 """set_custom_exc(exc_tuple, handler)
1609 """set_custom_exc(exc_tuple, handler)
1610
1610
1611 Set a custom exception handler, which will be called if any of the
1611 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
1612 exceptions in exc_tuple occur in the mainloop (specifically, in the
1613 run_code() method).
1613 run_code() method).
1614
1614
1615 Parameters
1615 Parameters
1616 ----------
1616 ----------
1617
1617
1618 exc_tuple : tuple of exception classes
1618 exc_tuple : tuple of exception classes
1619 A *tuple* of exception classes, for which to call the defined
1619 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
1620 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
1621 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::
1622 you only want to trap a single exception, use a singleton tuple::
1623
1623
1624 exc_tuple == (MyCustomException,)
1624 exc_tuple == (MyCustomException,)
1625
1625
1626 handler : callable
1626 handler : callable
1627 handler must have the following signature::
1627 handler must have the following signature::
1628
1628
1629 def my_handler(self, etype, value, tb, tb_offset=None):
1629 def my_handler(self, etype, value, tb, tb_offset=None):
1630 ...
1630 ...
1631 return structured_traceback
1631 return structured_traceback
1632
1632
1633 Your handler must return a structured traceback (a list of strings),
1633 Your handler must return a structured traceback (a list of strings),
1634 or None.
1634 or None.
1635
1635
1636 This will be made into an instance method (via types.MethodType)
1636 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
1637 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
1638 listed in the exc_tuple are caught. If the handler is None, an
1639 internal basic one is used, which just prints basic info.
1639 internal basic one is used, which just prints basic info.
1640
1640
1641 To protect IPython from crashes, if your handler ever raises an
1641 To protect IPython from crashes, if your handler ever raises an
1642 exception or returns an invalid result, it will be immediately
1642 exception or returns an invalid result, it will be immediately
1643 disabled.
1643 disabled.
1644
1644
1645 WARNING: by putting in your own exception handler into IPython's main
1645 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
1646 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."""
1647 facility should only be used if you really know what you are doing."""
1648 if not isinstance(exc_tuple, tuple):
1648 if not isinstance(exc_tuple, tuple):
1649 raise TypeError("The custom exceptions must be given as a tuple.")
1649 raise TypeError("The custom exceptions must be given as a tuple.")
1650
1650
1651 def dummy_handler(self, etype, value, tb, tb_offset=None):
1651 def dummy_handler(self, etype, value, tb, tb_offset=None):
1652 print('*** Simple custom exception handler ***')
1652 print('*** Simple custom exception handler ***')
1653 print('Exception type :', etype)
1653 print('Exception type :', etype)
1654 print('Exception value:', value)
1654 print('Exception value:', value)
1655 print('Traceback :', tb)
1655 print('Traceback :', tb)
1656
1656
1657 def validate_stb(stb):
1657 def validate_stb(stb):
1658 """validate structured traceback return type
1658 """validate structured traceback return type
1659
1659
1660 return type of CustomTB *should* be a list of strings, but allow
1660 return type of CustomTB *should* be a list of strings, but allow
1661 single strings or None, which are harmless.
1661 single strings or None, which are harmless.
1662
1662
1663 This function will *always* return a list of strings,
1663 This function will *always* return a list of strings,
1664 and will raise a TypeError if stb is inappropriate.
1664 and will raise a TypeError if stb is inappropriate.
1665 """
1665 """
1666 msg = "CustomTB must return list of strings, not %r" % stb
1666 msg = "CustomTB must return list of strings, not %r" % stb
1667 if stb is None:
1667 if stb is None:
1668 return []
1668 return []
1669 elif isinstance(stb, str):
1669 elif isinstance(stb, str):
1670 return [stb]
1670 return [stb]
1671 elif not isinstance(stb, list):
1671 elif not isinstance(stb, list):
1672 raise TypeError(msg)
1672 raise TypeError(msg)
1673 # it's a list
1673 # it's a list
1674 for line in stb:
1674 for line in stb:
1675 # check every element
1675 # check every element
1676 if not isinstance(line, str):
1676 if not isinstance(line, str):
1677 raise TypeError(msg)
1677 raise TypeError(msg)
1678 return stb
1678 return stb
1679
1679
1680 if handler is None:
1680 if handler is None:
1681 wrapped = dummy_handler
1681 wrapped = dummy_handler
1682 else:
1682 else:
1683 def wrapped(self,etype,value,tb,tb_offset=None):
1683 def wrapped(self,etype,value,tb,tb_offset=None):
1684 """wrap CustomTB handler, to protect IPython from user code
1684 """wrap CustomTB handler, to protect IPython from user code
1685
1685
1686 This makes it harder (but not impossible) for custom exception
1686 This makes it harder (but not impossible) for custom exception
1687 handlers to crash IPython.
1687 handlers to crash IPython.
1688 """
1688 """
1689 try:
1689 try:
1690 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1690 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1691 return validate_stb(stb)
1691 return validate_stb(stb)
1692 except:
1692 except:
1693 # clear custom handler immediately
1693 # clear custom handler immediately
1694 self.set_custom_exc((), None)
1694 self.set_custom_exc((), None)
1695 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1695 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1696 # show the exception in handler first
1696 # show the exception in handler first
1697 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1697 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1698 print(self.InteractiveTB.stb2text(stb))
1698 print(self.InteractiveTB.stb2text(stb))
1699 print("The original exception:")
1699 print("The original exception:")
1700 stb = self.InteractiveTB.structured_traceback(
1700 stb = self.InteractiveTB.structured_traceback(
1701 (etype,value,tb), tb_offset=tb_offset
1701 (etype,value,tb), tb_offset=tb_offset
1702 )
1702 )
1703 return stb
1703 return stb
1704
1704
1705 self.CustomTB = types.MethodType(wrapped,self)
1705 self.CustomTB = types.MethodType(wrapped,self)
1706 self.custom_exceptions = exc_tuple
1706 self.custom_exceptions = exc_tuple
1707
1707
1708 def excepthook(self, etype, value, tb):
1708 def excepthook(self, etype, value, tb):
1709 """One more defense for GUI apps that call sys.excepthook.
1709 """One more defense for GUI apps that call sys.excepthook.
1710
1710
1711 GUI frameworks like wxPython trap exceptions and call
1711 GUI frameworks like wxPython trap exceptions and call
1712 sys.excepthook themselves. I guess this is a feature that
1712 sys.excepthook themselves. I guess this is a feature that
1713 enables them to keep running after exceptions that would
1713 enables them to keep running after exceptions that would
1714 otherwise kill their mainloop. This is a bother for IPython
1714 otherwise kill their mainloop. This is a bother for IPython
1715 which excepts to catch all of the program exceptions with a try:
1715 which excepts to catch all of the program exceptions with a try:
1716 except: statement.
1716 except: statement.
1717
1717
1718 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1718 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
1719 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
1720 IPython crashed. In order to work around this, we can disable the
1721 CrashHandler and replace it with this excepthook instead, which prints a
1721 CrashHandler and replace it with this excepthook instead, which prints a
1722 regular traceback using our InteractiveTB. In this fashion, apps which
1722 regular traceback using our InteractiveTB. In this fashion, apps which
1723 call sys.excepthook will generate a regular-looking exception from
1723 call sys.excepthook will generate a regular-looking exception from
1724 IPython, and the CrashHandler will only be triggered by real IPython
1724 IPython, and the CrashHandler will only be triggered by real IPython
1725 crashes.
1725 crashes.
1726
1726
1727 This hook should be used sparingly, only in places which are not likely
1727 This hook should be used sparingly, only in places which are not likely
1728 to be true IPython errors.
1728 to be true IPython errors.
1729 """
1729 """
1730 self.showtraceback((etype, value, tb), tb_offset=0)
1730 self.showtraceback((etype, value, tb), tb_offset=0)
1731
1731
1732 def _get_exc_info(self, exc_tuple=None):
1732 def _get_exc_info(self, exc_tuple=None):
1733 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1733 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1734
1734
1735 Ensures sys.last_type,value,traceback hold the exc_info we found,
1735 Ensures sys.last_type,value,traceback hold the exc_info we found,
1736 from whichever source.
1736 from whichever source.
1737
1737
1738 raises ValueError if none of these contain any information
1738 raises ValueError if none of these contain any information
1739 """
1739 """
1740 if exc_tuple is None:
1740 if exc_tuple is None:
1741 etype, value, tb = sys.exc_info()
1741 etype, value, tb = sys.exc_info()
1742 else:
1742 else:
1743 etype, value, tb = exc_tuple
1743 etype, value, tb = exc_tuple
1744
1744
1745 if etype is None:
1745 if etype is None:
1746 if hasattr(sys, 'last_type'):
1746 if hasattr(sys, 'last_type'):
1747 etype, value, tb = sys.last_type, sys.last_value, \
1747 etype, value, tb = sys.last_type, sys.last_value, \
1748 sys.last_traceback
1748 sys.last_traceback
1749
1749
1750 if etype is None:
1750 if etype is None:
1751 raise ValueError("No exception to find")
1751 raise ValueError("No exception to find")
1752
1752
1753 # Now store the exception info in sys.last_type etc.
1753 # Now store the exception info in sys.last_type etc.
1754 # WARNING: these variables are somewhat deprecated and not
1754 # WARNING: these variables are somewhat deprecated and not
1755 # necessarily safe to use in a threaded environment, but tools
1755 # necessarily safe to use in a threaded environment, but tools
1756 # like pdb depend on their existence, so let's set them. If we
1756 # 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.
1757 # find problems in the field, we'll need to revisit their use.
1758 sys.last_type = etype
1758 sys.last_type = etype
1759 sys.last_value = value
1759 sys.last_value = value
1760 sys.last_traceback = tb
1760 sys.last_traceback = tb
1761
1761
1762 return etype, value, tb
1762 return etype, value, tb
1763
1763
1764 def show_usage_error(self, exc):
1764 def show_usage_error(self, exc):
1765 """Show a short message for UsageErrors
1765 """Show a short message for UsageErrors
1766
1766
1767 These are special exceptions that shouldn't show a traceback.
1767 These are special exceptions that shouldn't show a traceback.
1768 """
1768 """
1769 print("UsageError: %s" % exc, file=sys.stderr)
1769 print("UsageError: %s" % exc, file=sys.stderr)
1770
1770
1771 def get_exception_only(self, exc_tuple=None):
1771 def get_exception_only(self, exc_tuple=None):
1772 """
1772 """
1773 Return as a string (ending with a newline) the exception that
1773 Return as a string (ending with a newline) the exception that
1774 just occurred, without any traceback.
1774 just occurred, without any traceback.
1775 """
1775 """
1776 etype, value, tb = self._get_exc_info(exc_tuple)
1776 etype, value, tb = self._get_exc_info(exc_tuple)
1777 msg = traceback.format_exception_only(etype, value)
1777 msg = traceback.format_exception_only(etype, value)
1778 return ''.join(msg)
1778 return ''.join(msg)
1779
1779
1780 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1780 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1781 exception_only=False, running_compiled_code=False):
1781 exception_only=False, running_compiled_code=False):
1782 """Display the exception that just occurred.
1782 """Display the exception that just occurred.
1783
1783
1784 If nothing is known about the exception, this is the method which
1784 If nothing is known about the exception, this is the method which
1785 should be used throughout the code for presenting user tracebacks,
1785 should be used throughout the code for presenting user tracebacks,
1786 rather than directly invoking the InteractiveTB object.
1786 rather than directly invoking the InteractiveTB object.
1787
1787
1788 A specific showsyntaxerror() also exists, but this method can take
1788 A specific showsyntaxerror() also exists, but this method can take
1789 care of calling it if needed, so unless you are explicitly catching a
1789 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
1790 SyntaxError exception, don't try to analyze the stack manually and
1791 simply call this method."""
1791 simply call this method."""
1792
1792
1793 try:
1793 try:
1794 try:
1794 try:
1795 etype, value, tb = self._get_exc_info(exc_tuple)
1795 etype, value, tb = self._get_exc_info(exc_tuple)
1796 except ValueError:
1796 except ValueError:
1797 print('No traceback available to show.', file=sys.stderr)
1797 print('No traceback available to show.', file=sys.stderr)
1798 return
1798 return
1799
1799
1800 if issubclass(etype, SyntaxError):
1800 if issubclass(etype, SyntaxError):
1801 # Though this won't be called by syntax errors in the input
1801 # Though this won't be called by syntax errors in the input
1802 # line, there may be SyntaxError cases with imported code.
1802 # line, there may be SyntaxError cases with imported code.
1803 self.showsyntaxerror(filename, running_compiled_code)
1803 self.showsyntaxerror(filename, running_compiled_code)
1804 elif etype is UsageError:
1804 elif etype is UsageError:
1805 self.show_usage_error(value)
1805 self.show_usage_error(value)
1806 else:
1806 else:
1807 if exception_only:
1807 if exception_only:
1808 stb = ['An exception has occurred, use %tb to see '
1808 stb = ['An exception has occurred, use %tb to see '
1809 'the full traceback.\n']
1809 'the full traceback.\n']
1810 stb.extend(self.InteractiveTB.get_exception_only(etype,
1810 stb.extend(self.InteractiveTB.get_exception_only(etype,
1811 value))
1811 value))
1812 else:
1812 else:
1813 try:
1813 try:
1814 # Exception classes can customise their traceback - we
1814 # Exception classes can customise their traceback - we
1815 # use this in IPython.parallel for exceptions occurring
1815 # use this in IPython.parallel for exceptions occurring
1816 # in the engines. This should return a list of strings.
1816 # in the engines. This should return a list of strings.
1817 stb = value._render_traceback_()
1817 stb = value._render_traceback_()
1818 except Exception:
1818 except Exception:
1819 stb = self.InteractiveTB.structured_traceback(etype,
1819 stb = self.InteractiveTB.structured_traceback(etype,
1820 value, tb, tb_offset=tb_offset)
1820 value, tb, tb_offset=tb_offset)
1821
1821
1822 self._showtraceback(etype, value, stb)
1822 self._showtraceback(etype, value, stb)
1823 if self.call_pdb:
1823 if self.call_pdb:
1824 # drop into debugger
1824 # drop into debugger
1825 self.debugger(force=True)
1825 self.debugger(force=True)
1826 return
1826 return
1827
1827
1828 # Actually show the traceback
1828 # Actually show the traceback
1829 self._showtraceback(etype, value, stb)
1829 self._showtraceback(etype, value, stb)
1830
1830
1831 except KeyboardInterrupt:
1831 except KeyboardInterrupt:
1832 print('\n' + self.get_exception_only(), file=sys.stderr)
1832 print('\n' + self.get_exception_only(), file=sys.stderr)
1833
1833
1834 def _showtraceback(self, etype, evalue, stb):
1834 def _showtraceback(self, etype, evalue, stb):
1835 """Actually show a traceback.
1835 """Actually show a traceback.
1836
1836
1837 Subclasses may override this method to put the traceback on a different
1837 Subclasses may override this method to put the traceback on a different
1838 place, like a side channel.
1838 place, like a side channel.
1839 """
1839 """
1840 print(self.InteractiveTB.stb2text(stb))
1840 print(self.InteractiveTB.stb2text(stb))
1841
1841
1842 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1842 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1843 """Display the syntax error that just occurred.
1843 """Display the syntax error that just occurred.
1844
1844
1845 This doesn't display a stack trace because there isn't one.
1845 This doesn't display a stack trace because there isn't one.
1846
1846
1847 If a filename is given, it is stuffed in the exception instead
1847 If a filename is given, it is stuffed in the exception instead
1848 of what was there before (because Python's parser always uses
1848 of what was there before (because Python's parser always uses
1849 "<string>" when reading from a string).
1849 "<string>" when reading from a string).
1850
1850
1851 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1851 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1852 longer stack trace will be displayed.
1852 longer stack trace will be displayed.
1853 """
1853 """
1854 etype, value, last_traceback = self._get_exc_info()
1854 etype, value, last_traceback = self._get_exc_info()
1855
1855
1856 if filename and issubclass(etype, SyntaxError):
1856 if filename and issubclass(etype, SyntaxError):
1857 try:
1857 try:
1858 value.filename = filename
1858 value.filename = filename
1859 except:
1859 except:
1860 # Not the format we expect; leave it alone
1860 # Not the format we expect; leave it alone
1861 pass
1861 pass
1862
1862
1863 # If the error occured when executing compiled code, we should provide full stacktrace.
1863 # 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 []
1864 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1865 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1865 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1866 self._showtraceback(etype, value, stb)
1866 self._showtraceback(etype, value, stb)
1867
1867
1868 # This is overridden in TerminalInteractiveShell to show a message about
1868 # This is overridden in TerminalInteractiveShell to show a message about
1869 # the %paste magic.
1869 # the %paste magic.
1870 def showindentationerror(self):
1870 def showindentationerror(self):
1871 """Called by run_cell when there's an IndentationError in code entered
1871 """Called by run_cell when there's an IndentationError in code entered
1872 at the prompt.
1872 at the prompt.
1873
1873
1874 This is overridden in TerminalInteractiveShell to show a message about
1874 This is overridden in TerminalInteractiveShell to show a message about
1875 the %paste magic."""
1875 the %paste magic."""
1876 self.showsyntaxerror()
1876 self.showsyntaxerror()
1877
1877
1878 #-------------------------------------------------------------------------
1878 #-------------------------------------------------------------------------
1879 # Things related to readline
1879 # Things related to readline
1880 #-------------------------------------------------------------------------
1880 #-------------------------------------------------------------------------
1881
1881
1882 def init_readline(self):
1882 def init_readline(self):
1883 """DEPRECATED
1883 """DEPRECATED
1884
1884
1885 Moved to terminal subclass, here only to simplify the init logic."""
1885 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
1886 # 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',
1887 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1888 DeprecationWarning, stacklevel=2)
1888 DeprecationWarning, stacklevel=2)
1889 self.set_custom_completer = no_op
1889 self.set_custom_completer = no_op
1890
1890
1891 @skip_doctest
1891 @skip_doctest
1892 def set_next_input(self, s, replace=False):
1892 def set_next_input(self, s, replace=False):
1893 """ Sets the 'default' input string for the next command line.
1893 """ Sets the 'default' input string for the next command line.
1894
1894
1895 Example::
1895 Example::
1896
1896
1897 In [1]: _ip.set_next_input("Hello Word")
1897 In [1]: _ip.set_next_input("Hello Word")
1898 In [2]: Hello Word_ # cursor is here
1898 In [2]: Hello Word_ # cursor is here
1899 """
1899 """
1900 self.rl_next_input = s
1900 self.rl_next_input = s
1901
1901
1902 def _indent_current_str(self):
1902 def _indent_current_str(self):
1903 """return the current level of indentation as a string"""
1903 """return the current level of indentation as a string"""
1904 return self.input_splitter.indent_spaces * ' '
1904 return self.input_splitter.indent_spaces * ' '
1905
1905
1906 #-------------------------------------------------------------------------
1906 #-------------------------------------------------------------------------
1907 # Things related to text completion
1907 # Things related to text completion
1908 #-------------------------------------------------------------------------
1908 #-------------------------------------------------------------------------
1909
1909
1910 def init_completer(self):
1910 def init_completer(self):
1911 """Initialize the completion machinery.
1911 """Initialize the completion machinery.
1912
1912
1913 This creates completion machinery that can be used by client code,
1913 This creates completion machinery that can be used by client code,
1914 either interactively in-process (typically triggered by the readline
1914 either interactively in-process (typically triggered by the readline
1915 library), programmatically (such as in test suites) or out-of-process
1915 library), programmatically (such as in test suites) or out-of-process
1916 (typically over the network by remote frontends).
1916 (typically over the network by remote frontends).
1917 """
1917 """
1918 from IPython.core.completer import IPCompleter
1918 from IPython.core.completer import IPCompleter
1919 from IPython.core.completerlib import (module_completer,
1919 from IPython.core.completerlib import (module_completer,
1920 magic_run_completer, cd_completer, reset_completer)
1920 magic_run_completer, cd_completer, reset_completer)
1921
1921
1922 self.Completer = IPCompleter(shell=self,
1922 self.Completer = IPCompleter(shell=self,
1923 namespace=self.user_ns,
1923 namespace=self.user_ns,
1924 global_namespace=self.user_global_ns,
1924 global_namespace=self.user_global_ns,
1925 parent=self,
1925 parent=self,
1926 )
1926 )
1927 self.configurables.append(self.Completer)
1927 self.configurables.append(self.Completer)
1928
1928
1929 # Add custom completers to the basic ones built into IPCompleter
1929 # Add custom completers to the basic ones built into IPCompleter
1930 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1930 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1931 self.strdispatchers['complete_command'] = sdisp
1931 self.strdispatchers['complete_command'] = sdisp
1932 self.Completer.custom_completers = sdisp
1932 self.Completer.custom_completers = sdisp
1933
1933
1934 self.set_hook('complete_command', module_completer, str_key = 'import')
1934 self.set_hook('complete_command', module_completer, str_key = 'import')
1935 self.set_hook('complete_command', module_completer, str_key = 'from')
1935 self.set_hook('complete_command', module_completer, str_key = 'from')
1936 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1936 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1937 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1937 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1938 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1938 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1939 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1939 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1940
1940
1941
1941
1942 def complete(self, text, line=None, cursor_pos=None):
1942 def complete(self, text, line=None, cursor_pos=None):
1943 """Return the completed text and a list of completions.
1943 """Return the completed text and a list of completions.
1944
1944
1945 Parameters
1945 Parameters
1946 ----------
1946 ----------
1947
1947
1948 text : string
1948 text : string
1949 A string of text to be completed on. It can be given as empty and
1949 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
1950 instead a line/position pair are given. In this case, the
1951 completer itself will split the line like readline does.
1951 completer itself will split the line like readline does.
1952
1952
1953 line : string, optional
1953 line : string, optional
1954 The complete line that text is part of.
1954 The complete line that text is part of.
1955
1955
1956 cursor_pos : int, optional
1956 cursor_pos : int, optional
1957 The position of the cursor on the input line.
1957 The position of the cursor on the input line.
1958
1958
1959 Returns
1959 Returns
1960 -------
1960 -------
1961 text : string
1961 text : string
1962 The actual text that was completed.
1962 The actual text that was completed.
1963
1963
1964 matches : list
1964 matches : list
1965 A sorted list with all possible completions.
1965 A sorted list with all possible completions.
1966
1966
1967 The optional arguments allow the completion to take more context into
1967 The optional arguments allow the completion to take more context into
1968 account, and are part of the low-level completion API.
1968 account, and are part of the low-level completion API.
1969
1969
1970 This is a wrapper around the completion mechanism, similar to what
1970 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
1971 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
1972 exposing it as a method, it can be used by other non-readline
1973 environments (such as GUIs) for text completion.
1973 environments (such as GUIs) for text completion.
1974
1974
1975 Simple usage example:
1975 Simple usage example:
1976
1976
1977 In [1]: x = 'hello'
1977 In [1]: x = 'hello'
1978
1978
1979 In [2]: _ip.complete('x.l')
1979 In [2]: _ip.complete('x.l')
1980 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1980 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1981 """
1981 """
1982
1982
1983 # Inject names into __builtin__ so we can complete on the added names.
1983 # Inject names into __builtin__ so we can complete on the added names.
1984 with self.builtin_trap:
1984 with self.builtin_trap:
1985 return self.Completer.complete(text, line, cursor_pos)
1985 return self.Completer.complete(text, line, cursor_pos)
1986
1986
1987 def set_custom_completer(self, completer, pos=0):
1987 def set_custom_completer(self, completer, pos=0):
1988 """Adds a new custom completer function.
1988 """Adds a new custom completer function.
1989
1989
1990 The position argument (defaults to 0) is the index in the completers
1990 The position argument (defaults to 0) is the index in the completers
1991 list where you want the completer to be inserted."""
1991 list where you want the completer to be inserted."""
1992
1992
1993 newcomp = types.MethodType(completer,self.Completer)
1993 newcomp = types.MethodType(completer,self.Completer)
1994 self.Completer.matchers.insert(pos,newcomp)
1994 self.Completer.matchers.insert(pos,newcomp)
1995
1995
1996 def set_completer_frame(self, frame=None):
1996 def set_completer_frame(self, frame=None):
1997 """Set the frame of the completer."""
1997 """Set the frame of the completer."""
1998 if frame:
1998 if frame:
1999 self.Completer.namespace = frame.f_locals
1999 self.Completer.namespace = frame.f_locals
2000 self.Completer.global_namespace = frame.f_globals
2000 self.Completer.global_namespace = frame.f_globals
2001 else:
2001 else:
2002 self.Completer.namespace = self.user_ns
2002 self.Completer.namespace = self.user_ns
2003 self.Completer.global_namespace = self.user_global_ns
2003 self.Completer.global_namespace = self.user_global_ns
2004
2004
2005 #-------------------------------------------------------------------------
2005 #-------------------------------------------------------------------------
2006 # Things related to magics
2006 # Things related to magics
2007 #-------------------------------------------------------------------------
2007 #-------------------------------------------------------------------------
2008
2008
2009 def init_magics(self):
2009 def init_magics(self):
2010 from IPython.core import magics as m
2010 from IPython.core import magics as m
2011 self.magics_manager = magic.MagicsManager(shell=self,
2011 self.magics_manager = magic.MagicsManager(shell=self,
2012 parent=self,
2012 parent=self,
2013 user_magics=m.UserMagics(self))
2013 user_magics=m.UserMagics(self))
2014 self.configurables.append(self.magics_manager)
2014 self.configurables.append(self.magics_manager)
2015
2015
2016 # Expose as public API from the magics manager
2016 # Expose as public API from the magics manager
2017 self.register_magics = self.magics_manager.register
2017 self.register_magics = self.magics_manager.register
2018
2018
2019 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2019 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2020 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2020 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2021 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2021 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2022 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2022 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2023 )
2023 )
2024
2024
2025 # Register Magic Aliases
2025 # Register Magic Aliases
2026 mman = self.magics_manager
2026 mman = self.magics_manager
2027 # FIXME: magic aliases should be defined by the Magics classes
2027 # FIXME: magic aliases should be defined by the Magics classes
2028 # or in MagicsManager, not here
2028 # or in MagicsManager, not here
2029 mman.register_alias('ed', 'edit')
2029 mman.register_alias('ed', 'edit')
2030 mman.register_alias('hist', 'history')
2030 mman.register_alias('hist', 'history')
2031 mman.register_alias('rep', 'recall')
2031 mman.register_alias('rep', 'recall')
2032 mman.register_alias('SVG', 'svg', 'cell')
2032 mman.register_alias('SVG', 'svg', 'cell')
2033 mman.register_alias('HTML', 'html', 'cell')
2033 mman.register_alias('HTML', 'html', 'cell')
2034 mman.register_alias('file', 'writefile', 'cell')
2034 mman.register_alias('file', 'writefile', 'cell')
2035
2035
2036 # FIXME: Move the color initialization to the DisplayHook, which
2036 # FIXME: Move the color initialization to the DisplayHook, which
2037 # should be split into a prompt manager and displayhook. We probably
2037 # should be split into a prompt manager and displayhook. We probably
2038 # even need a centralize colors management object.
2038 # even need a centralize colors management object.
2039 self.magic('colors %s' % self.colors)
2039 self.run_line_magic('colors', self.colors)
2040
2040
2041 # Defined here so that it's included in the documentation
2041 # Defined here so that it's included in the documentation
2042 @functools.wraps(magic.MagicsManager.register_function)
2042 @functools.wraps(magic.MagicsManager.register_function)
2043 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2043 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2044 self.magics_manager.register_function(func,
2044 self.magics_manager.register_function(func,
2045 magic_kind=magic_kind, magic_name=magic_name)
2045 magic_kind=magic_kind, magic_name=magic_name)
2046
2046
2047 def run_line_magic(self, magic_name, line, back_compat=False):
2047 def run_line_magic(self, magic_name, line, _stack_depth=1):
2048 """Execute the given line magic.
2048 """Execute the given line magic.
2049
2049
2050 Parameters
2050 Parameters
2051 ----------
2051 ----------
2052 magic_name : str
2052 magic_name : str
2053 Name of the desired magic function, without '%' prefix.
2053 Name of the desired magic function, without '%' prefix.
2054
2054
2055 line : str
2055 line : str
2056 The rest of the input line as a single string.
2056 The rest of the input line as a single string.
2057
2057
2058 back_compat : bool
2058 _stack_depth : int
2059 If run_line_magic() is called from magic() then it should be 'True'.
2059 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()'
2060 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2061 """
2061 """
2062 fn = self.find_line_magic(magic_name)
2062 fn = self.find_line_magic(magic_name)
2063 if fn is None:
2063 if fn is None:
2064 cm = self.find_cell_magic(magic_name)
2064 cm = self.find_cell_magic(magic_name)
2065 etpl = "Line magic function `%%%s` not found%s."
2065 etpl = "Line magic function `%%%s` not found%s."
2066 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2066 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2067 'did you mean that instead?)' % magic_name )
2067 'did you mean that instead?)' % magic_name )
2068 error(etpl % (magic_name, extra))
2068 error(etpl % (magic_name, extra))
2069 else:
2069 else:
2070 # Note: this is the distance in the stack to the user's frame.
2070 # 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
2071 # This will need to be updated if the internal calling logic gets
2072 # refactored, or else we'll be expanding the wrong variables.
2072 # refactored, or else we'll be expanding the wrong variables.
2073
2073 # Determine stack_depth depending on where run_line_magic() has been called
2074 # Determine stack_depth depending on where run_line_magic() has been called
2074 if back_compat:
2075 stack_depth = _stack_depth
2075 # run_line_magic() called directly using 'get_ipython().magic()'
2076 stack_depth = 2
2077 else:
2078 # run_line_magic() called directly using 'get_ipython().run_line_magic()'
2079 stack_depth = 1
2080 magic_arg_s = self.var_expand(line, stack_depth)
2076 magic_arg_s = self.var_expand(line, stack_depth)
2081 # Put magic args in a list so we can call with f(*a) syntax
2077 # Put magic args in a list so we can call with f(*a) syntax
2082 args = [magic_arg_s]
2078 args = [magic_arg_s]
2083 kwargs = {}
2079 kwargs = {}
2084 # Grab local namespace if we need it:
2080 # Grab local namespace if we need it:
2085 if getattr(fn, "needs_local_scope", False):
2081 if getattr(fn, "needs_local_scope", False):
2086 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2082 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2087 with self.builtin_trap:
2083 with self.builtin_trap:
2088 result = fn(*args,**kwargs)
2084 result = fn(*args,**kwargs)
2089 return result
2085 return result
2090
2086
2091 def run_cell_magic(self, magic_name, line, cell):
2087 def run_cell_magic(self, magic_name, line, cell):
2092 """Execute the given cell magic.
2088 """Execute the given cell magic.
2093
2089
2094 Parameters
2090 Parameters
2095 ----------
2091 ----------
2096 magic_name : str
2092 magic_name : str
2097 Name of the desired magic function, without '%' prefix.
2093 Name of the desired magic function, without '%' prefix.
2098
2094
2099 line : str
2095 line : str
2100 The rest of the first input line as a single string.
2096 The rest of the first input line as a single string.
2101
2097
2102 cell : str
2098 cell : str
2103 The body of the cell as a (possibly multiline) string.
2099 The body of the cell as a (possibly multiline) string.
2104 """
2100 """
2105 fn = self.find_cell_magic(magic_name)
2101 fn = self.find_cell_magic(magic_name)
2106 if fn is None:
2102 if fn is None:
2107 lm = self.find_line_magic(magic_name)
2103 lm = self.find_line_magic(magic_name)
2108 etpl = "Cell magic `%%{0}` not found{1}."
2104 etpl = "Cell magic `%%{0}` not found{1}."
2109 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2105 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2110 'did you mean that instead?)'.format(magic_name))
2106 'did you mean that instead?)'.format(magic_name))
2111 error(etpl.format(magic_name, extra))
2107 error(etpl.format(magic_name, extra))
2112 elif cell == '':
2108 elif cell == '':
2113 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2109 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2114 if self.find_line_magic(magic_name) is not None:
2110 if self.find_line_magic(magic_name) is not None:
2115 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2111 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2116 raise UsageError(message)
2112 raise UsageError(message)
2117 else:
2113 else:
2118 # Note: this is the distance in the stack to the user's frame.
2114 # Note: this is the distance in the stack to the user's frame.
2119 # This will need to be updated if the internal calling logic gets
2115 # This will need to be updated if the internal calling logic gets
2120 # refactored, or else we'll be expanding the wrong variables.
2116 # refactored, or else we'll be expanding the wrong variables.
2121 stack_depth = 2
2117 stack_depth = 2
2122 magic_arg_s = self.var_expand(line, stack_depth)
2118 magic_arg_s = self.var_expand(line, stack_depth)
2123 with self.builtin_trap:
2119 with self.builtin_trap:
2124 result = fn(magic_arg_s, cell)
2120 result = fn(magic_arg_s, cell)
2125 return result
2121 return result
2126
2122
2127 def find_line_magic(self, magic_name):
2123 def find_line_magic(self, magic_name):
2128 """Find and return a line magic by name.
2124 """Find and return a line magic by name.
2129
2125
2130 Returns None if the magic isn't found."""
2126 Returns None if the magic isn't found."""
2131 return self.magics_manager.magics['line'].get(magic_name)
2127 return self.magics_manager.magics['line'].get(magic_name)
2132
2128
2133 def find_cell_magic(self, magic_name):
2129 def find_cell_magic(self, magic_name):
2134 """Find and return a cell magic by name.
2130 """Find and return a cell magic by name.
2135
2131
2136 Returns None if the magic isn't found."""
2132 Returns None if the magic isn't found."""
2137 return self.magics_manager.magics['cell'].get(magic_name)
2133 return self.magics_manager.magics['cell'].get(magic_name)
2138
2134
2139 def find_magic(self, magic_name, magic_kind='line'):
2135 def find_magic(self, magic_name, magic_kind='line'):
2140 """Find and return a magic of the given type by name.
2136 """Find and return a magic of the given type by name.
2141
2137
2142 Returns None if the magic isn't found."""
2138 Returns None if the magic isn't found."""
2143 return self.magics_manager.magics[magic_kind].get(magic_name)
2139 return self.magics_manager.magics[magic_kind].get(magic_name)
2144
2140
2145 def magic(self, arg_s):
2141 def magic(self, arg_s):
2146 """DEPRECATED. Use run_line_magic() instead.
2142 """DEPRECATED. Use run_line_magic() instead.
2147
2143
2148 Call a magic function by name.
2144 Call a magic function by name.
2149
2145
2150 Input: a string containing the name of the magic function to call and
2146 Input: a string containing the name of the magic function to call and
2151 any additional arguments to be passed to the magic.
2147 any additional arguments to be passed to the magic.
2152
2148
2153 magic('name -opt foo bar') is equivalent to typing at the ipython
2149 magic('name -opt foo bar') is equivalent to typing at the ipython
2154 prompt:
2150 prompt:
2155
2151
2156 In[1]: %name -opt foo bar
2152 In[1]: %name -opt foo bar
2157
2153
2158 To call a magic without arguments, simply use magic('name').
2154 To call a magic without arguments, simply use magic('name').
2159
2155
2160 This provides a proper Python function to call IPython's magics in any
2156 This provides a proper Python function to call IPython's magics in any
2161 valid Python code you can type at the interpreter, including loops and
2157 valid Python code you can type at the interpreter, including loops and
2162 compound statements.
2158 compound statements.
2163 """
2159 """
2164 # TODO: should we issue a loud deprecation warning here?
2160 # TODO: should we issue a loud deprecation warning here?
2165 magic_name, _, magic_arg_s = arg_s.partition(' ')
2161 magic_name, _, magic_arg_s = arg_s.partition(' ')
2166 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2162 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2167 return self.run_line_magic(magic_name, magic_arg_s, back_compat=True)
2163 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2168
2164
2169 #-------------------------------------------------------------------------
2165 #-------------------------------------------------------------------------
2170 # Things related to macros
2166 # Things related to macros
2171 #-------------------------------------------------------------------------
2167 #-------------------------------------------------------------------------
2172
2168
2173 def define_macro(self, name, themacro):
2169 def define_macro(self, name, themacro):
2174 """Define a new macro
2170 """Define a new macro
2175
2171
2176 Parameters
2172 Parameters
2177 ----------
2173 ----------
2178 name : str
2174 name : str
2179 The name of the macro.
2175 The name of the macro.
2180 themacro : str or Macro
2176 themacro : str or Macro
2181 The action to do upon invoking the macro. If a string, a new
2177 The action to do upon invoking the macro. If a string, a new
2182 Macro object is created by passing the string to it.
2178 Macro object is created by passing the string to it.
2183 """
2179 """
2184
2180
2185 from IPython.core import macro
2181 from IPython.core import macro
2186
2182
2187 if isinstance(themacro, str):
2183 if isinstance(themacro, str):
2188 themacro = macro.Macro(themacro)
2184 themacro = macro.Macro(themacro)
2189 if not isinstance(themacro, macro.Macro):
2185 if not isinstance(themacro, macro.Macro):
2190 raise ValueError('A macro must be a string or a Macro instance.')
2186 raise ValueError('A macro must be a string or a Macro instance.')
2191 self.user_ns[name] = themacro
2187 self.user_ns[name] = themacro
2192
2188
2193 #-------------------------------------------------------------------------
2189 #-------------------------------------------------------------------------
2194 # Things related to the running of system commands
2190 # Things related to the running of system commands
2195 #-------------------------------------------------------------------------
2191 #-------------------------------------------------------------------------
2196
2192
2197 def system_piped(self, cmd):
2193 def system_piped(self, cmd):
2198 """Call the given cmd in a subprocess, piping stdout/err
2194 """Call the given cmd in a subprocess, piping stdout/err
2199
2195
2200 Parameters
2196 Parameters
2201 ----------
2197 ----------
2202 cmd : str
2198 cmd : str
2203 Command to execute (can not end in '&', as background processes are
2199 Command to execute (can not end in '&', as background processes are
2204 not supported. Should not be a command that expects input
2200 not supported. Should not be a command that expects input
2205 other than simple text.
2201 other than simple text.
2206 """
2202 """
2207 if cmd.rstrip().endswith('&'):
2203 if cmd.rstrip().endswith('&'):
2208 # this is *far* from a rigorous test
2204 # this is *far* from a rigorous test
2209 # We do not support backgrounding processes because we either use
2205 # We do not support backgrounding processes because we either use
2210 # pexpect or pipes to read from. Users can always just call
2206 # pexpect or pipes to read from. Users can always just call
2211 # os.system() or use ip.system=ip.system_raw
2207 # os.system() or use ip.system=ip.system_raw
2212 # if they really want a background process.
2208 # if they really want a background process.
2213 raise OSError("Background processes not supported.")
2209 raise OSError("Background processes not supported.")
2214
2210
2215 # we explicitly do NOT return the subprocess status code, because
2211 # we explicitly do NOT return the subprocess status code, because
2216 # a non-None value would trigger :func:`sys.displayhook` calls.
2212 # a non-None value would trigger :func:`sys.displayhook` calls.
2217 # Instead, we store the exit_code in user_ns.
2213 # Instead, we store the exit_code in user_ns.
2218 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2214 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2219
2215
2220 def system_raw(self, cmd):
2216 def system_raw(self, cmd):
2221 """Call the given cmd in a subprocess using os.system on Windows or
2217 """Call the given cmd in a subprocess using os.system on Windows or
2222 subprocess.call using the system shell on other platforms.
2218 subprocess.call using the system shell on other platforms.
2223
2219
2224 Parameters
2220 Parameters
2225 ----------
2221 ----------
2226 cmd : str
2222 cmd : str
2227 Command to execute.
2223 Command to execute.
2228 """
2224 """
2229 cmd = self.var_expand(cmd, depth=1)
2225 cmd = self.var_expand(cmd, depth=1)
2230 # protect os.system from UNC paths on Windows, which it can't handle:
2226 # protect os.system from UNC paths on Windows, which it can't handle:
2231 if sys.platform == 'win32':
2227 if sys.platform == 'win32':
2232 from IPython.utils._process_win32 import AvoidUNCPath
2228 from IPython.utils._process_win32 import AvoidUNCPath
2233 with AvoidUNCPath() as path:
2229 with AvoidUNCPath() as path:
2234 if path is not None:
2230 if path is not None:
2235 cmd = '"pushd %s &&"%s' % (path, cmd)
2231 cmd = '"pushd %s &&"%s' % (path, cmd)
2236 try:
2232 try:
2237 ec = os.system(cmd)
2233 ec = os.system(cmd)
2238 except KeyboardInterrupt:
2234 except KeyboardInterrupt:
2239 print('\n' + self.get_exception_only(), file=sys.stderr)
2235 print('\n' + self.get_exception_only(), file=sys.stderr)
2240 ec = -2
2236 ec = -2
2241 else:
2237 else:
2242 # For posix the result of the subprocess.call() below is an exit
2238 # For posix the result of the subprocess.call() below is an exit
2243 # code, which by convention is zero for success, positive for
2239 # code, which by convention is zero for success, positive for
2244 # program failure. Exit codes above 128 are reserved for signals,
2240 # program failure. Exit codes above 128 are reserved for signals,
2245 # and the formula for converting a signal to an exit code is usually
2241 # and the formula for converting a signal to an exit code is usually
2246 # signal_number+128. To more easily differentiate between exit
2242 # signal_number+128. To more easily differentiate between exit
2247 # codes and signals, ipython uses negative numbers. For instance
2243 # codes and signals, ipython uses negative numbers. For instance
2248 # since control-c is signal 2 but exit code 130, ipython's
2244 # since control-c is signal 2 but exit code 130, ipython's
2249 # _exit_code variable will read -2. Note that some shells like
2245 # _exit_code variable will read -2. Note that some shells like
2250 # csh and fish don't follow sh/bash conventions for exit codes.
2246 # csh and fish don't follow sh/bash conventions for exit codes.
2251 executable = os.environ.get('SHELL', None)
2247 executable = os.environ.get('SHELL', None)
2252 try:
2248 try:
2253 # Use env shell instead of default /bin/sh
2249 # Use env shell instead of default /bin/sh
2254 ec = subprocess.call(cmd, shell=True, executable=executable)
2250 ec = subprocess.call(cmd, shell=True, executable=executable)
2255 except KeyboardInterrupt:
2251 except KeyboardInterrupt:
2256 # intercept control-C; a long traceback is not useful here
2252 # intercept control-C; a long traceback is not useful here
2257 print('\n' + self.get_exception_only(), file=sys.stderr)
2253 print('\n' + self.get_exception_only(), file=sys.stderr)
2258 ec = 130
2254 ec = 130
2259 if ec > 128:
2255 if ec > 128:
2260 ec = -(ec - 128)
2256 ec = -(ec - 128)
2261
2257
2262 # We explicitly do NOT return the subprocess status code, because
2258 # We explicitly do NOT return the subprocess status code, because
2263 # a non-None value would trigger :func:`sys.displayhook` calls.
2259 # a non-None value would trigger :func:`sys.displayhook` calls.
2264 # Instead, we store the exit_code in user_ns. Note the semantics
2260 # Instead, we store the exit_code in user_ns. Note the semantics
2265 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2261 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2266 # but raising SystemExit(_exit_code) will give status 254!
2262 # but raising SystemExit(_exit_code) will give status 254!
2267 self.user_ns['_exit_code'] = ec
2263 self.user_ns['_exit_code'] = ec
2268
2264
2269 # use piped system by default, because it is better behaved
2265 # use piped system by default, because it is better behaved
2270 system = system_piped
2266 system = system_piped
2271
2267
2272 def getoutput(self, cmd, split=True, depth=0):
2268 def getoutput(self, cmd, split=True, depth=0):
2273 """Get output (possibly including stderr) from a subprocess.
2269 """Get output (possibly including stderr) from a subprocess.
2274
2270
2275 Parameters
2271 Parameters
2276 ----------
2272 ----------
2277 cmd : str
2273 cmd : str
2278 Command to execute (can not end in '&', as background processes are
2274 Command to execute (can not end in '&', as background processes are
2279 not supported.
2275 not supported.
2280 split : bool, optional
2276 split : bool, optional
2281 If True, split the output into an IPython SList. Otherwise, an
2277 If True, split the output into an IPython SList. Otherwise, an
2282 IPython LSString is returned. These are objects similar to normal
2278 IPython LSString is returned. These are objects similar to normal
2283 lists and strings, with a few convenience attributes for easier
2279 lists and strings, with a few convenience attributes for easier
2284 manipulation of line-based output. You can use '?' on them for
2280 manipulation of line-based output. You can use '?' on them for
2285 details.
2281 details.
2286 depth : int, optional
2282 depth : int, optional
2287 How many frames above the caller are the local variables which should
2283 How many frames above the caller are the local variables which should
2288 be expanded in the command string? The default (0) assumes that the
2284 be expanded in the command string? The default (0) assumes that the
2289 expansion variables are in the stack frame calling this function.
2285 expansion variables are in the stack frame calling this function.
2290 """
2286 """
2291 if cmd.rstrip().endswith('&'):
2287 if cmd.rstrip().endswith('&'):
2292 # this is *far* from a rigorous test
2288 # this is *far* from a rigorous test
2293 raise OSError("Background processes not supported.")
2289 raise OSError("Background processes not supported.")
2294 out = getoutput(self.var_expand(cmd, depth=depth+1))
2290 out = getoutput(self.var_expand(cmd, depth=depth+1))
2295 if split:
2291 if split:
2296 out = SList(out.splitlines())
2292 out = SList(out.splitlines())
2297 else:
2293 else:
2298 out = LSString(out)
2294 out = LSString(out)
2299 return out
2295 return out
2300
2296
2301 #-------------------------------------------------------------------------
2297 #-------------------------------------------------------------------------
2302 # Things related to aliases
2298 # Things related to aliases
2303 #-------------------------------------------------------------------------
2299 #-------------------------------------------------------------------------
2304
2300
2305 def init_alias(self):
2301 def init_alias(self):
2306 self.alias_manager = AliasManager(shell=self, parent=self)
2302 self.alias_manager = AliasManager(shell=self, parent=self)
2307 self.configurables.append(self.alias_manager)
2303 self.configurables.append(self.alias_manager)
2308
2304
2309 #-------------------------------------------------------------------------
2305 #-------------------------------------------------------------------------
2310 # Things related to extensions
2306 # Things related to extensions
2311 #-------------------------------------------------------------------------
2307 #-------------------------------------------------------------------------
2312
2308
2313 def init_extension_manager(self):
2309 def init_extension_manager(self):
2314 self.extension_manager = ExtensionManager(shell=self, parent=self)
2310 self.extension_manager = ExtensionManager(shell=self, parent=self)
2315 self.configurables.append(self.extension_manager)
2311 self.configurables.append(self.extension_manager)
2316
2312
2317 #-------------------------------------------------------------------------
2313 #-------------------------------------------------------------------------
2318 # Things related to payloads
2314 # Things related to payloads
2319 #-------------------------------------------------------------------------
2315 #-------------------------------------------------------------------------
2320
2316
2321 def init_payload(self):
2317 def init_payload(self):
2322 self.payload_manager = PayloadManager(parent=self)
2318 self.payload_manager = PayloadManager(parent=self)
2323 self.configurables.append(self.payload_manager)
2319 self.configurables.append(self.payload_manager)
2324
2320
2325 #-------------------------------------------------------------------------
2321 #-------------------------------------------------------------------------
2326 # Things related to the prefilter
2322 # Things related to the prefilter
2327 #-------------------------------------------------------------------------
2323 #-------------------------------------------------------------------------
2328
2324
2329 def init_prefilter(self):
2325 def init_prefilter(self):
2330 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2326 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2331 self.configurables.append(self.prefilter_manager)
2327 self.configurables.append(self.prefilter_manager)
2332 # Ultimately this will be refactored in the new interpreter code, but
2328 # Ultimately this will be refactored in the new interpreter code, but
2333 # for now, we should expose the main prefilter method (there's legacy
2329 # for now, we should expose the main prefilter method (there's legacy
2334 # code out there that may rely on this).
2330 # code out there that may rely on this).
2335 self.prefilter = self.prefilter_manager.prefilter_lines
2331 self.prefilter = self.prefilter_manager.prefilter_lines
2336
2332
2337 def auto_rewrite_input(self, cmd):
2333 def auto_rewrite_input(self, cmd):
2338 """Print to the screen the rewritten form of the user's command.
2334 """Print to the screen the rewritten form of the user's command.
2339
2335
2340 This shows visual feedback by rewriting input lines that cause
2336 This shows visual feedback by rewriting input lines that cause
2341 automatic calling to kick in, like::
2337 automatic calling to kick in, like::
2342
2338
2343 /f x
2339 /f x
2344
2340
2345 into::
2341 into::
2346
2342
2347 ------> f(x)
2343 ------> f(x)
2348
2344
2349 after the user's input prompt. This helps the user understand that the
2345 after the user's input prompt. This helps the user understand that the
2350 input line was transformed automatically by IPython.
2346 input line was transformed automatically by IPython.
2351 """
2347 """
2352 if not self.show_rewritten_input:
2348 if not self.show_rewritten_input:
2353 return
2349 return
2354
2350
2355 # This is overridden in TerminalInteractiveShell to use fancy prompts
2351 # This is overridden in TerminalInteractiveShell to use fancy prompts
2356 print("------> " + cmd)
2352 print("------> " + cmd)
2357
2353
2358 #-------------------------------------------------------------------------
2354 #-------------------------------------------------------------------------
2359 # Things related to extracting values/expressions from kernel and user_ns
2355 # Things related to extracting values/expressions from kernel and user_ns
2360 #-------------------------------------------------------------------------
2356 #-------------------------------------------------------------------------
2361
2357
2362 def _user_obj_error(self):
2358 def _user_obj_error(self):
2363 """return simple exception dict
2359 """return simple exception dict
2364
2360
2365 for use in user_expressions
2361 for use in user_expressions
2366 """
2362 """
2367
2363
2368 etype, evalue, tb = self._get_exc_info()
2364 etype, evalue, tb = self._get_exc_info()
2369 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2365 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2370
2366
2371 exc_info = {
2367 exc_info = {
2372 u'status' : 'error',
2368 u'status' : 'error',
2373 u'traceback' : stb,
2369 u'traceback' : stb,
2374 u'ename' : etype.__name__,
2370 u'ename' : etype.__name__,
2375 u'evalue' : py3compat.safe_unicode(evalue),
2371 u'evalue' : py3compat.safe_unicode(evalue),
2376 }
2372 }
2377
2373
2378 return exc_info
2374 return exc_info
2379
2375
2380 def _format_user_obj(self, obj):
2376 def _format_user_obj(self, obj):
2381 """format a user object to display dict
2377 """format a user object to display dict
2382
2378
2383 for use in user_expressions
2379 for use in user_expressions
2384 """
2380 """
2385
2381
2386 data, md = self.display_formatter.format(obj)
2382 data, md = self.display_formatter.format(obj)
2387 value = {
2383 value = {
2388 'status' : 'ok',
2384 'status' : 'ok',
2389 'data' : data,
2385 'data' : data,
2390 'metadata' : md,
2386 'metadata' : md,
2391 }
2387 }
2392 return value
2388 return value
2393
2389
2394 def user_expressions(self, expressions):
2390 def user_expressions(self, expressions):
2395 """Evaluate a dict of expressions in the user's namespace.
2391 """Evaluate a dict of expressions in the user's namespace.
2396
2392
2397 Parameters
2393 Parameters
2398 ----------
2394 ----------
2399 expressions : dict
2395 expressions : dict
2400 A dict with string keys and string values. The expression values
2396 A dict with string keys and string values. The expression values
2401 should be valid Python expressions, each of which will be evaluated
2397 should be valid Python expressions, each of which will be evaluated
2402 in the user namespace.
2398 in the user namespace.
2403
2399
2404 Returns
2400 Returns
2405 -------
2401 -------
2406 A dict, keyed like the input expressions dict, with the rich mime-typed
2402 A dict, keyed like the input expressions dict, with the rich mime-typed
2407 display_data of each value.
2403 display_data of each value.
2408 """
2404 """
2409 out = {}
2405 out = {}
2410 user_ns = self.user_ns
2406 user_ns = self.user_ns
2411 global_ns = self.user_global_ns
2407 global_ns = self.user_global_ns
2412
2408
2413 for key, expr in expressions.items():
2409 for key, expr in expressions.items():
2414 try:
2410 try:
2415 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2411 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2416 except:
2412 except:
2417 value = self._user_obj_error()
2413 value = self._user_obj_error()
2418 out[key] = value
2414 out[key] = value
2419 return out
2415 return out
2420
2416
2421 #-------------------------------------------------------------------------
2417 #-------------------------------------------------------------------------
2422 # Things related to the running of code
2418 # Things related to the running of code
2423 #-------------------------------------------------------------------------
2419 #-------------------------------------------------------------------------
2424
2420
2425 def ex(self, cmd):
2421 def ex(self, cmd):
2426 """Execute a normal python statement in user namespace."""
2422 """Execute a normal python statement in user namespace."""
2427 with self.builtin_trap:
2423 with self.builtin_trap:
2428 exec(cmd, self.user_global_ns, self.user_ns)
2424 exec(cmd, self.user_global_ns, self.user_ns)
2429
2425
2430 def ev(self, expr):
2426 def ev(self, expr):
2431 """Evaluate python expression expr in user namespace.
2427 """Evaluate python expression expr in user namespace.
2432
2428
2433 Returns the result of evaluation
2429 Returns the result of evaluation
2434 """
2430 """
2435 with self.builtin_trap:
2431 with self.builtin_trap:
2436 return eval(expr, self.user_global_ns, self.user_ns)
2432 return eval(expr, self.user_global_ns, self.user_ns)
2437
2433
2438 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2434 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2439 """A safe version of the builtin execfile().
2435 """A safe version of the builtin execfile().
2440
2436
2441 This version will never throw an exception, but instead print
2437 This version will never throw an exception, but instead print
2442 helpful error messages to the screen. This only works on pure
2438 helpful error messages to the screen. This only works on pure
2443 Python files with the .py extension.
2439 Python files with the .py extension.
2444
2440
2445 Parameters
2441 Parameters
2446 ----------
2442 ----------
2447 fname : string
2443 fname : string
2448 The name of the file to be executed.
2444 The name of the file to be executed.
2449 where : tuple
2445 where : tuple
2450 One or two namespaces, passed to execfile() as (globals,locals).
2446 One or two namespaces, passed to execfile() as (globals,locals).
2451 If only one is given, it is passed as both.
2447 If only one is given, it is passed as both.
2452 exit_ignore : bool (False)
2448 exit_ignore : bool (False)
2453 If True, then silence SystemExit for non-zero status (it is always
2449 If True, then silence SystemExit for non-zero status (it is always
2454 silenced for zero status, as it is so common).
2450 silenced for zero status, as it is so common).
2455 raise_exceptions : bool (False)
2451 raise_exceptions : bool (False)
2456 If True raise exceptions everywhere. Meant for testing.
2452 If True raise exceptions everywhere. Meant for testing.
2457 shell_futures : bool (False)
2453 shell_futures : bool (False)
2458 If True, the code will share future statements with the interactive
2454 If True, the code will share future statements with the interactive
2459 shell. It will both be affected by previous __future__ imports, and
2455 shell. It will both be affected by previous __future__ imports, and
2460 any __future__ imports in the code will affect the shell. If False,
2456 any __future__ imports in the code will affect the shell. If False,
2461 __future__ imports are not shared in either direction.
2457 __future__ imports are not shared in either direction.
2462
2458
2463 """
2459 """
2464 fname = os.path.abspath(os.path.expanduser(fname))
2460 fname = os.path.abspath(os.path.expanduser(fname))
2465
2461
2466 # Make sure we can open the file
2462 # Make sure we can open the file
2467 try:
2463 try:
2468 with open(fname):
2464 with open(fname):
2469 pass
2465 pass
2470 except:
2466 except:
2471 warn('Could not open file <%s> for safe execution.' % fname)
2467 warn('Could not open file <%s> for safe execution.' % fname)
2472 return
2468 return
2473
2469
2474 # Find things also in current directory. This is needed to mimic the
2470 # Find things also in current directory. This is needed to mimic the
2475 # behavior of running a script from the system command line, where
2471 # behavior of running a script from the system command line, where
2476 # Python inserts the script's directory into sys.path
2472 # Python inserts the script's directory into sys.path
2477 dname = os.path.dirname(fname)
2473 dname = os.path.dirname(fname)
2478
2474
2479 with prepended_to_syspath(dname), self.builtin_trap:
2475 with prepended_to_syspath(dname), self.builtin_trap:
2480 try:
2476 try:
2481 glob, loc = (where + (None, ))[:2]
2477 glob, loc = (where + (None, ))[:2]
2482 py3compat.execfile(
2478 py3compat.execfile(
2483 fname, glob, loc,
2479 fname, glob, loc,
2484 self.compile if shell_futures else None)
2480 self.compile if shell_futures else None)
2485 except SystemExit as status:
2481 except SystemExit as status:
2486 # If the call was made with 0 or None exit status (sys.exit(0)
2482 # If the call was made with 0 or None exit status (sys.exit(0)
2487 # or sys.exit() ), don't bother showing a traceback, as both of
2483 # or sys.exit() ), don't bother showing a traceback, as both of
2488 # these are considered normal by the OS:
2484 # these are considered normal by the OS:
2489 # > python -c'import sys;sys.exit(0)'; echo $?
2485 # > python -c'import sys;sys.exit(0)'; echo $?
2490 # 0
2486 # 0
2491 # > python -c'import sys;sys.exit()'; echo $?
2487 # > python -c'import sys;sys.exit()'; echo $?
2492 # 0
2488 # 0
2493 # For other exit status, we show the exception unless
2489 # For other exit status, we show the exception unless
2494 # explicitly silenced, but only in short form.
2490 # explicitly silenced, but only in short form.
2495 if status.code:
2491 if status.code:
2496 if raise_exceptions:
2492 if raise_exceptions:
2497 raise
2493 raise
2498 if not exit_ignore:
2494 if not exit_ignore:
2499 self.showtraceback(exception_only=True)
2495 self.showtraceback(exception_only=True)
2500 except:
2496 except:
2501 if raise_exceptions:
2497 if raise_exceptions:
2502 raise
2498 raise
2503 # tb offset is 2 because we wrap execfile
2499 # tb offset is 2 because we wrap execfile
2504 self.showtraceback(tb_offset=2)
2500 self.showtraceback(tb_offset=2)
2505
2501
2506 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2502 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2507 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2503 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2508
2504
2509 Parameters
2505 Parameters
2510 ----------
2506 ----------
2511 fname : str
2507 fname : str
2512 The name of the file to execute. The filename must have a
2508 The name of the file to execute. The filename must have a
2513 .ipy or .ipynb extension.
2509 .ipy or .ipynb extension.
2514 shell_futures : bool (False)
2510 shell_futures : bool (False)
2515 If True, the code will share future statements with the interactive
2511 If True, the code will share future statements with the interactive
2516 shell. It will both be affected by previous __future__ imports, and
2512 shell. It will both be affected by previous __future__ imports, and
2517 any __future__ imports in the code will affect the shell. If False,
2513 any __future__ imports in the code will affect the shell. If False,
2518 __future__ imports are not shared in either direction.
2514 __future__ imports are not shared in either direction.
2519 raise_exceptions : bool (False)
2515 raise_exceptions : bool (False)
2520 If True raise exceptions everywhere. Meant for testing.
2516 If True raise exceptions everywhere. Meant for testing.
2521 """
2517 """
2522 fname = os.path.abspath(os.path.expanduser(fname))
2518 fname = os.path.abspath(os.path.expanduser(fname))
2523
2519
2524 # Make sure we can open the file
2520 # Make sure we can open the file
2525 try:
2521 try:
2526 with open(fname):
2522 with open(fname):
2527 pass
2523 pass
2528 except:
2524 except:
2529 warn('Could not open file <%s> for safe execution.' % fname)
2525 warn('Could not open file <%s> for safe execution.' % fname)
2530 return
2526 return
2531
2527
2532 # Find things also in current directory. This is needed to mimic the
2528 # Find things also in current directory. This is needed to mimic the
2533 # behavior of running a script from the system command line, where
2529 # behavior of running a script from the system command line, where
2534 # Python inserts the script's directory into sys.path
2530 # Python inserts the script's directory into sys.path
2535 dname = os.path.dirname(fname)
2531 dname = os.path.dirname(fname)
2536
2532
2537 def get_cells():
2533 def get_cells():
2538 """generator for sequence of code blocks to run"""
2534 """generator for sequence of code blocks to run"""
2539 if fname.endswith('.ipynb'):
2535 if fname.endswith('.ipynb'):
2540 from nbformat import read
2536 from nbformat import read
2541 nb = read(fname, as_version=4)
2537 nb = read(fname, as_version=4)
2542 if not nb.cells:
2538 if not nb.cells:
2543 return
2539 return
2544 for cell in nb.cells:
2540 for cell in nb.cells:
2545 if cell.cell_type == 'code':
2541 if cell.cell_type == 'code':
2546 yield cell.source
2542 yield cell.source
2547 else:
2543 else:
2548 with open(fname) as f:
2544 with open(fname) as f:
2549 yield f.read()
2545 yield f.read()
2550
2546
2551 with prepended_to_syspath(dname):
2547 with prepended_to_syspath(dname):
2552 try:
2548 try:
2553 for cell in get_cells():
2549 for cell in get_cells():
2554 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2550 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2555 if raise_exceptions:
2551 if raise_exceptions:
2556 result.raise_error()
2552 result.raise_error()
2557 elif not result.success:
2553 elif not result.success:
2558 break
2554 break
2559 except:
2555 except:
2560 if raise_exceptions:
2556 if raise_exceptions:
2561 raise
2557 raise
2562 self.showtraceback()
2558 self.showtraceback()
2563 warn('Unknown failure executing file: <%s>' % fname)
2559 warn('Unknown failure executing file: <%s>' % fname)
2564
2560
2565 def safe_run_module(self, mod_name, where):
2561 def safe_run_module(self, mod_name, where):
2566 """A safe version of runpy.run_module().
2562 """A safe version of runpy.run_module().
2567
2563
2568 This version will never throw an exception, but instead print
2564 This version will never throw an exception, but instead print
2569 helpful error messages to the screen.
2565 helpful error messages to the screen.
2570
2566
2571 `SystemExit` exceptions with status code 0 or None are ignored.
2567 `SystemExit` exceptions with status code 0 or None are ignored.
2572
2568
2573 Parameters
2569 Parameters
2574 ----------
2570 ----------
2575 mod_name : string
2571 mod_name : string
2576 The name of the module to be executed.
2572 The name of the module to be executed.
2577 where : dict
2573 where : dict
2578 The globals namespace.
2574 The globals namespace.
2579 """
2575 """
2580 try:
2576 try:
2581 try:
2577 try:
2582 where.update(
2578 where.update(
2583 runpy.run_module(str(mod_name), run_name="__main__",
2579 runpy.run_module(str(mod_name), run_name="__main__",
2584 alter_sys=True)
2580 alter_sys=True)
2585 )
2581 )
2586 except SystemExit as status:
2582 except SystemExit as status:
2587 if status.code:
2583 if status.code:
2588 raise
2584 raise
2589 except:
2585 except:
2590 self.showtraceback()
2586 self.showtraceback()
2591 warn('Unknown failure executing module: <%s>' % mod_name)
2587 warn('Unknown failure executing module: <%s>' % mod_name)
2592
2588
2593 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2589 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2594 """Run a complete IPython cell.
2590 """Run a complete IPython cell.
2595
2591
2596 Parameters
2592 Parameters
2597 ----------
2593 ----------
2598 raw_cell : str
2594 raw_cell : str
2599 The code (including IPython code such as %magic functions) to run.
2595 The code (including IPython code such as %magic functions) to run.
2600 store_history : bool
2596 store_history : bool
2601 If True, the raw and translated cell will be stored in IPython's
2597 If True, the raw and translated cell will be stored in IPython's
2602 history. For user code calling back into IPython's machinery, this
2598 history. For user code calling back into IPython's machinery, this
2603 should be set to False.
2599 should be set to False.
2604 silent : bool
2600 silent : bool
2605 If True, avoid side-effects, such as implicit displayhooks and
2601 If True, avoid side-effects, such as implicit displayhooks and
2606 and logging. silent=True forces store_history=False.
2602 and logging. silent=True forces store_history=False.
2607 shell_futures : bool
2603 shell_futures : bool
2608 If True, the code will share future statements with the interactive
2604 If True, the code will share future statements with the interactive
2609 shell. It will both be affected by previous __future__ imports, and
2605 shell. It will both be affected by previous __future__ imports, and
2610 any __future__ imports in the code will affect the shell. If False,
2606 any __future__ imports in the code will affect the shell. If False,
2611 __future__ imports are not shared in either direction.
2607 __future__ imports are not shared in either direction.
2612
2608
2613 Returns
2609 Returns
2614 -------
2610 -------
2615 result : :class:`ExecutionResult`
2611 result : :class:`ExecutionResult`
2616 """
2612 """
2617 result = ExecutionResult()
2613 result = ExecutionResult()
2618
2614
2619 if (not raw_cell) or raw_cell.isspace():
2615 if (not raw_cell) or raw_cell.isspace():
2620 self.last_execution_succeeded = True
2616 self.last_execution_succeeded = True
2621 return result
2617 return result
2622
2618
2623 if silent:
2619 if silent:
2624 store_history = False
2620 store_history = False
2625
2621
2626 if store_history:
2622 if store_history:
2627 result.execution_count = self.execution_count
2623 result.execution_count = self.execution_count
2628
2624
2629 def error_before_exec(value):
2625 def error_before_exec(value):
2630 result.error_before_exec = value
2626 result.error_before_exec = value
2631 self.last_execution_succeeded = False
2627 self.last_execution_succeeded = False
2632 return result
2628 return result
2633
2629
2634 self.events.trigger('pre_execute')
2630 self.events.trigger('pre_execute')
2635 if not silent:
2631 if not silent:
2636 self.events.trigger('pre_run_cell')
2632 self.events.trigger('pre_run_cell')
2637
2633
2638 # If any of our input transformation (input_transformer_manager or
2634 # If any of our input transformation (input_transformer_manager or
2639 # prefilter_manager) raises an exception, we store it in this variable
2635 # prefilter_manager) raises an exception, we store it in this variable
2640 # so that we can display the error after logging the input and storing
2636 # so that we can display the error after logging the input and storing
2641 # it in the history.
2637 # it in the history.
2642 preprocessing_exc_tuple = None
2638 preprocessing_exc_tuple = None
2643 try:
2639 try:
2644 # Static input transformations
2640 # Static input transformations
2645 cell = self.input_transformer_manager.transform_cell(raw_cell)
2641 cell = self.input_transformer_manager.transform_cell(raw_cell)
2646 except SyntaxError:
2642 except SyntaxError:
2647 preprocessing_exc_tuple = sys.exc_info()
2643 preprocessing_exc_tuple = sys.exc_info()
2648 cell = raw_cell # cell has to exist so it can be stored/logged
2644 cell = raw_cell # cell has to exist so it can be stored/logged
2649 else:
2645 else:
2650 if len(cell.splitlines()) == 1:
2646 if len(cell.splitlines()) == 1:
2651 # Dynamic transformations - only applied for single line commands
2647 # Dynamic transformations - only applied for single line commands
2652 with self.builtin_trap:
2648 with self.builtin_trap:
2653 try:
2649 try:
2654 # use prefilter_lines to handle trailing newlines
2650 # use prefilter_lines to handle trailing newlines
2655 # restore trailing newline for ast.parse
2651 # restore trailing newline for ast.parse
2656 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2652 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2657 except Exception:
2653 except Exception:
2658 # don't allow prefilter errors to crash IPython
2654 # don't allow prefilter errors to crash IPython
2659 preprocessing_exc_tuple = sys.exc_info()
2655 preprocessing_exc_tuple = sys.exc_info()
2660
2656
2661 # Store raw and processed history
2657 # Store raw and processed history
2662 if store_history:
2658 if store_history:
2663 self.history_manager.store_inputs(self.execution_count,
2659 self.history_manager.store_inputs(self.execution_count,
2664 cell, raw_cell)
2660 cell, raw_cell)
2665 if not silent:
2661 if not silent:
2666 self.logger.log(cell, raw_cell)
2662 self.logger.log(cell, raw_cell)
2667
2663
2668 # Display the exception if input processing failed.
2664 # Display the exception if input processing failed.
2669 if preprocessing_exc_tuple is not None:
2665 if preprocessing_exc_tuple is not None:
2670 self.showtraceback(preprocessing_exc_tuple)
2666 self.showtraceback(preprocessing_exc_tuple)
2671 if store_history:
2667 if store_history:
2672 self.execution_count += 1
2668 self.execution_count += 1
2673 return error_before_exec(preprocessing_exc_tuple[2])
2669 return error_before_exec(preprocessing_exc_tuple[2])
2674
2670
2675 # Our own compiler remembers the __future__ environment. If we want to
2671 # Our own compiler remembers the __future__ environment. If we want to
2676 # run code with a separate __future__ environment, use the default
2672 # run code with a separate __future__ environment, use the default
2677 # compiler
2673 # compiler
2678 compiler = self.compile if shell_futures else CachingCompiler()
2674 compiler = self.compile if shell_futures else CachingCompiler()
2679
2675
2680 with self.builtin_trap:
2676 with self.builtin_trap:
2681 cell_name = self.compile.cache(cell, self.execution_count)
2677 cell_name = self.compile.cache(cell, self.execution_count)
2682
2678
2683 with self.display_trap:
2679 with self.display_trap:
2684 # Compile to bytecode
2680 # Compile to bytecode
2685 try:
2681 try:
2686 code_ast = compiler.ast_parse(cell, filename=cell_name)
2682 code_ast = compiler.ast_parse(cell, filename=cell_name)
2687 except self.custom_exceptions as e:
2683 except self.custom_exceptions as e:
2688 etype, value, tb = sys.exc_info()
2684 etype, value, tb = sys.exc_info()
2689 self.CustomTB(etype, value, tb)
2685 self.CustomTB(etype, value, tb)
2690 return error_before_exec(e)
2686 return error_before_exec(e)
2691 except IndentationError as e:
2687 except IndentationError as e:
2692 self.showindentationerror()
2688 self.showindentationerror()
2693 if store_history:
2689 if store_history:
2694 self.execution_count += 1
2690 self.execution_count += 1
2695 return error_before_exec(e)
2691 return error_before_exec(e)
2696 except (OverflowError, SyntaxError, ValueError, TypeError,
2692 except (OverflowError, SyntaxError, ValueError, TypeError,
2697 MemoryError) as e:
2693 MemoryError) as e:
2698 self.showsyntaxerror()
2694 self.showsyntaxerror()
2699 if store_history:
2695 if store_history:
2700 self.execution_count += 1
2696 self.execution_count += 1
2701 return error_before_exec(e)
2697 return error_before_exec(e)
2702
2698
2703 # Apply AST transformations
2699 # Apply AST transformations
2704 try:
2700 try:
2705 code_ast = self.transform_ast(code_ast)
2701 code_ast = self.transform_ast(code_ast)
2706 except InputRejected as e:
2702 except InputRejected as e:
2707 self.showtraceback()
2703 self.showtraceback()
2708 if store_history:
2704 if store_history:
2709 self.execution_count += 1
2705 self.execution_count += 1
2710 return error_before_exec(e)
2706 return error_before_exec(e)
2711
2707
2712 # Give the displayhook a reference to our ExecutionResult so it
2708 # Give the displayhook a reference to our ExecutionResult so it
2713 # can fill in the output value.
2709 # can fill in the output value.
2714 self.displayhook.exec_result = result
2710 self.displayhook.exec_result = result
2715
2711
2716 # Execute the user code
2712 # Execute the user code
2717 interactivity = "none" if silent else self.ast_node_interactivity
2713 interactivity = "none" if silent else self.ast_node_interactivity
2718 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2714 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2719 interactivity=interactivity, compiler=compiler, result=result)
2715 interactivity=interactivity, compiler=compiler, result=result)
2720
2716
2721 self.last_execution_succeeded = not has_raised
2717 self.last_execution_succeeded = not has_raised
2722
2718
2723 # Reset this so later displayed values do not modify the
2719 # Reset this so later displayed values do not modify the
2724 # ExecutionResult
2720 # ExecutionResult
2725 self.displayhook.exec_result = None
2721 self.displayhook.exec_result = None
2726
2722
2727 self.events.trigger('post_execute')
2723 self.events.trigger('post_execute')
2728 if not silent:
2724 if not silent:
2729 self.events.trigger('post_run_cell')
2725 self.events.trigger('post_run_cell')
2730
2726
2731 if store_history:
2727 if store_history:
2732 # Write output to the database. Does nothing unless
2728 # Write output to the database. Does nothing unless
2733 # history output logging is enabled.
2729 # history output logging is enabled.
2734 self.history_manager.store_output(self.execution_count)
2730 self.history_manager.store_output(self.execution_count)
2735 # Each cell is a *single* input, regardless of how many lines it has
2731 # Each cell is a *single* input, regardless of how many lines it has
2736 self.execution_count += 1
2732 self.execution_count += 1
2737
2733
2738 return result
2734 return result
2739
2735
2740 def transform_ast(self, node):
2736 def transform_ast(self, node):
2741 """Apply the AST transformations from self.ast_transformers
2737 """Apply the AST transformations from self.ast_transformers
2742
2738
2743 Parameters
2739 Parameters
2744 ----------
2740 ----------
2745 node : ast.Node
2741 node : ast.Node
2746 The root node to be transformed. Typically called with the ast.Module
2742 The root node to be transformed. Typically called with the ast.Module
2747 produced by parsing user input.
2743 produced by parsing user input.
2748
2744
2749 Returns
2745 Returns
2750 -------
2746 -------
2751 An ast.Node corresponding to the node it was called with. Note that it
2747 An ast.Node corresponding to the node it was called with. Note that it
2752 may also modify the passed object, so don't rely on references to the
2748 may also modify the passed object, so don't rely on references to the
2753 original AST.
2749 original AST.
2754 """
2750 """
2755 for transformer in self.ast_transformers:
2751 for transformer in self.ast_transformers:
2756 try:
2752 try:
2757 node = transformer.visit(node)
2753 node = transformer.visit(node)
2758 except InputRejected:
2754 except InputRejected:
2759 # User-supplied AST transformers can reject an input by raising
2755 # User-supplied AST transformers can reject an input by raising
2760 # an InputRejected. Short-circuit in this case so that we
2756 # an InputRejected. Short-circuit in this case so that we
2761 # don't unregister the transform.
2757 # don't unregister the transform.
2762 raise
2758 raise
2763 except Exception:
2759 except Exception:
2764 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2760 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2765 self.ast_transformers.remove(transformer)
2761 self.ast_transformers.remove(transformer)
2766
2762
2767 if self.ast_transformers:
2763 if self.ast_transformers:
2768 ast.fix_missing_locations(node)
2764 ast.fix_missing_locations(node)
2769 return node
2765 return node
2770
2766
2771
2767
2772 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2768 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2773 compiler=compile, result=None):
2769 compiler=compile, result=None):
2774 """Run a sequence of AST nodes. The execution mode depends on the
2770 """Run a sequence of AST nodes. The execution mode depends on the
2775 interactivity parameter.
2771 interactivity parameter.
2776
2772
2777 Parameters
2773 Parameters
2778 ----------
2774 ----------
2779 nodelist : list
2775 nodelist : list
2780 A sequence of AST nodes to run.
2776 A sequence of AST nodes to run.
2781 cell_name : str
2777 cell_name : str
2782 Will be passed to the compiler as the filename of the cell. Typically
2778 Will be passed to the compiler as the filename of the cell. Typically
2783 the value returned by ip.compile.cache(cell).
2779 the value returned by ip.compile.cache(cell).
2784 interactivity : str
2780 interactivity : str
2785 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2781 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2786 specifying which nodes should be run interactively (displaying output
2782 specifying which nodes should be run interactively (displaying output
2787 from expressions). 'last_expr' will run the last node interactively
2783 from expressions). 'last_expr' will run the last node interactively
2788 only if it is an expression (i.e. expressions in loops or other blocks
2784 only if it is an expression (i.e. expressions in loops or other blocks
2789 are not displayed) 'last_expr_or_assign' will run the last expression
2785 are not displayed) 'last_expr_or_assign' will run the last expression
2790 or the last assignment. Other values for this parameter will raise a
2786 or the last assignment. Other values for this parameter will raise a
2791 ValueError.
2787 ValueError.
2792 compiler : callable
2788 compiler : callable
2793 A function with the same interface as the built-in compile(), to turn
2789 A function with the same interface as the built-in compile(), to turn
2794 the AST nodes into code objects. Default is the built-in compile().
2790 the AST nodes into code objects. Default is the built-in compile().
2795 result : ExecutionResult, optional
2791 result : ExecutionResult, optional
2796 An object to store exceptions that occur during execution.
2792 An object to store exceptions that occur during execution.
2797
2793
2798 Returns
2794 Returns
2799 -------
2795 -------
2800 True if an exception occurred while running code, False if it finished
2796 True if an exception occurred while running code, False if it finished
2801 running.
2797 running.
2802 """
2798 """
2803 if not nodelist:
2799 if not nodelist:
2804 return
2800 return
2805
2801
2806 if interactivity == 'last_expr_or_assign':
2802 if interactivity == 'last_expr_or_assign':
2807 if isinstance(nodelist[-1], _assign_nodes):
2803 if isinstance(nodelist[-1], _assign_nodes):
2808 asg = nodelist[-1]
2804 asg = nodelist[-1]
2809 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2805 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2810 target = asg.targets[0]
2806 target = asg.targets[0]
2811 elif isinstance(asg, _single_targets_nodes):
2807 elif isinstance(asg, _single_targets_nodes):
2812 target = asg.target
2808 target = asg.target
2813 else:
2809 else:
2814 target = None
2810 target = None
2815 if isinstance(target, ast.Name):
2811 if isinstance(target, ast.Name):
2816 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2812 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2817 ast.fix_missing_locations(nnode)
2813 ast.fix_missing_locations(nnode)
2818 nodelist.append(nnode)
2814 nodelist.append(nnode)
2819 interactivity = 'last_expr'
2815 interactivity = 'last_expr'
2820
2816
2821 if interactivity == 'last_expr':
2817 if interactivity == 'last_expr':
2822 if isinstance(nodelist[-1], ast.Expr):
2818 if isinstance(nodelist[-1], ast.Expr):
2823 interactivity = "last"
2819 interactivity = "last"
2824 else:
2820 else:
2825 interactivity = "none"
2821 interactivity = "none"
2826
2822
2827 if interactivity == 'none':
2823 if interactivity == 'none':
2828 to_run_exec, to_run_interactive = nodelist, []
2824 to_run_exec, to_run_interactive = nodelist, []
2829 elif interactivity == 'last':
2825 elif interactivity == 'last':
2830 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2826 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2831 elif interactivity == 'all':
2827 elif interactivity == 'all':
2832 to_run_exec, to_run_interactive = [], nodelist
2828 to_run_exec, to_run_interactive = [], nodelist
2833 else:
2829 else:
2834 raise ValueError("Interactivity was %r" % interactivity)
2830 raise ValueError("Interactivity was %r" % interactivity)
2835
2831
2836 try:
2832 try:
2837 for i, node in enumerate(to_run_exec):
2833 for i, node in enumerate(to_run_exec):
2838 mod = ast.Module([node])
2834 mod = ast.Module([node])
2839 code = compiler(mod, cell_name, "exec")
2835 code = compiler(mod, cell_name, "exec")
2840 if self.run_code(code, result):
2836 if self.run_code(code, result):
2841 return True
2837 return True
2842
2838
2843 for i, node in enumerate(to_run_interactive):
2839 for i, node in enumerate(to_run_interactive):
2844 mod = ast.Interactive([node])
2840 mod = ast.Interactive([node])
2845 code = compiler(mod, cell_name, "single")
2841 code = compiler(mod, cell_name, "single")
2846 if self.run_code(code, result):
2842 if self.run_code(code, result):
2847 return True
2843 return True
2848
2844
2849 # Flush softspace
2845 # Flush softspace
2850 if softspace(sys.stdout, 0):
2846 if softspace(sys.stdout, 0):
2851 print()
2847 print()
2852
2848
2853 except:
2849 except:
2854 # It's possible to have exceptions raised here, typically by
2850 # It's possible to have exceptions raised here, typically by
2855 # compilation of odd code (such as a naked 'return' outside a
2851 # compilation of odd code (such as a naked 'return' outside a
2856 # function) that did parse but isn't valid. Typically the exception
2852 # function) that did parse but isn't valid. Typically the exception
2857 # is a SyntaxError, but it's safest just to catch anything and show
2853 # is a SyntaxError, but it's safest just to catch anything and show
2858 # the user a traceback.
2854 # the user a traceback.
2859
2855
2860 # We do only one try/except outside the loop to minimize the impact
2856 # We do only one try/except outside the loop to minimize the impact
2861 # on runtime, and also because if any node in the node list is
2857 # on runtime, and also because if any node in the node list is
2862 # broken, we should stop execution completely.
2858 # broken, we should stop execution completely.
2863 if result:
2859 if result:
2864 result.error_before_exec = sys.exc_info()[1]
2860 result.error_before_exec = sys.exc_info()[1]
2865 self.showtraceback()
2861 self.showtraceback()
2866 return True
2862 return True
2867
2863
2868 return False
2864 return False
2869
2865
2870 def run_code(self, code_obj, result=None):
2866 def run_code(self, code_obj, result=None):
2871 """Execute a code object.
2867 """Execute a code object.
2872
2868
2873 When an exception occurs, self.showtraceback() is called to display a
2869 When an exception occurs, self.showtraceback() is called to display a
2874 traceback.
2870 traceback.
2875
2871
2876 Parameters
2872 Parameters
2877 ----------
2873 ----------
2878 code_obj : code object
2874 code_obj : code object
2879 A compiled code object, to be executed
2875 A compiled code object, to be executed
2880 result : ExecutionResult, optional
2876 result : ExecutionResult, optional
2881 An object to store exceptions that occur during execution.
2877 An object to store exceptions that occur during execution.
2882
2878
2883 Returns
2879 Returns
2884 -------
2880 -------
2885 False : successful execution.
2881 False : successful execution.
2886 True : an error occurred.
2882 True : an error occurred.
2887 """
2883 """
2888 # Set our own excepthook in case the user code tries to call it
2884 # Set our own excepthook in case the user code tries to call it
2889 # directly, so that the IPython crash handler doesn't get triggered
2885 # directly, so that the IPython crash handler doesn't get triggered
2890 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2886 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2891
2887
2892 # we save the original sys.excepthook in the instance, in case config
2888 # we save the original sys.excepthook in the instance, in case config
2893 # code (such as magics) needs access to it.
2889 # code (such as magics) needs access to it.
2894 self.sys_excepthook = old_excepthook
2890 self.sys_excepthook = old_excepthook
2895 outflag = True # happens in more places, so it's easier as default
2891 outflag = True # happens in more places, so it's easier as default
2896 try:
2892 try:
2897 try:
2893 try:
2898 self.hooks.pre_run_code_hook()
2894 self.hooks.pre_run_code_hook()
2899 #rprint('Running code', repr(code_obj)) # dbg
2895 #rprint('Running code', repr(code_obj)) # dbg
2900 exec(code_obj, self.user_global_ns, self.user_ns)
2896 exec(code_obj, self.user_global_ns, self.user_ns)
2901 finally:
2897 finally:
2902 # Reset our crash handler in place
2898 # Reset our crash handler in place
2903 sys.excepthook = old_excepthook
2899 sys.excepthook = old_excepthook
2904 except SystemExit as e:
2900 except SystemExit as e:
2905 if result is not None:
2901 if result is not None:
2906 result.error_in_exec = e
2902 result.error_in_exec = e
2907 self.showtraceback(exception_only=True)
2903 self.showtraceback(exception_only=True)
2908 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2904 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2909 except self.custom_exceptions:
2905 except self.custom_exceptions:
2910 etype, value, tb = sys.exc_info()
2906 etype, value, tb = sys.exc_info()
2911 if result is not None:
2907 if result is not None:
2912 result.error_in_exec = value
2908 result.error_in_exec = value
2913 self.CustomTB(etype, value, tb)
2909 self.CustomTB(etype, value, tb)
2914 except:
2910 except:
2915 if result is not None:
2911 if result is not None:
2916 result.error_in_exec = sys.exc_info()[1]
2912 result.error_in_exec = sys.exc_info()[1]
2917 self.showtraceback(running_compiled_code=True)
2913 self.showtraceback(running_compiled_code=True)
2918 else:
2914 else:
2919 outflag = False
2915 outflag = False
2920 return outflag
2916 return outflag
2921
2917
2922 # For backwards compatibility
2918 # For backwards compatibility
2923 runcode = run_code
2919 runcode = run_code
2924
2920
2925 #-------------------------------------------------------------------------
2921 #-------------------------------------------------------------------------
2926 # Things related to GUI support and pylab
2922 # Things related to GUI support and pylab
2927 #-------------------------------------------------------------------------
2923 #-------------------------------------------------------------------------
2928
2924
2929 active_eventloop = None
2925 active_eventloop = None
2930
2926
2931 def enable_gui(self, gui=None):
2927 def enable_gui(self, gui=None):
2932 raise NotImplementedError('Implement enable_gui in a subclass')
2928 raise NotImplementedError('Implement enable_gui in a subclass')
2933
2929
2934 def enable_matplotlib(self, gui=None):
2930 def enable_matplotlib(self, gui=None):
2935 """Enable interactive matplotlib and inline figure support.
2931 """Enable interactive matplotlib and inline figure support.
2936
2932
2937 This takes the following steps:
2933 This takes the following steps:
2938
2934
2939 1. select the appropriate eventloop and matplotlib backend
2935 1. select the appropriate eventloop and matplotlib backend
2940 2. set up matplotlib for interactive use with that backend
2936 2. set up matplotlib for interactive use with that backend
2941 3. configure formatters for inline figure display
2937 3. configure formatters for inline figure display
2942 4. enable the selected gui eventloop
2938 4. enable the selected gui eventloop
2943
2939
2944 Parameters
2940 Parameters
2945 ----------
2941 ----------
2946 gui : optional, string
2942 gui : optional, string
2947 If given, dictates the choice of matplotlib GUI backend to use
2943 If given, dictates the choice of matplotlib GUI backend to use
2948 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2944 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2949 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2945 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2950 matplotlib (as dictated by the matplotlib build-time options plus the
2946 matplotlib (as dictated by the matplotlib build-time options plus the
2951 user's matplotlibrc configuration file). Note that not all backends
2947 user's matplotlibrc configuration file). Note that not all backends
2952 make sense in all contexts, for example a terminal ipython can't
2948 make sense in all contexts, for example a terminal ipython can't
2953 display figures inline.
2949 display figures inline.
2954 """
2950 """
2955 from IPython.core import pylabtools as pt
2951 from IPython.core import pylabtools as pt
2956 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2952 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2957
2953
2958 if gui != 'inline':
2954 if gui != 'inline':
2959 # If we have our first gui selection, store it
2955 # If we have our first gui selection, store it
2960 if self.pylab_gui_select is None:
2956 if self.pylab_gui_select is None:
2961 self.pylab_gui_select = gui
2957 self.pylab_gui_select = gui
2962 # Otherwise if they are different
2958 # Otherwise if they are different
2963 elif gui != self.pylab_gui_select:
2959 elif gui != self.pylab_gui_select:
2964 print('Warning: Cannot change to a different GUI toolkit: %s.'
2960 print('Warning: Cannot change to a different GUI toolkit: %s.'
2965 ' Using %s instead.' % (gui, self.pylab_gui_select))
2961 ' Using %s instead.' % (gui, self.pylab_gui_select))
2966 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2962 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2967
2963
2968 pt.activate_matplotlib(backend)
2964 pt.activate_matplotlib(backend)
2969 pt.configure_inline_support(self, backend)
2965 pt.configure_inline_support(self, backend)
2970
2966
2971 # Now we must activate the gui pylab wants to use, and fix %run to take
2967 # Now we must activate the gui pylab wants to use, and fix %run to take
2972 # plot updates into account
2968 # plot updates into account
2973 self.enable_gui(gui)
2969 self.enable_gui(gui)
2974 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2970 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2975 pt.mpl_runner(self.safe_execfile)
2971 pt.mpl_runner(self.safe_execfile)
2976
2972
2977 return gui, backend
2973 return gui, backend
2978
2974
2979 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2975 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2980 """Activate pylab support at runtime.
2976 """Activate pylab support at runtime.
2981
2977
2982 This turns on support for matplotlib, preloads into the interactive
2978 This turns on support for matplotlib, preloads into the interactive
2983 namespace all of numpy and pylab, and configures IPython to correctly
2979 namespace all of numpy and pylab, and configures IPython to correctly
2984 interact with the GUI event loop. The GUI backend to be used can be
2980 interact with the GUI event loop. The GUI backend to be used can be
2985 optionally selected with the optional ``gui`` argument.
2981 optionally selected with the optional ``gui`` argument.
2986
2982
2987 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2983 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2988
2984
2989 Parameters
2985 Parameters
2990 ----------
2986 ----------
2991 gui : optional, string
2987 gui : optional, string
2992 If given, dictates the choice of matplotlib GUI backend to use
2988 If given, dictates the choice of matplotlib GUI backend to use
2993 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2989 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2994 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2990 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2995 matplotlib (as dictated by the matplotlib build-time options plus the
2991 matplotlib (as dictated by the matplotlib build-time options plus the
2996 user's matplotlibrc configuration file). Note that not all backends
2992 user's matplotlibrc configuration file). Note that not all backends
2997 make sense in all contexts, for example a terminal ipython can't
2993 make sense in all contexts, for example a terminal ipython can't
2998 display figures inline.
2994 display figures inline.
2999 import_all : optional, bool, default: True
2995 import_all : optional, bool, default: True
3000 Whether to do `from numpy import *` and `from pylab import *`
2996 Whether to do `from numpy import *` and `from pylab import *`
3001 in addition to module imports.
2997 in addition to module imports.
3002 welcome_message : deprecated
2998 welcome_message : deprecated
3003 This argument is ignored, no welcome message will be displayed.
2999 This argument is ignored, no welcome message will be displayed.
3004 """
3000 """
3005 from IPython.core.pylabtools import import_pylab
3001 from IPython.core.pylabtools import import_pylab
3006
3002
3007 gui, backend = self.enable_matplotlib(gui)
3003 gui, backend = self.enable_matplotlib(gui)
3008
3004
3009 # We want to prevent the loading of pylab to pollute the user's
3005 # We want to prevent the loading of pylab to pollute the user's
3010 # namespace as shown by the %who* magics, so we execute the activation
3006 # namespace as shown by the %who* magics, so we execute the activation
3011 # code in an empty namespace, and we update *both* user_ns and
3007 # code in an empty namespace, and we update *both* user_ns and
3012 # user_ns_hidden with this information.
3008 # user_ns_hidden with this information.
3013 ns = {}
3009 ns = {}
3014 import_pylab(ns, import_all)
3010 import_pylab(ns, import_all)
3015 # warn about clobbered names
3011 # warn about clobbered names
3016 ignored = {"__builtins__"}
3012 ignored = {"__builtins__"}
3017 both = set(ns).intersection(self.user_ns).difference(ignored)
3013 both = set(ns).intersection(self.user_ns).difference(ignored)
3018 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3014 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3019 self.user_ns.update(ns)
3015 self.user_ns.update(ns)
3020 self.user_ns_hidden.update(ns)
3016 self.user_ns_hidden.update(ns)
3021 return gui, backend, clobbered
3017 return gui, backend, clobbered
3022
3018
3023 #-------------------------------------------------------------------------
3019 #-------------------------------------------------------------------------
3024 # Utilities
3020 # Utilities
3025 #-------------------------------------------------------------------------
3021 #-------------------------------------------------------------------------
3026
3022
3027 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3023 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3028 """Expand python variables in a string.
3024 """Expand python variables in a string.
3029
3025
3030 The depth argument indicates how many frames above the caller should
3026 The depth argument indicates how many frames above the caller should
3031 be walked to look for the local namespace where to expand variables.
3027 be walked to look for the local namespace where to expand variables.
3032
3028
3033 The global namespace for expansion is always the user's interactive
3029 The global namespace for expansion is always the user's interactive
3034 namespace.
3030 namespace.
3035 """
3031 """
3036 ns = self.user_ns.copy()
3032 ns = self.user_ns.copy()
3037 try:
3033 try:
3038 frame = sys._getframe(depth+1)
3034 frame = sys._getframe(depth+1)
3039 except ValueError:
3035 except ValueError:
3040 # This is thrown if there aren't that many frames on the stack,
3036 # This is thrown if there aren't that many frames on the stack,
3041 # e.g. if a script called run_line_magic() directly.
3037 # e.g. if a script called run_line_magic() directly.
3042 pass
3038 pass
3043 else:
3039 else:
3044 ns.update(frame.f_locals)
3040 ns.update(frame.f_locals)
3045
3041
3046 try:
3042 try:
3047 # We have to use .vformat() here, because 'self' is a valid and common
3043 # We have to use .vformat() here, because 'self' is a valid and common
3048 # name, and expanding **ns for .format() would make it collide with
3044 # name, and expanding **ns for .format() would make it collide with
3049 # the 'self' argument of the method.
3045 # the 'self' argument of the method.
3050 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3046 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3051 except Exception:
3047 except Exception:
3052 # if formatter couldn't format, just let it go untransformed
3048 # if formatter couldn't format, just let it go untransformed
3053 pass
3049 pass
3054 return cmd
3050 return cmd
3055
3051
3056 def mktempfile(self, data=None, prefix='ipython_edit_'):
3052 def mktempfile(self, data=None, prefix='ipython_edit_'):
3057 """Make a new tempfile and return its filename.
3053 """Make a new tempfile and return its filename.
3058
3054
3059 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3055 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3060 but it registers the created filename internally so ipython cleans it up
3056 but it registers the created filename internally so ipython cleans it up
3061 at exit time.
3057 at exit time.
3062
3058
3063 Optional inputs:
3059 Optional inputs:
3064
3060
3065 - data(None): if data is given, it gets written out to the temp file
3061 - data(None): if data is given, it gets written out to the temp file
3066 immediately, and the file is closed again."""
3062 immediately, and the file is closed again."""
3067
3063
3068 dirname = tempfile.mkdtemp(prefix=prefix)
3064 dirname = tempfile.mkdtemp(prefix=prefix)
3069 self.tempdirs.append(dirname)
3065 self.tempdirs.append(dirname)
3070
3066
3071 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3067 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3072 os.close(handle) # On Windows, there can only be one open handle on a file
3068 os.close(handle) # On Windows, there can only be one open handle on a file
3073 self.tempfiles.append(filename)
3069 self.tempfiles.append(filename)
3074
3070
3075 if data:
3071 if data:
3076 tmp_file = open(filename,'w')
3072 tmp_file = open(filename,'w')
3077 tmp_file.write(data)
3073 tmp_file.write(data)
3078 tmp_file.close()
3074 tmp_file.close()
3079 return filename
3075 return filename
3080
3076
3081 @undoc
3077 @undoc
3082 def write(self,data):
3078 def write(self,data):
3083 """DEPRECATED: Write a string to the default output"""
3079 """DEPRECATED: Write a string to the default output"""
3084 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3080 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3085 DeprecationWarning, stacklevel=2)
3081 DeprecationWarning, stacklevel=2)
3086 sys.stdout.write(data)
3082 sys.stdout.write(data)
3087
3083
3088 @undoc
3084 @undoc
3089 def write_err(self,data):
3085 def write_err(self,data):
3090 """DEPRECATED: Write a string to the default error output"""
3086 """DEPRECATED: Write a string to the default error output"""
3091 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3087 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3092 DeprecationWarning, stacklevel=2)
3088 DeprecationWarning, stacklevel=2)
3093 sys.stderr.write(data)
3089 sys.stderr.write(data)
3094
3090
3095 def ask_yes_no(self, prompt, default=None, interrupt=None):
3091 def ask_yes_no(self, prompt, default=None, interrupt=None):
3096 if self.quiet:
3092 if self.quiet:
3097 return True
3093 return True
3098 return ask_yes_no(prompt,default,interrupt)
3094 return ask_yes_no(prompt,default,interrupt)
3099
3095
3100 def show_usage(self):
3096 def show_usage(self):
3101 """Show a usage message"""
3097 """Show a usage message"""
3102 page.page(IPython.core.usage.interactive_usage)
3098 page.page(IPython.core.usage.interactive_usage)
3103
3099
3104 def extract_input_lines(self, range_str, raw=False):
3100 def extract_input_lines(self, range_str, raw=False):
3105 """Return as a string a set of input history slices.
3101 """Return as a string a set of input history slices.
3106
3102
3107 Parameters
3103 Parameters
3108 ----------
3104 ----------
3109 range_str : string
3105 range_str : string
3110 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3106 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3111 since this function is for use by magic functions which get their
3107 since this function is for use by magic functions which get their
3112 arguments as strings. The number before the / is the session
3108 arguments as strings. The number before the / is the session
3113 number: ~n goes n back from the current session.
3109 number: ~n goes n back from the current session.
3114
3110
3115 raw : bool, optional
3111 raw : bool, optional
3116 By default, the processed input is used. If this is true, the raw
3112 By default, the processed input is used. If this is true, the raw
3117 input history is used instead.
3113 input history is used instead.
3118
3114
3119 Notes
3115 Notes
3120 -----
3116 -----
3121
3117
3122 Slices can be described with two notations:
3118 Slices can be described with two notations:
3123
3119
3124 * ``N:M`` -> standard python form, means including items N...(M-1).
3120 * ``N:M`` -> standard python form, means including items N...(M-1).
3125 * ``N-M`` -> include items N..M (closed endpoint).
3121 * ``N-M`` -> include items N..M (closed endpoint).
3126 """
3122 """
3127 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3123 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3128 return "\n".join(x for _, _, x in lines)
3124 return "\n".join(x for _, _, x in lines)
3129
3125
3130 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3126 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3131 """Get a code string from history, file, url, or a string or macro.
3127 """Get a code string from history, file, url, or a string or macro.
3132
3128
3133 This is mainly used by magic functions.
3129 This is mainly used by magic functions.
3134
3130
3135 Parameters
3131 Parameters
3136 ----------
3132 ----------
3137
3133
3138 target : str
3134 target : str
3139
3135
3140 A string specifying code to retrieve. This will be tried respectively
3136 A string specifying code to retrieve. This will be tried respectively
3141 as: ranges of input history (see %history for syntax), url,
3137 as: ranges of input history (see %history for syntax), url,
3142 corresponding .py file, filename, or an expression evaluating to a
3138 corresponding .py file, filename, or an expression evaluating to a
3143 string or Macro in the user namespace.
3139 string or Macro in the user namespace.
3144
3140
3145 raw : bool
3141 raw : bool
3146 If true (default), retrieve raw history. Has no effect on the other
3142 If true (default), retrieve raw history. Has no effect on the other
3147 retrieval mechanisms.
3143 retrieval mechanisms.
3148
3144
3149 py_only : bool (default False)
3145 py_only : bool (default False)
3150 Only try to fetch python code, do not try alternative methods to decode file
3146 Only try to fetch python code, do not try alternative methods to decode file
3151 if unicode fails.
3147 if unicode fails.
3152
3148
3153 Returns
3149 Returns
3154 -------
3150 -------
3155 A string of code.
3151 A string of code.
3156
3152
3157 ValueError is raised if nothing is found, and TypeError if it evaluates
3153 ValueError is raised if nothing is found, and TypeError if it evaluates
3158 to an object of another type. In each case, .args[0] is a printable
3154 to an object of another type. In each case, .args[0] is a printable
3159 message.
3155 message.
3160 """
3156 """
3161 code = self.extract_input_lines(target, raw=raw) # Grab history
3157 code = self.extract_input_lines(target, raw=raw) # Grab history
3162 if code:
3158 if code:
3163 return code
3159 return code
3164 try:
3160 try:
3165 if target.startswith(('http://', 'https://')):
3161 if target.startswith(('http://', 'https://')):
3166 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3162 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3167 except UnicodeDecodeError:
3163 except UnicodeDecodeError:
3168 if not py_only :
3164 if not py_only :
3169 # Deferred import
3165 # Deferred import
3170 from urllib.request import urlopen
3166 from urllib.request import urlopen
3171 response = urlopen(target)
3167 response = urlopen(target)
3172 return response.read().decode('latin1')
3168 return response.read().decode('latin1')
3173 raise ValueError(("'%s' seem to be unreadable.") % target)
3169 raise ValueError(("'%s' seem to be unreadable.") % target)
3174
3170
3175 potential_target = [target]
3171 potential_target = [target]
3176 try :
3172 try :
3177 potential_target.insert(0,get_py_filename(target))
3173 potential_target.insert(0,get_py_filename(target))
3178 except IOError:
3174 except IOError:
3179 pass
3175 pass
3180
3176
3181 for tgt in potential_target :
3177 for tgt in potential_target :
3182 if os.path.isfile(tgt): # Read file
3178 if os.path.isfile(tgt): # Read file
3183 try :
3179 try :
3184 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3180 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3185 except UnicodeDecodeError :
3181 except UnicodeDecodeError :
3186 if not py_only :
3182 if not py_only :
3187 with io_open(tgt,'r', encoding='latin1') as f :
3183 with io_open(tgt,'r', encoding='latin1') as f :
3188 return f.read()
3184 return f.read()
3189 raise ValueError(("'%s' seem to be unreadable.") % target)
3185 raise ValueError(("'%s' seem to be unreadable.") % target)
3190 elif os.path.isdir(os.path.expanduser(tgt)):
3186 elif os.path.isdir(os.path.expanduser(tgt)):
3191 raise ValueError("'%s' is a directory, not a regular file." % target)
3187 raise ValueError("'%s' is a directory, not a regular file." % target)
3192
3188
3193 if search_ns:
3189 if search_ns:
3194 # Inspect namespace to load object source
3190 # Inspect namespace to load object source
3195 object_info = self.object_inspect(target, detail_level=1)
3191 object_info = self.object_inspect(target, detail_level=1)
3196 if object_info['found'] and object_info['source']:
3192 if object_info['found'] and object_info['source']:
3197 return object_info['source']
3193 return object_info['source']
3198
3194
3199 try: # User namespace
3195 try: # User namespace
3200 codeobj = eval(target, self.user_ns)
3196 codeobj = eval(target, self.user_ns)
3201 except Exception:
3197 except Exception:
3202 raise ValueError(("'%s' was not found in history, as a file, url, "
3198 raise ValueError(("'%s' was not found in history, as a file, url, "
3203 "nor in the user namespace.") % target)
3199 "nor in the user namespace.") % target)
3204
3200
3205 if isinstance(codeobj, str):
3201 if isinstance(codeobj, str):
3206 return codeobj
3202 return codeobj
3207 elif isinstance(codeobj, Macro):
3203 elif isinstance(codeobj, Macro):
3208 return codeobj.value
3204 return codeobj.value
3209
3205
3210 raise TypeError("%s is neither a string nor a macro." % target,
3206 raise TypeError("%s is neither a string nor a macro." % target,
3211 codeobj)
3207 codeobj)
3212
3208
3213 #-------------------------------------------------------------------------
3209 #-------------------------------------------------------------------------
3214 # Things related to IPython exiting
3210 # Things related to IPython exiting
3215 #-------------------------------------------------------------------------
3211 #-------------------------------------------------------------------------
3216 def atexit_operations(self):
3212 def atexit_operations(self):
3217 """This will be executed at the time of exit.
3213 """This will be executed at the time of exit.
3218
3214
3219 Cleanup operations and saving of persistent data that is done
3215 Cleanup operations and saving of persistent data that is done
3220 unconditionally by IPython should be performed here.
3216 unconditionally by IPython should be performed here.
3221
3217
3222 For things that may depend on startup flags or platform specifics (such
3218 For things that may depend on startup flags or platform specifics (such
3223 as having readline or not), register a separate atexit function in the
3219 as having readline or not), register a separate atexit function in the
3224 code that has the appropriate information, rather than trying to
3220 code that has the appropriate information, rather than trying to
3225 clutter
3221 clutter
3226 """
3222 """
3227 # Close the history session (this stores the end time and line count)
3223 # Close the history session (this stores the end time and line count)
3228 # this must be *before* the tempfile cleanup, in case of temporary
3224 # this must be *before* the tempfile cleanup, in case of temporary
3229 # history db
3225 # history db
3230 self.history_manager.end_session()
3226 self.history_manager.end_session()
3231
3227
3232 # Cleanup all tempfiles and folders left around
3228 # Cleanup all tempfiles and folders left around
3233 for tfile in self.tempfiles:
3229 for tfile in self.tempfiles:
3234 try:
3230 try:
3235 os.unlink(tfile)
3231 os.unlink(tfile)
3236 except OSError:
3232 except OSError:
3237 pass
3233 pass
3238
3234
3239 for tdir in self.tempdirs:
3235 for tdir in self.tempdirs:
3240 try:
3236 try:
3241 os.rmdir(tdir)
3237 os.rmdir(tdir)
3242 except OSError:
3238 except OSError:
3243 pass
3239 pass
3244
3240
3245 # Clear all user namespaces to release all references cleanly.
3241 # Clear all user namespaces to release all references cleanly.
3246 self.reset(new_session=False)
3242 self.reset(new_session=False)
3247
3243
3248 # Run user hooks
3244 # Run user hooks
3249 self.hooks.shutdown_hook()
3245 self.hooks.shutdown_hook()
3250
3246
3251 def cleanup(self):
3247 def cleanup(self):
3252 self.restore_sys_module_state()
3248 self.restore_sys_module_state()
3253
3249
3254
3250
3255 # Overridden in terminal subclass to change prompts
3251 # Overridden in terminal subclass to change prompts
3256 def switch_doctest_mode(self, mode):
3252 def switch_doctest_mode(self, mode):
3257 pass
3253 pass
3258
3254
3259
3255
3260 class InteractiveShellABC(metaclass=abc.ABCMeta):
3256 class InteractiveShellABC(metaclass=abc.ABCMeta):
3261 """An abstract base class for InteractiveShell."""
3257 """An abstract base class for InteractiveShell."""
3262
3258
3263 InteractiveShellABC.register(InteractiveShell)
3259 InteractiveShellABC.register(InteractiveShell)
@@ -1,97 +1,97 b''
1 """Tests for input handlers.
1 """Tests for input handlers.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # third party
7 # third party
8 import nose.tools as nt
8 import nose.tools as nt
9
9
10 # our own packages
10 # our own packages
11 from IPython.core import autocall
11 from IPython.core import autocall
12 from IPython.testing import tools as tt
12 from IPython.testing import tools as tt
13 from IPython.testing.globalipapp import get_ipython
13 from IPython.testing.globalipapp import get_ipython
14 from IPython.utils import py3compat
14 from IPython.utils import py3compat
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Globals
17 # Globals
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 # Get the public instance of IPython
20 # Get the public instance of IPython
21 ip = get_ipython()
21 ip = get_ipython()
22
22
23 failures = []
23 failures = []
24 num_tests = 0
24 num_tests = 0
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class CallableIndexable(object):
30 class CallableIndexable(object):
31 def __getitem__(self, idx): return True
31 def __getitem__(self, idx): return True
32 def __call__(self, *args, **kws): return True
32 def __call__(self, *args, **kws): return True
33
33
34
34
35 class Autocallable(autocall.IPyAutocall):
35 class Autocallable(autocall.IPyAutocall):
36 def __call__(self):
36 def __call__(self):
37 return "called"
37 return "called"
38
38
39
39
40 def run(tests):
40 def run(tests):
41 """Loop through a list of (pre, post) inputs, where pre is the string
41 """Loop through a list of (pre, post) inputs, where pre is the string
42 handed to ipython, and post is how that string looks after it's been
42 handed to ipython, and post is how that string looks after it's been
43 transformed (i.e. ipython's notion of _i)"""
43 transformed (i.e. ipython's notion of _i)"""
44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
45
45
46
46
47 def test_handlers():
47 def test_handlers():
48 call_idx = CallableIndexable()
48 call_idx = CallableIndexable()
49 ip.user_ns['call_idx'] = call_idx
49 ip.user_ns['call_idx'] = call_idx
50
50
51 # For many of the below, we're also checking that leading whitespace
51 # For many of the below, we're also checking that leading whitespace
52 # turns off the esc char, which it should unless there is a continuation
52 # turns off the esc char, which it should unless there is a continuation
53 # line.
53 # line.
54 run([(i,py3compat.u_format(o)) for i,o in \
54 run([(i,py3compat.u_format(o)) for i,o in \
55 [('"no change"', '"no change"'), # normal
55 [('"no change"', '"no change"'), # normal
56 (u"lsmagic", "get_ipython().run_line_magic({u}'lsmagic', {u}'')"), # magic
56 (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic
57 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
57 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
58 ]])
58 ]])
59
59
60 # Objects which are instances of IPyAutocall are *always* autocalled
60 # Objects which are instances of IPyAutocall are *always* autocalled
61 autocallable = Autocallable()
61 autocallable = Autocallable()
62 ip.user_ns['autocallable'] = autocallable
62 ip.user_ns['autocallable'] = autocallable
63
63
64 # auto
64 # auto
65 ip.magic('autocall 0')
65 ip.magic('autocall 0')
66 # Only explicit escapes or instances of IPyAutocallable should get
66 # Only explicit escapes or instances of IPyAutocallable should get
67 # expanded
67 # expanded
68 run([
68 run([
69 ('len "abc"', 'len "abc"'),
69 ('len "abc"', 'len "abc"'),
70 ('autocallable', 'autocallable()'),
70 ('autocallable', 'autocallable()'),
71 # Don't add extra brackets (gh-1117)
71 # Don't add extra brackets (gh-1117)
72 ('autocallable()', 'autocallable()'),
72 ('autocallable()', 'autocallable()'),
73 ])
73 ])
74 ip.magic('autocall 1')
74 ip.magic('autocall 1')
75 run([
75 run([
76 ('len "abc"', 'len("abc")'),
76 ('len "abc"', 'len("abc")'),
77 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
77 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
78 # Autocall is turned off if first arg is [] and the object
78 # Autocall is turned off if first arg is [] and the object
79 # is both callable and indexable. Like so:
79 # is both callable and indexable. Like so:
80 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
80 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
81 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
81 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
82 ('call_idx 1', 'call_idx(1)'),
82 ('call_idx 1', 'call_idx(1)'),
83 ('len', 'len'), # only at 2 does it auto-call on single args
83 ('len', 'len'), # only at 2 does it auto-call on single args
84 ])
84 ])
85 ip.magic('autocall 2')
85 ip.magic('autocall 2')
86 run([
86 run([
87 ('len "abc"', 'len("abc")'),
87 ('len "abc"', 'len("abc")'),
88 ('len "abc";', 'len("abc");'),
88 ('len "abc";', 'len("abc");'),
89 ('len [1,2]', 'len([1,2])'),
89 ('len [1,2]', 'len([1,2])'),
90 ('call_idx [1]', 'call_idx [1]'),
90 ('call_idx [1]', 'call_idx [1]'),
91 ('call_idx 1', 'call_idx(1)'),
91 ('call_idx 1', 'call_idx(1)'),
92 # This is what's different:
92 # This is what's different:
93 ('len', 'len()'), # only at 2 does it auto-call on single args
93 ('len', 'len()'), # only at 2 does it auto-call on single args
94 ])
94 ])
95 ip.magic('autocall 1')
95 ip.magic('autocall 1')
96
96
97 nt.assert_equal(failures, [])
97 nt.assert_equal(failures, [])
@@ -1,641 +1,641 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the inputsplitter module."""
2 """Tests for the inputsplitter module."""
3
3
4
4
5 # Copyright (c) IPython Development Team.
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7
7
8 import unittest
8 import unittest
9 import sys
9 import sys
10
10
11 import nose.tools as nt
11 import nose.tools as nt
12
12
13 from IPython.core import inputsplitter as isp
13 from IPython.core import inputsplitter as isp
14 from IPython.core.inputtransformer import InputTransformer
14 from IPython.core.inputtransformer import InputTransformer
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
16 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils import py3compat
17 from IPython.utils import py3compat
18 from IPython.utils.py3compat import input
18 from IPython.utils.py3compat import input
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Semi-complete examples (also used as tests)
21 # Semi-complete examples (also used as tests)
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 # Note: at the bottom, there's a slightly more complete version of this that
24 # Note: at the bottom, there's a slightly more complete version of this that
25 # can be useful during development of code here.
25 # can be useful during development of code here.
26
26
27 def mini_interactive_loop(input_func):
27 def mini_interactive_loop(input_func):
28 """Minimal example of the logic of an interactive interpreter loop.
28 """Minimal example of the logic of an interactive interpreter loop.
29
29
30 This serves as an example, and it is used by the test system with a fake
30 This serves as an example, and it is used by the test system with a fake
31 raw_input that simulates interactive input."""
31 raw_input that simulates interactive input."""
32
32
33 from IPython.core.inputsplitter import InputSplitter
33 from IPython.core.inputsplitter import InputSplitter
34
34
35 isp = InputSplitter()
35 isp = InputSplitter()
36 # In practice, this input loop would be wrapped in an outside loop to read
36 # In practice, this input loop would be wrapped in an outside loop to read
37 # input indefinitely, until some exit/quit command was issued. Here we
37 # input indefinitely, until some exit/quit command was issued. Here we
38 # only illustrate the basic inner loop.
38 # only illustrate the basic inner loop.
39 while isp.push_accepts_more():
39 while isp.push_accepts_more():
40 indent = ' '*isp.indent_spaces
40 indent = ' '*isp.indent_spaces
41 prompt = '>>> ' + indent
41 prompt = '>>> ' + indent
42 line = indent + input_func(prompt)
42 line = indent + input_func(prompt)
43 isp.push(line)
43 isp.push(line)
44
44
45 # Here we just return input so we can use it in a test suite, but a real
45 # Here we just return input so we can use it in a test suite, but a real
46 # interpreter would instead send it for execution somewhere.
46 # interpreter would instead send it for execution somewhere.
47 src = isp.source_reset()
47 src = isp.source_reset()
48 #print 'Input source was:\n', src # dbg
48 #print 'Input source was:\n', src # dbg
49 return src
49 return src
50
50
51 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
52 # Test utilities, just for local use
52 # Test utilities, just for local use
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54
54
55 def assemble(block):
55 def assemble(block):
56 """Assemble a block into multi-line sub-blocks."""
56 """Assemble a block into multi-line sub-blocks."""
57 return ['\n'.join(sub_block)+'\n' for sub_block in block]
57 return ['\n'.join(sub_block)+'\n' for sub_block in block]
58
58
59
59
60 def pseudo_input(lines):
60 def pseudo_input(lines):
61 """Return a function that acts like raw_input but feeds the input list."""
61 """Return a function that acts like raw_input but feeds the input list."""
62 ilines = iter(lines)
62 ilines = iter(lines)
63 def raw_in(prompt):
63 def raw_in(prompt):
64 try:
64 try:
65 return next(ilines)
65 return next(ilines)
66 except StopIteration:
66 except StopIteration:
67 return ''
67 return ''
68 return raw_in
68 return raw_in
69
69
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71 # Tests
71 # Tests
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 def test_spaces():
73 def test_spaces():
74 tests = [('', 0),
74 tests = [('', 0),
75 (' ', 1),
75 (' ', 1),
76 ('\n', 0),
76 ('\n', 0),
77 (' \n', 1),
77 (' \n', 1),
78 ('x', 0),
78 ('x', 0),
79 (' x', 1),
79 (' x', 1),
80 (' x',2),
80 (' x',2),
81 (' x',4),
81 (' x',4),
82 # Note: tabs are counted as a single whitespace!
82 # Note: tabs are counted as a single whitespace!
83 ('\tx', 1),
83 ('\tx', 1),
84 ('\t x', 2),
84 ('\t x', 2),
85 ]
85 ]
86 tt.check_pairs(isp.num_ini_spaces, tests)
86 tt.check_pairs(isp.num_ini_spaces, tests)
87
87
88
88
89 def test_remove_comments():
89 def test_remove_comments():
90 tests = [('text', 'text'),
90 tests = [('text', 'text'),
91 ('text # comment', 'text '),
91 ('text # comment', 'text '),
92 ('text # comment\n', 'text \n'),
92 ('text # comment\n', 'text \n'),
93 ('text # comment \n', 'text \n'),
93 ('text # comment \n', 'text \n'),
94 ('line # c \nline\n','line \nline\n'),
94 ('line # c \nline\n','line \nline\n'),
95 ('line # c \nline#c2 \nline\nline #c\n\n',
95 ('line # c \nline#c2 \nline\nline #c\n\n',
96 'line \nline\nline\nline \n\n'),
96 'line \nline\nline\nline \n\n'),
97 ]
97 ]
98 tt.check_pairs(isp.remove_comments, tests)
98 tt.check_pairs(isp.remove_comments, tests)
99
99
100
100
101 def test_get_input_encoding():
101 def test_get_input_encoding():
102 encoding = isp.get_input_encoding()
102 encoding = isp.get_input_encoding()
103 nt.assert_true(isinstance(encoding, str))
103 nt.assert_true(isinstance(encoding, str))
104 # simple-minded check that at least encoding a simple string works with the
104 # simple-minded check that at least encoding a simple string works with the
105 # encoding we got.
105 # encoding we got.
106 nt.assert_equal(u'test'.encode(encoding), b'test')
106 nt.assert_equal(u'test'.encode(encoding), b'test')
107
107
108
108
109 class NoInputEncodingTestCase(unittest.TestCase):
109 class NoInputEncodingTestCase(unittest.TestCase):
110 def setUp(self):
110 def setUp(self):
111 self.old_stdin = sys.stdin
111 self.old_stdin = sys.stdin
112 class X: pass
112 class X: pass
113 fake_stdin = X()
113 fake_stdin = X()
114 sys.stdin = fake_stdin
114 sys.stdin = fake_stdin
115
115
116 def test(self):
116 def test(self):
117 # Verify that if sys.stdin has no 'encoding' attribute we do the right
117 # Verify that if sys.stdin has no 'encoding' attribute we do the right
118 # thing
118 # thing
119 enc = isp.get_input_encoding()
119 enc = isp.get_input_encoding()
120 self.assertEqual(enc, 'ascii')
120 self.assertEqual(enc, 'ascii')
121
121
122 def tearDown(self):
122 def tearDown(self):
123 sys.stdin = self.old_stdin
123 sys.stdin = self.old_stdin
124
124
125
125
126 class InputSplitterTestCase(unittest.TestCase):
126 class InputSplitterTestCase(unittest.TestCase):
127 def setUp(self):
127 def setUp(self):
128 self.isp = isp.InputSplitter()
128 self.isp = isp.InputSplitter()
129
129
130 def test_reset(self):
130 def test_reset(self):
131 isp = self.isp
131 isp = self.isp
132 isp.push('x=1')
132 isp.push('x=1')
133 isp.reset()
133 isp.reset()
134 self.assertEqual(isp._buffer, [])
134 self.assertEqual(isp._buffer, [])
135 self.assertEqual(isp.indent_spaces, 0)
135 self.assertEqual(isp.indent_spaces, 0)
136 self.assertEqual(isp.source, '')
136 self.assertEqual(isp.source, '')
137 self.assertEqual(isp.code, None)
137 self.assertEqual(isp.code, None)
138 self.assertEqual(isp._is_complete, False)
138 self.assertEqual(isp._is_complete, False)
139
139
140 def test_source(self):
140 def test_source(self):
141 self.isp._store('1')
141 self.isp._store('1')
142 self.isp._store('2')
142 self.isp._store('2')
143 self.assertEqual(self.isp.source, '1\n2\n')
143 self.assertEqual(self.isp.source, '1\n2\n')
144 self.assertEqual(len(self.isp._buffer)>0, True)
144 self.assertEqual(len(self.isp._buffer)>0, True)
145 self.assertEqual(self.isp.source_reset(), '1\n2\n')
145 self.assertEqual(self.isp.source_reset(), '1\n2\n')
146 self.assertEqual(self.isp._buffer, [])
146 self.assertEqual(self.isp._buffer, [])
147 self.assertEqual(self.isp.source, '')
147 self.assertEqual(self.isp.source, '')
148
148
149 def test_indent(self):
149 def test_indent(self):
150 isp = self.isp # shorthand
150 isp = self.isp # shorthand
151 isp.push('x=1')
151 isp.push('x=1')
152 self.assertEqual(isp.indent_spaces, 0)
152 self.assertEqual(isp.indent_spaces, 0)
153 isp.push('if 1:\n x=1')
153 isp.push('if 1:\n x=1')
154 self.assertEqual(isp.indent_spaces, 4)
154 self.assertEqual(isp.indent_spaces, 4)
155 isp.push('y=2\n')
155 isp.push('y=2\n')
156 self.assertEqual(isp.indent_spaces, 0)
156 self.assertEqual(isp.indent_spaces, 0)
157
157
158 def test_indent2(self):
158 def test_indent2(self):
159 isp = self.isp
159 isp = self.isp
160 isp.push('if 1:')
160 isp.push('if 1:')
161 self.assertEqual(isp.indent_spaces, 4)
161 self.assertEqual(isp.indent_spaces, 4)
162 isp.push(' x=1')
162 isp.push(' x=1')
163 self.assertEqual(isp.indent_spaces, 4)
163 self.assertEqual(isp.indent_spaces, 4)
164 # Blank lines shouldn't change the indent level
164 # Blank lines shouldn't change the indent level
165 isp.push(' '*2)
165 isp.push(' '*2)
166 self.assertEqual(isp.indent_spaces, 4)
166 self.assertEqual(isp.indent_spaces, 4)
167
167
168 def test_indent3(self):
168 def test_indent3(self):
169 isp = self.isp
169 isp = self.isp
170 # When a multiline statement contains parens or multiline strings, we
170 # When a multiline statement contains parens or multiline strings, we
171 # shouldn't get confused.
171 # shouldn't get confused.
172 isp.push("if 1:")
172 isp.push("if 1:")
173 isp.push(" x = (1+\n 2)")
173 isp.push(" x = (1+\n 2)")
174 self.assertEqual(isp.indent_spaces, 4)
174 self.assertEqual(isp.indent_spaces, 4)
175
175
176 def test_indent4(self):
176 def test_indent4(self):
177 isp = self.isp
177 isp = self.isp
178 # whitespace after ':' should not screw up indent level
178 # whitespace after ':' should not screw up indent level
179 isp.push('if 1: \n x=1')
179 isp.push('if 1: \n x=1')
180 self.assertEqual(isp.indent_spaces, 4)
180 self.assertEqual(isp.indent_spaces, 4)
181 isp.push('y=2\n')
181 isp.push('y=2\n')
182 self.assertEqual(isp.indent_spaces, 0)
182 self.assertEqual(isp.indent_spaces, 0)
183 isp.push('if 1:\t\n x=1')
183 isp.push('if 1:\t\n x=1')
184 self.assertEqual(isp.indent_spaces, 4)
184 self.assertEqual(isp.indent_spaces, 4)
185 isp.push('y=2\n')
185 isp.push('y=2\n')
186 self.assertEqual(isp.indent_spaces, 0)
186 self.assertEqual(isp.indent_spaces, 0)
187
187
188 def test_dedent_pass(self):
188 def test_dedent_pass(self):
189 isp = self.isp # shorthand
189 isp = self.isp # shorthand
190 # should NOT cause dedent
190 # should NOT cause dedent
191 isp.push('if 1:\n passes = 5')
191 isp.push('if 1:\n passes = 5')
192 self.assertEqual(isp.indent_spaces, 4)
192 self.assertEqual(isp.indent_spaces, 4)
193 isp.push('if 1:\n pass')
193 isp.push('if 1:\n pass')
194 self.assertEqual(isp.indent_spaces, 0)
194 self.assertEqual(isp.indent_spaces, 0)
195 isp.push('if 1:\n pass ')
195 isp.push('if 1:\n pass ')
196 self.assertEqual(isp.indent_spaces, 0)
196 self.assertEqual(isp.indent_spaces, 0)
197
197
198 def test_dedent_break(self):
198 def test_dedent_break(self):
199 isp = self.isp # shorthand
199 isp = self.isp # shorthand
200 # should NOT cause dedent
200 # should NOT cause dedent
201 isp.push('while 1:\n breaks = 5')
201 isp.push('while 1:\n breaks = 5')
202 self.assertEqual(isp.indent_spaces, 4)
202 self.assertEqual(isp.indent_spaces, 4)
203 isp.push('while 1:\n break')
203 isp.push('while 1:\n break')
204 self.assertEqual(isp.indent_spaces, 0)
204 self.assertEqual(isp.indent_spaces, 0)
205 isp.push('while 1:\n break ')
205 isp.push('while 1:\n break ')
206 self.assertEqual(isp.indent_spaces, 0)
206 self.assertEqual(isp.indent_spaces, 0)
207
207
208 def test_dedent_continue(self):
208 def test_dedent_continue(self):
209 isp = self.isp # shorthand
209 isp = self.isp # shorthand
210 # should NOT cause dedent
210 # should NOT cause dedent
211 isp.push('while 1:\n continues = 5')
211 isp.push('while 1:\n continues = 5')
212 self.assertEqual(isp.indent_spaces, 4)
212 self.assertEqual(isp.indent_spaces, 4)
213 isp.push('while 1:\n continue')
213 isp.push('while 1:\n continue')
214 self.assertEqual(isp.indent_spaces, 0)
214 self.assertEqual(isp.indent_spaces, 0)
215 isp.push('while 1:\n continue ')
215 isp.push('while 1:\n continue ')
216 self.assertEqual(isp.indent_spaces, 0)
216 self.assertEqual(isp.indent_spaces, 0)
217
217
218 def test_dedent_raise(self):
218 def test_dedent_raise(self):
219 isp = self.isp # shorthand
219 isp = self.isp # shorthand
220 # should NOT cause dedent
220 # should NOT cause dedent
221 isp.push('if 1:\n raised = 4')
221 isp.push('if 1:\n raised = 4')
222 self.assertEqual(isp.indent_spaces, 4)
222 self.assertEqual(isp.indent_spaces, 4)
223 isp.push('if 1:\n raise TypeError()')
223 isp.push('if 1:\n raise TypeError()')
224 self.assertEqual(isp.indent_spaces, 0)
224 self.assertEqual(isp.indent_spaces, 0)
225 isp.push('if 1:\n raise')
225 isp.push('if 1:\n raise')
226 self.assertEqual(isp.indent_spaces, 0)
226 self.assertEqual(isp.indent_spaces, 0)
227 isp.push('if 1:\n raise ')
227 isp.push('if 1:\n raise ')
228 self.assertEqual(isp.indent_spaces, 0)
228 self.assertEqual(isp.indent_spaces, 0)
229
229
230 def test_dedent_return(self):
230 def test_dedent_return(self):
231 isp = self.isp # shorthand
231 isp = self.isp # shorthand
232 # should NOT cause dedent
232 # should NOT cause dedent
233 isp.push('if 1:\n returning = 4')
233 isp.push('if 1:\n returning = 4')
234 self.assertEqual(isp.indent_spaces, 4)
234 self.assertEqual(isp.indent_spaces, 4)
235 isp.push('if 1:\n return 5 + 493')
235 isp.push('if 1:\n return 5 + 493')
236 self.assertEqual(isp.indent_spaces, 0)
236 self.assertEqual(isp.indent_spaces, 0)
237 isp.push('if 1:\n return')
237 isp.push('if 1:\n return')
238 self.assertEqual(isp.indent_spaces, 0)
238 self.assertEqual(isp.indent_spaces, 0)
239 isp.push('if 1:\n return ')
239 isp.push('if 1:\n return ')
240 self.assertEqual(isp.indent_spaces, 0)
240 self.assertEqual(isp.indent_spaces, 0)
241 isp.push('if 1:\n return(0)')
241 isp.push('if 1:\n return(0)')
242 self.assertEqual(isp.indent_spaces, 0)
242 self.assertEqual(isp.indent_spaces, 0)
243
243
244 def test_push(self):
244 def test_push(self):
245 isp = self.isp
245 isp = self.isp
246 self.assertEqual(isp.push('x=1'), True)
246 self.assertEqual(isp.push('x=1'), True)
247
247
248 def test_push2(self):
248 def test_push2(self):
249 isp = self.isp
249 isp = self.isp
250 self.assertEqual(isp.push('if 1:'), False)
250 self.assertEqual(isp.push('if 1:'), False)
251 for line in [' x=1', '# a comment', ' y=2']:
251 for line in [' x=1', '# a comment', ' y=2']:
252 print(line)
252 print(line)
253 self.assertEqual(isp.push(line), True)
253 self.assertEqual(isp.push(line), True)
254
254
255 def test_push3(self):
255 def test_push3(self):
256 isp = self.isp
256 isp = self.isp
257 isp.push('if True:')
257 isp.push('if True:')
258 isp.push(' a = 1')
258 isp.push(' a = 1')
259 self.assertEqual(isp.push('b = [1,'), False)
259 self.assertEqual(isp.push('b = [1,'), False)
260
260
261 def test_push_accepts_more(self):
261 def test_push_accepts_more(self):
262 isp = self.isp
262 isp = self.isp
263 isp.push('x=1')
263 isp.push('x=1')
264 self.assertEqual(isp.push_accepts_more(), False)
264 self.assertEqual(isp.push_accepts_more(), False)
265
265
266 def test_push_accepts_more2(self):
266 def test_push_accepts_more2(self):
267 isp = self.isp
267 isp = self.isp
268 isp.push('if 1:')
268 isp.push('if 1:')
269 self.assertEqual(isp.push_accepts_more(), True)
269 self.assertEqual(isp.push_accepts_more(), True)
270 isp.push(' x=1')
270 isp.push(' x=1')
271 self.assertEqual(isp.push_accepts_more(), True)
271 self.assertEqual(isp.push_accepts_more(), True)
272 isp.push('')
272 isp.push('')
273 self.assertEqual(isp.push_accepts_more(), False)
273 self.assertEqual(isp.push_accepts_more(), False)
274
274
275 def test_push_accepts_more3(self):
275 def test_push_accepts_more3(self):
276 isp = self.isp
276 isp = self.isp
277 isp.push("x = (2+\n3)")
277 isp.push("x = (2+\n3)")
278 self.assertEqual(isp.push_accepts_more(), False)
278 self.assertEqual(isp.push_accepts_more(), False)
279
279
280 def test_push_accepts_more4(self):
280 def test_push_accepts_more4(self):
281 isp = self.isp
281 isp = self.isp
282 # When a multiline statement contains parens or multiline strings, we
282 # When a multiline statement contains parens or multiline strings, we
283 # shouldn't get confused.
283 # shouldn't get confused.
284 # FIXME: we should be able to better handle de-dents in statements like
284 # FIXME: we should be able to better handle de-dents in statements like
285 # multiline strings and multiline expressions (continued with \ or
285 # multiline strings and multiline expressions (continued with \ or
286 # parens). Right now we aren't handling the indentation tracking quite
286 # parens). Right now we aren't handling the indentation tracking quite
287 # correctly with this, though in practice it may not be too much of a
287 # correctly with this, though in practice it may not be too much of a
288 # problem. We'll need to see.
288 # problem. We'll need to see.
289 isp.push("if 1:")
289 isp.push("if 1:")
290 isp.push(" x = (2+")
290 isp.push(" x = (2+")
291 isp.push(" 3)")
291 isp.push(" 3)")
292 self.assertEqual(isp.push_accepts_more(), True)
292 self.assertEqual(isp.push_accepts_more(), True)
293 isp.push(" y = 3")
293 isp.push(" y = 3")
294 self.assertEqual(isp.push_accepts_more(), True)
294 self.assertEqual(isp.push_accepts_more(), True)
295 isp.push('')
295 isp.push('')
296 self.assertEqual(isp.push_accepts_more(), False)
296 self.assertEqual(isp.push_accepts_more(), False)
297
297
298 def test_push_accepts_more5(self):
298 def test_push_accepts_more5(self):
299 isp = self.isp
299 isp = self.isp
300 isp.push('try:')
300 isp.push('try:')
301 isp.push(' a = 5')
301 isp.push(' a = 5')
302 isp.push('except:')
302 isp.push('except:')
303 isp.push(' raise')
303 isp.push(' raise')
304 # We want to be able to add an else: block at this point, so it should
304 # We want to be able to add an else: block at this point, so it should
305 # wait for a blank line.
305 # wait for a blank line.
306 self.assertEqual(isp.push_accepts_more(), True)
306 self.assertEqual(isp.push_accepts_more(), True)
307
307
308 def test_continuation(self):
308 def test_continuation(self):
309 isp = self.isp
309 isp = self.isp
310 isp.push("import os, \\")
310 isp.push("import os, \\")
311 self.assertEqual(isp.push_accepts_more(), True)
311 self.assertEqual(isp.push_accepts_more(), True)
312 isp.push("sys")
312 isp.push("sys")
313 self.assertEqual(isp.push_accepts_more(), False)
313 self.assertEqual(isp.push_accepts_more(), False)
314
314
315 def test_syntax_error(self):
315 def test_syntax_error(self):
316 isp = self.isp
316 isp = self.isp
317 # Syntax errors immediately produce a 'ready' block, so the invalid
317 # Syntax errors immediately produce a 'ready' block, so the invalid
318 # Python can be sent to the kernel for evaluation with possible ipython
318 # Python can be sent to the kernel for evaluation with possible ipython
319 # special-syntax conversion.
319 # special-syntax conversion.
320 isp.push('run foo')
320 isp.push('run foo')
321 self.assertEqual(isp.push_accepts_more(), False)
321 self.assertEqual(isp.push_accepts_more(), False)
322
322
323 def test_unicode(self):
323 def test_unicode(self):
324 self.isp.push(u"Pérez")
324 self.isp.push(u"Pérez")
325 self.isp.push(u'\xc3\xa9')
325 self.isp.push(u'\xc3\xa9')
326 self.isp.push(u"u'\xc3\xa9'")
326 self.isp.push(u"u'\xc3\xa9'")
327
327
328 def test_line_continuation(self):
328 def test_line_continuation(self):
329 """ Test issue #2108."""
329 """ Test issue #2108."""
330 isp = self.isp
330 isp = self.isp
331 # A blank line after a line continuation should not accept more
331 # A blank line after a line continuation should not accept more
332 isp.push("1 \\\n\n")
332 isp.push("1 \\\n\n")
333 self.assertEqual(isp.push_accepts_more(), False)
333 self.assertEqual(isp.push_accepts_more(), False)
334 # Whitespace after a \ is a SyntaxError. The only way to test that
334 # Whitespace after a \ is a SyntaxError. The only way to test that
335 # here is to test that push doesn't accept more (as with
335 # here is to test that push doesn't accept more (as with
336 # test_syntax_error() above).
336 # test_syntax_error() above).
337 isp.push(r"1 \ ")
337 isp.push(r"1 \ ")
338 self.assertEqual(isp.push_accepts_more(), False)
338 self.assertEqual(isp.push_accepts_more(), False)
339 # Even if the line is continuable (c.f. the regular Python
339 # Even if the line is continuable (c.f. the regular Python
340 # interpreter)
340 # interpreter)
341 isp.push(r"(1 \ ")
341 isp.push(r"(1 \ ")
342 self.assertEqual(isp.push_accepts_more(), False)
342 self.assertEqual(isp.push_accepts_more(), False)
343
343
344 def test_check_complete(self):
344 def test_check_complete(self):
345 isp = self.isp
345 isp = self.isp
346 self.assertEqual(isp.check_complete("a = 1"), ('complete', None))
346 self.assertEqual(isp.check_complete("a = 1"), ('complete', None))
347 self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4))
347 self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4))
348 self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None))
348 self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None))
349 self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0))
349 self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0))
350 self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None))
350 self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None))
351
351
352 class InteractiveLoopTestCase(unittest.TestCase):
352 class InteractiveLoopTestCase(unittest.TestCase):
353 """Tests for an interactive loop like a python shell.
353 """Tests for an interactive loop like a python shell.
354 """
354 """
355 def check_ns(self, lines, ns):
355 def check_ns(self, lines, ns):
356 """Validate that the given input lines produce the resulting namespace.
356 """Validate that the given input lines produce the resulting namespace.
357
357
358 Note: the input lines are given exactly as they would be typed in an
358 Note: the input lines are given exactly as they would be typed in an
359 auto-indenting environment, as mini_interactive_loop above already does
359 auto-indenting environment, as mini_interactive_loop above already does
360 auto-indenting and prepends spaces to the input.
360 auto-indenting and prepends spaces to the input.
361 """
361 """
362 src = mini_interactive_loop(pseudo_input(lines))
362 src = mini_interactive_loop(pseudo_input(lines))
363 test_ns = {}
363 test_ns = {}
364 exec(src, test_ns)
364 exec(src, test_ns)
365 # We can't check that the provided ns is identical to the test_ns,
365 # We can't check that the provided ns is identical to the test_ns,
366 # because Python fills test_ns with extra keys (copyright, etc). But
366 # because Python fills test_ns with extra keys (copyright, etc). But
367 # we can check that the given dict is *contained* in test_ns
367 # we can check that the given dict is *contained* in test_ns
368 for k,v in ns.items():
368 for k,v in ns.items():
369 self.assertEqual(test_ns[k], v)
369 self.assertEqual(test_ns[k], v)
370
370
371 def test_simple(self):
371 def test_simple(self):
372 self.check_ns(['x=1'], dict(x=1))
372 self.check_ns(['x=1'], dict(x=1))
373
373
374 def test_simple2(self):
374 def test_simple2(self):
375 self.check_ns(['if 1:', 'x=2'], dict(x=2))
375 self.check_ns(['if 1:', 'x=2'], dict(x=2))
376
376
377 def test_xy(self):
377 def test_xy(self):
378 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
378 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
379
379
380 def test_abc(self):
380 def test_abc(self):
381 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
381 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
382
382
383 def test_multi(self):
383 def test_multi(self):
384 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
384 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
385
385
386
386
387 class IPythonInputTestCase(InputSplitterTestCase):
387 class IPythonInputTestCase(InputSplitterTestCase):
388 """By just creating a new class whose .isp is a different instance, we
388 """By just creating a new class whose .isp is a different instance, we
389 re-run the same test battery on the new input splitter.
389 re-run the same test battery on the new input splitter.
390
390
391 In addition, this runs the tests over the syntax and syntax_ml dicts that
391 In addition, this runs the tests over the syntax and syntax_ml dicts that
392 were tested by individual functions, as part of the OO interface.
392 were tested by individual functions, as part of the OO interface.
393
393
394 It also makes some checks on the raw buffer storage.
394 It also makes some checks on the raw buffer storage.
395 """
395 """
396
396
397 def setUp(self):
397 def setUp(self):
398 self.isp = isp.IPythonInputSplitter()
398 self.isp = isp.IPythonInputSplitter()
399
399
400 def test_syntax(self):
400 def test_syntax(self):
401 """Call all single-line syntax tests from the main object"""
401 """Call all single-line syntax tests from the main object"""
402 isp = self.isp
402 isp = self.isp
403 for example in syntax.values():
403 for example in syntax.values():
404 for raw, out_t in example:
404 for raw, out_t in example:
405 if raw.startswith(' '):
405 if raw.startswith(' '):
406 continue
406 continue
407
407
408 isp.push(raw+'\n')
408 isp.push(raw+'\n')
409 out_raw = isp.source_raw
409 out_raw = isp.source_raw
410 out = isp.source_reset()
410 out = isp.source_reset()
411 self.assertEqual(out.rstrip(), out_t,
411 self.assertEqual(out.rstrip(), out_t,
412 tt.pair_fail_msg.format("inputsplitter",raw, out_t, out))
412 tt.pair_fail_msg.format("inputsplitter",raw, out_t, out))
413 self.assertEqual(out_raw.rstrip(), raw.rstrip())
413 self.assertEqual(out_raw.rstrip(), raw.rstrip())
414
414
415 def test_syntax_multiline(self):
415 def test_syntax_multiline(self):
416 isp = self.isp
416 isp = self.isp
417 for example in syntax_ml.values():
417 for example in syntax_ml.values():
418 for line_pairs in example:
418 for line_pairs in example:
419 out_t_parts = []
419 out_t_parts = []
420 raw_parts = []
420 raw_parts = []
421 for lraw, out_t_part in line_pairs:
421 for lraw, out_t_part in line_pairs:
422 if out_t_part is not None:
422 if out_t_part is not None:
423 out_t_parts.append(out_t_part)
423 out_t_parts.append(out_t_part)
424
424
425 if lraw is not None:
425 if lraw is not None:
426 isp.push(lraw)
426 isp.push(lraw)
427 raw_parts.append(lraw)
427 raw_parts.append(lraw)
428
428
429 out_raw = isp.source_raw
429 out_raw = isp.source_raw
430 out = isp.source_reset()
430 out = isp.source_reset()
431 out_t = '\n'.join(out_t_parts).rstrip()
431 out_t = '\n'.join(out_t_parts).rstrip()
432 raw = '\n'.join(raw_parts).rstrip()
432 raw = '\n'.join(raw_parts).rstrip()
433 self.assertEqual(out.rstrip(), out_t)
433 self.assertEqual(out.rstrip(), out_t)
434 self.assertEqual(out_raw.rstrip(), raw)
434 self.assertEqual(out_raw.rstrip(), raw)
435
435
436 def test_syntax_multiline_cell(self):
436 def test_syntax_multiline_cell(self):
437 isp = self.isp
437 isp = self.isp
438 for example in syntax_ml.values():
438 for example in syntax_ml.values():
439
439
440 out_t_parts = []
440 out_t_parts = []
441 for line_pairs in example:
441 for line_pairs in example:
442 raw = '\n'.join(r for r, _ in line_pairs if r is not None)
442 raw = '\n'.join(r for r, _ in line_pairs if r is not None)
443 out_t = '\n'.join(t for _,t in line_pairs if t is not None)
443 out_t = '\n'.join(t for _,t in line_pairs if t is not None)
444 out = isp.transform_cell(raw)
444 out = isp.transform_cell(raw)
445 # Match ignoring trailing whitespace
445 # Match ignoring trailing whitespace
446 self.assertEqual(out.rstrip(), out_t.rstrip())
446 self.assertEqual(out.rstrip(), out_t.rstrip())
447
447
448 def test_cellmagic_preempt(self):
448 def test_cellmagic_preempt(self):
449 isp = self.isp
449 isp = self.isp
450 for raw, name, line, cell in [
450 for raw, name, line, cell in [
451 ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'),
451 ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'),
452 ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'),
452 ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'),
453 (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'),
453 (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'),
454 ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'),
454 ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'),
455 ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'),
455 ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'),
456 ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'),
456 ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'),
457 ]:
457 ]:
458 expected = "get_ipython().run_cell_magic(%r, %r, %r)" % (
458 expected = "get_ipython().run_cell_magic(%r, %r, %r)" % (
459 name, line, cell
459 name, line, cell
460 )
460 )
461 out = isp.transform_cell(raw)
461 out = isp.transform_cell(raw)
462 self.assertEqual(out.rstrip(), expected.rstrip())
462 self.assertEqual(out.rstrip(), expected.rstrip())
463
463
464 def test_multiline_passthrough(self):
464 def test_multiline_passthrough(self):
465 isp = self.isp
465 isp = self.isp
466 class CommentTransformer(InputTransformer):
466 class CommentTransformer(InputTransformer):
467 def __init__(self):
467 def __init__(self):
468 self._lines = []
468 self._lines = []
469
469
470 def push(self, line):
470 def push(self, line):
471 self._lines.append(line + '#')
471 self._lines.append(line + '#')
472
472
473 def reset(self):
473 def reset(self):
474 text = '\n'.join(self._lines)
474 text = '\n'.join(self._lines)
475 self._lines = []
475 self._lines = []
476 return text
476 return text
477
477
478 isp.physical_line_transforms.insert(0, CommentTransformer())
478 isp.physical_line_transforms.insert(0, CommentTransformer())
479
479
480 for raw, expected in [
480 for raw, expected in [
481 ("a=5", "a=5#"),
481 ("a=5", "a=5#"),
482 ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')),
482 ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')),
483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % (
483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % (
484 u'ls foo#', u'ls', u'bar#'
484 u'ls foo#', u'ls', u'bar#'
485 )),
485 )),
486 ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().run_line_magic(%r, %r)\n4#\n5#" % (u'ls', u'foo#')),
486 ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().run_line_magic(%r, %r)\n4#\n5#" % (u'ls', u'foo#')),
487 ]:
487 ]:
488 out = isp.transform_cell(raw)
488 out = isp.transform_cell(raw)
489 self.assertEqual(out.rstrip(), expected.rstrip())
489 self.assertEqual(out.rstrip(), expected.rstrip())
490
490
491 #-----------------------------------------------------------------------------
491 #-----------------------------------------------------------------------------
492 # Main - use as a script, mostly for developer experiments
492 # Main - use as a script, mostly for developer experiments
493 #-----------------------------------------------------------------------------
493 #-----------------------------------------------------------------------------
494
494
495 if __name__ == '__main__':
495 if __name__ == '__main__':
496 # A simple demo for interactive experimentation. This code will not get
496 # A simple demo for interactive experimentation. This code will not get
497 # picked up by any test suite.
497 # picked up by any test suite.
498 from IPython.core.inputsplitter import IPythonInputSplitter
498 from IPython.core.inputsplitter import IPythonInputSplitter
499
499
500 # configure here the syntax to use, prompt and whether to autoindent
500 # configure here the syntax to use, prompt and whether to autoindent
501 #isp, start_prompt = InputSplitter(), '>>> '
501 #isp, start_prompt = InputSplitter(), '>>> '
502 isp, start_prompt = IPythonInputSplitter(), 'In> '
502 isp, start_prompt = IPythonInputSplitter(), 'In> '
503
503
504 autoindent = True
504 autoindent = True
505 #autoindent = False
505 #autoindent = False
506
506
507 try:
507 try:
508 while True:
508 while True:
509 prompt = start_prompt
509 prompt = start_prompt
510 while isp.push_accepts_more():
510 while isp.push_accepts_more():
511 indent = ' '*isp.indent_spaces
511 indent = ' '*isp.indent_spaces
512 if autoindent:
512 if autoindent:
513 line = indent + input(prompt+indent)
513 line = indent + input(prompt+indent)
514 else:
514 else:
515 line = input(prompt)
515 line = input(prompt)
516 isp.push(line)
516 isp.push(line)
517 prompt = '... '
517 prompt = '... '
518
518
519 # Here we just return input so we can use it in a test suite, but a
519 # Here we just return input so we can use it in a test suite, but a
520 # real interpreter would instead send it for execution somewhere.
520 # real interpreter would instead send it for execution somewhere.
521 #src = isp.source; raise EOFError # dbg
521 #src = isp.source; raise EOFError # dbg
522 raw = isp.source_raw
522 raw = isp.source_raw
523 src = isp.source_reset()
523 src = isp.source_reset()
524 print('Input source was:\n', src)
524 print('Input source was:\n', src)
525 print('Raw source was:\n', raw)
525 print('Raw source was:\n', raw)
526 except EOFError:
526 except EOFError:
527 print('Bye')
527 print('Bye')
528
528
529 # Tests for cell magics support
529 # Tests for cell magics support
530
530
531 def test_last_blank():
531 def test_last_blank():
532 nt.assert_false(isp.last_blank(''))
532 nt.assert_false(isp.last_blank(''))
533 nt.assert_false(isp.last_blank('abc'))
533 nt.assert_false(isp.last_blank('abc'))
534 nt.assert_false(isp.last_blank('abc\n'))
534 nt.assert_false(isp.last_blank('abc\n'))
535 nt.assert_false(isp.last_blank('abc\na'))
535 nt.assert_false(isp.last_blank('abc\na'))
536
536
537 nt.assert_true(isp.last_blank('\n'))
537 nt.assert_true(isp.last_blank('\n'))
538 nt.assert_true(isp.last_blank('\n '))
538 nt.assert_true(isp.last_blank('\n '))
539 nt.assert_true(isp.last_blank('abc\n '))
539 nt.assert_true(isp.last_blank('abc\n '))
540 nt.assert_true(isp.last_blank('abc\n\n'))
540 nt.assert_true(isp.last_blank('abc\n\n'))
541 nt.assert_true(isp.last_blank('abc\nd\n\n'))
541 nt.assert_true(isp.last_blank('abc\nd\n\n'))
542 nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
542 nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
543 nt.assert_true(isp.last_blank('abc \n \n \n\n'))
543 nt.assert_true(isp.last_blank('abc \n \n \n\n'))
544
544
545
545
546 def test_last_two_blanks():
546 def test_last_two_blanks():
547 nt.assert_false(isp.last_two_blanks(''))
547 nt.assert_false(isp.last_two_blanks(''))
548 nt.assert_false(isp.last_two_blanks('abc'))
548 nt.assert_false(isp.last_two_blanks('abc'))
549 nt.assert_false(isp.last_two_blanks('abc\n'))
549 nt.assert_false(isp.last_two_blanks('abc\n'))
550 nt.assert_false(isp.last_two_blanks('abc\n\na'))
550 nt.assert_false(isp.last_two_blanks('abc\n\na'))
551 nt.assert_false(isp.last_two_blanks('abc\n \n'))
551 nt.assert_false(isp.last_two_blanks('abc\n \n'))
552 nt.assert_false(isp.last_two_blanks('abc\n\n'))
552 nt.assert_false(isp.last_two_blanks('abc\n\n'))
553
553
554 nt.assert_true(isp.last_two_blanks('\n\n'))
554 nt.assert_true(isp.last_two_blanks('\n\n'))
555 nt.assert_true(isp.last_two_blanks('\n\n '))
555 nt.assert_true(isp.last_two_blanks('\n\n '))
556 nt.assert_true(isp.last_two_blanks('\n \n'))
556 nt.assert_true(isp.last_two_blanks('\n \n'))
557 nt.assert_true(isp.last_two_blanks('abc\n\n '))
557 nt.assert_true(isp.last_two_blanks('abc\n\n '))
558 nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
558 nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
559 nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
559 nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
560 nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
560 nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
561 nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
561 nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
562 nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
562 nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
563 nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
563 nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
564
564
565
565
566 class CellMagicsCommon(object):
566 class CellMagicsCommon(object):
567
567
568 def test_whole_cell(self):
568 def test_whole_cell(self):
569 src = "%%cellm line\nbody\n"
569 src = "%%cellm line\nbody\n"
570 out = self.sp.transform_cell(src)
570 out = self.sp.transform_cell(src)
571 ref = u"get_ipython().run_cell_magic({u}'cellm', {u}'line', {u}'body')\n"
571 ref = u"get_ipython().run_cell_magic('cellm', 'line', 'body')\n"
572 nt.assert_equal(out, py3compat.u_format(ref))
572 nt.assert_equal(out, py3compat.u_format(ref))
573
573
574 def test_cellmagic_help(self):
574 def test_cellmagic_help(self):
575 self.sp.push('%%cellm?')
575 self.sp.push('%%cellm?')
576 nt.assert_false(self.sp.push_accepts_more())
576 nt.assert_false(self.sp.push_accepts_more())
577
577
578 def tearDown(self):
578 def tearDown(self):
579 self.sp.reset()
579 self.sp.reset()
580
580
581
581
582 class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):
582 class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):
583 sp = isp.IPythonInputSplitter(line_input_checker=False)
583 sp = isp.IPythonInputSplitter(line_input_checker=False)
584
584
585 def test_incremental(self):
585 def test_incremental(self):
586 sp = self.sp
586 sp = self.sp
587 sp.push('%%cellm firstline\n')
587 sp.push('%%cellm firstline\n')
588 nt.assert_true(sp.push_accepts_more()) #1
588 nt.assert_true(sp.push_accepts_more()) #1
589 sp.push('line2\n')
589 sp.push('line2\n')
590 nt.assert_true(sp.push_accepts_more()) #2
590 nt.assert_true(sp.push_accepts_more()) #2
591 sp.push('\n')
591 sp.push('\n')
592 # This should accept a blank line and carry on until the cell is reset
592 # This should accept a blank line and carry on until the cell is reset
593 nt.assert_true(sp.push_accepts_more()) #3
593 nt.assert_true(sp.push_accepts_more()) #3
594
594
595 def test_no_strip_coding(self):
595 def test_no_strip_coding(self):
596 src = '\n'.join([
596 src = '\n'.join([
597 '%%writefile foo.py',
597 '%%writefile foo.py',
598 '# coding: utf-8',
598 '# coding: utf-8',
599 'print(u"üñîçø∂é")',
599 'print(u"üñîçø∂é")',
600 ])
600 ])
601 out = self.sp.transform_cell(src)
601 out = self.sp.transform_cell(src)
602 nt.assert_in('# coding: utf-8', out)
602 nt.assert_in('# coding: utf-8', out)
603
603
604
604
605 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
605 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
606 sp = isp.IPythonInputSplitter(line_input_checker=True)
606 sp = isp.IPythonInputSplitter(line_input_checker=True)
607
607
608 def test_incremental(self):
608 def test_incremental(self):
609 sp = self.sp
609 sp = self.sp
610 sp.push('%%cellm line2\n')
610 sp.push('%%cellm line2\n')
611 nt.assert_true(sp.push_accepts_more()) #1
611 nt.assert_true(sp.push_accepts_more()) #1
612 sp.push('\n')
612 sp.push('\n')
613 # In this case, a blank line should end the cell magic
613 # In this case, a blank line should end the cell magic
614 nt.assert_false(sp.push_accepts_more()) #2
614 nt.assert_false(sp.push_accepts_more()) #2
615
615
616 indentation_samples = [
616 indentation_samples = [
617 ('a = 1', 0),
617 ('a = 1', 0),
618 ('for a in b:', 4),
618 ('for a in b:', 4),
619 ('def f():', 4),
619 ('def f():', 4),
620 ('def f(): #comment', 4),
620 ('def f(): #comment', 4),
621 ('a = ":#not a comment"', 0),
621 ('a = ":#not a comment"', 0),
622 ('def f():\n a = 1', 4),
622 ('def f():\n a = 1', 4),
623 ('def f():\n return 1', 0),
623 ('def f():\n return 1', 0),
624 ('for a in b:\n'
624 ('for a in b:\n'
625 ' if a < 0:'
625 ' if a < 0:'
626 ' continue', 3),
626 ' continue', 3),
627 ('a = {', 4),
627 ('a = {', 4),
628 ('a = {\n'
628 ('a = {\n'
629 ' 1,', 5),
629 ' 1,', 5),
630 ('b = """123', 0),
630 ('b = """123', 0),
631 ('', 0),
631 ('', 0),
632 ('def f():\n pass', 0),
632 ('def f():\n pass', 0),
633 ('class Bar:\n def f():\n pass', 4),
633 ('class Bar:\n def f():\n pass', 4),
634 ('class Bar:\n def f():\n raise', 4),
634 ('class Bar:\n def f():\n raise', 4),
635 ]
635 ]
636
636
637 def test_find_next_indent():
637 def test_find_next_indent():
638 for code, exp in indentation_samples:
638 for code, exp in indentation_samples:
639 res = isp.find_next_indent(code)
639 res = isp.find_next_indent(code)
640 msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code)
640 msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code)
641 assert res == exp, msg
641 assert res == exp, msg
@@ -1,494 +1,494 b''
1 import tokenize
1 import tokenize
2 import nose.tools as nt
2 import nose.tools as nt
3
3
4 from IPython.testing import tools as tt
4 from IPython.testing import tools as tt
5 from IPython.utils import py3compat
5 from IPython.utils import py3compat
6 u_fmt = py3compat.u_format
6 u_fmt = py3compat.u_format
7
7
8 from IPython.core import inputtransformer as ipt
8 from IPython.core import inputtransformer as ipt
9
9
10 def transform_and_reset(transformer):
10 def transform_and_reset(transformer):
11 transformer = transformer()
11 transformer = transformer()
12 def transform(inp):
12 def transform(inp):
13 try:
13 try:
14 return transformer.push(inp)
14 return transformer.push(inp)
15 finally:
15 finally:
16 transformer.reset()
16 transformer.reset()
17
17
18 return transform
18 return transform
19
19
20 # Transformer tests
20 # Transformer tests
21 def transform_checker(tests, transformer, **kwargs):
21 def transform_checker(tests, transformer, **kwargs):
22 """Utility to loop over test inputs"""
22 """Utility to loop over test inputs"""
23 transformer = transformer(**kwargs)
23 transformer = transformer(**kwargs)
24 try:
24 try:
25 for inp, tr in tests:
25 for inp, tr in tests:
26 if inp is None:
26 if inp is None:
27 out = transformer.reset()
27 out = transformer.reset()
28 else:
28 else:
29 out = transformer.push(inp)
29 out = transformer.push(inp)
30 nt.assert_equal(out, tr)
30 nt.assert_equal(out, tr)
31 finally:
31 finally:
32 transformer.reset()
32 transformer.reset()
33
33
34 # Data for all the syntax tests in the form of lists of pairs of
34 # Data for all the syntax tests in the form of lists of pairs of
35 # raw/transformed input. We store it here as a global dict so that we can use
35 # raw/transformed input. We store it here as a global dict so that we can use
36 # it both within single-function tests and also to validate the behavior of the
36 # it both within single-function tests and also to validate the behavior of the
37 # larger objects
37 # larger objects
38
38
39 syntax = \
39 syntax = \
40 dict(assign_system =
40 dict(assign_system =
41 [(i,py3compat.u_format(o)) for i,o in \
41 [(i,py3compat.u_format(o)) for i,o in \
42 [(u'a =! ls', "a = get_ipython().getoutput({u}'ls')"),
42 [(u'a =! ls', "a = get_ipython().getoutput('ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput({u}'ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput('ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput({u}'ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput('ls')"),
45 (u'd == !ls', u'd == !ls'), # Invalid syntax, but we leave == alone.
45 (u'd == !ls', u'd == !ls'), # Invalid syntax, but we leave == alone.
46 ('x=1', 'x=1'), # normal input is unmodified
46 ('x=1', 'x=1'), # normal input is unmodified
47 (' ',' '), # blank lines are kept intact
47 (' ',' '), # blank lines are kept intact
48 # Tuple unpacking
48 # Tuple unpacking
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput({u}\"echo 'a\\\\nb'\")"),
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput(\"echo 'a\\\\nb'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput({u}\"echo 'a'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput(\"echo 'a'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput({u}\"echo 'a\\\\nb\\\\nc'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput(\"echo 'a\\\\nb\\\\nc'\")"),
52 # Tuple unpacking with regular Python expressions, not our syntax.
52 # Tuple unpacking with regular Python expressions, not our syntax.
53 (u"a, b = range(2)", u"a, b = range(2)"),
53 (u"a, b = range(2)", u"a, b = range(2)"),
54 (u"a, = range(1)", u"a, = range(1)"),
54 (u"a, = range(1)", u"a, = range(1)"),
55 (u"a, *bc = range(3)", u"a, *bc = range(3)"),
55 (u"a, *bc = range(3)", u"a, *bc = range(3)"),
56 ]],
56 ]],
57
57
58 assign_magic =
58 assign_magic =
59 [(i,py3compat.u_format(o)) for i,o in \
59 [(i,py3compat.u_format(o)) for i,o in \
60 [(u'a =% who', "a = get_ipython().run_line_magic({u}'who', {u}'')"),
60 [(u'a =% who', "a = get_ipython().run_line_magic('who', '')"),
61 (u'b = %who', "b = get_ipython().run_line_magic({u}'who', {u}'')"),
61 (u'b = %who', "b = get_ipython().run_line_magic('who', '')"),
62 (u'c= %ls', "c = get_ipython().run_line_magic({u}'ls', {u}'')"),
62 (u'c= %ls', "c = get_ipython().run_line_magic('ls', '')"),
63 (u'd == %ls', u'd == %ls'), # Invalid syntax, but we leave == alone.
63 (u'd == %ls', u'd == %ls'), # Invalid syntax, but we leave == alone.
64 ('x=1', 'x=1'), # normal input is unmodified
64 ('x=1', 'x=1'), # normal input is unmodified
65 (' ',' '), # blank lines are kept intact
65 (' ',' '), # blank lines are kept intact
66 (u"a, b = %foo", u"a, b = get_ipython().run_line_magic({u}'foo', {u}'')"),
66 (u"a, b = %foo", u"a, b = get_ipython().run_line_magic('foo', '')"),
67 ]],
67 ]],
68
68
69 classic_prompt =
69 classic_prompt =
70 [('>>> x=1', 'x=1'),
70 [('>>> x=1', 'x=1'),
71 ('x=1', 'x=1'), # normal input is unmodified
71 ('x=1', 'x=1'), # normal input is unmodified
72 (' ', ' '), # blank lines are kept intact
72 (' ', ' '), # blank lines are kept intact
73 ],
73 ],
74
74
75 ipy_prompt =
75 ipy_prompt =
76 [('In [1]: x=1', 'x=1'),
76 [('In [1]: x=1', 'x=1'),
77 ('x=1', 'x=1'), # normal input is unmodified
77 ('x=1', 'x=1'), # normal input is unmodified
78 (' ',' '), # blank lines are kept intact
78 (' ',' '), # blank lines are kept intact
79 ],
79 ],
80
80
81 # Tests for the escape transformer to leave normal code alone
81 # Tests for the escape transformer to leave normal code alone
82 escaped_noesc =
82 escaped_noesc =
83 [ (' ', ' '),
83 [ (' ', ' '),
84 ('x=1', 'x=1'),
84 ('x=1', 'x=1'),
85 ],
85 ],
86
86
87 # System calls
87 # System calls
88 escaped_shell =
88 escaped_shell =
89 [(i,py3compat.u_format(o)) for i,o in \
89 [(i,py3compat.u_format(o)) for i,o in \
90 [ (u'!ls', "get_ipython().system({u}'ls')"),
90 [ (u'!ls', "get_ipython().system('ls')"),
91 # Double-escape shell, this means to capture the output of the
91 # Double-escape shell, this means to capture the output of the
92 # subprocess and return it
92 # subprocess and return it
93 (u'!!ls', "get_ipython().getoutput({u}'ls')"),
93 (u'!!ls', "get_ipython().getoutput('ls')"),
94 ]],
94 ]],
95
95
96 # Help/object info
96 # Help/object info
97 escaped_help =
97 escaped_help =
98 [(i,py3compat.u_format(o)) for i,o in \
98 [(i,py3compat.u_format(o)) for i,o in \
99 [ (u'?', 'get_ipython().show_usage()'),
99 [ (u'?', 'get_ipython().show_usage()'),
100 (u'?x1', "get_ipython().run_line_magic({u}'pinfo', {u}'x1')"),
100 (u'?x1', "get_ipython().run_line_magic('pinfo', 'x1')"),
101 (u'??x2', "get_ipython().run_line_magic({u}'pinfo2', {u}'x2')"),
101 (u'??x2', "get_ipython().run_line_magic('pinfo2', 'x2')"),
102 (u'?a.*s', "get_ipython().run_line_magic({u}'psearch', {u}'a.*s')"),
102 (u'?a.*s', "get_ipython().run_line_magic('psearch', 'a.*s')"),
103 (u'?%hist1', "get_ipython().run_line_magic({u}'pinfo', {u}'%hist1')"),
103 (u'?%hist1', "get_ipython().run_line_magic('pinfo', '%hist1')"),
104 (u'?%%hist2', "get_ipython().run_line_magic({u}'pinfo', {u}'%%hist2')"),
104 (u'?%%hist2', "get_ipython().run_line_magic('pinfo', '%%hist2')"),
105 (u'?abc = qwe', "get_ipython().run_line_magic({u}'pinfo', {u}'abc')"),
105 (u'?abc = qwe', "get_ipython().run_line_magic('pinfo', 'abc')"),
106 ]],
106 ]],
107
107
108 end_help =
108 end_help =
109 [(i,py3compat.u_format(o)) for i,o in \
109 [(i,py3compat.u_format(o)) for i,o in \
110 [ (u'x3?', "get_ipython().run_line_magic({u}'pinfo', {u}'x3')"),
110 [ (u'x3?', "get_ipython().run_line_magic('pinfo', 'x3')"),
111 (u'x4??', "get_ipython().run_line_magic({u}'pinfo2', {u}'x4')"),
111 (u'x4??', "get_ipython().run_line_magic('pinfo2', 'x4')"),
112 (u'%hist1?', "get_ipython().run_line_magic({u}'pinfo', {u}'%hist1')"),
112 (u'%hist1?', "get_ipython().run_line_magic('pinfo', '%hist1')"),
113 (u'%hist2??', "get_ipython().run_line_magic({u}'pinfo2', {u}'%hist2')"),
113 (u'%hist2??', "get_ipython().run_line_magic('pinfo2', '%hist2')"),
114 (u'%%hist3?', "get_ipython().run_line_magic({u}'pinfo', {u}'%%hist3')"),
114 (u'%%hist3?', "get_ipython().run_line_magic('pinfo', '%%hist3')"),
115 (u'%%hist4??', "get_ipython().run_line_magic({u}'pinfo2', {u}'%%hist4')"),
115 (u'%%hist4??', "get_ipython().run_line_magic('pinfo2', '%%hist4')"),
116 (u'f*?', "get_ipython().run_line_magic({u}'psearch', {u}'f*')"),
116 (u'f*?', "get_ipython().run_line_magic('psearch', 'f*')"),
117 (u'ax.*aspe*?', "get_ipython().run_line_magic({u}'psearch', {u}'ax.*aspe*')"),
117 (u'ax.*aspe*?', "get_ipython().run_line_magic('psearch', 'ax.*aspe*')"),
118 (u'a = abc?', "get_ipython().set_next_input({u}'a = abc');"
118 (u'a = abc?', "get_ipython().set_next_input('a = abc');"
119 "get_ipython().run_line_magic({u}'pinfo', {u}'abc')"),
119 "get_ipython().run_line_magic('pinfo', 'abc')"),
120 (u'a = abc.qe??', "get_ipython().set_next_input({u}'a = abc.qe');"
120 (u'a = abc.qe??', "get_ipython().set_next_input('a = abc.qe');"
121 "get_ipython().run_line_magic({u}'pinfo2', {u}'abc.qe')"),
121 "get_ipython().run_line_magic('pinfo2', 'abc.qe')"),
122 (u'a = *.items?', "get_ipython().set_next_input({u}'a = *.items');"
122 (u'a = *.items?', "get_ipython().set_next_input('a = *.items');"
123 "get_ipython().run_line_magic({u}'psearch', {u}'*.items')"),
123 "get_ipython().run_line_magic('psearch', '*.items')"),
124 (u'plot(a?', "get_ipython().set_next_input({u}'plot(a');"
124 (u'plot(a?', "get_ipython().set_next_input('plot(a');"
125 "get_ipython().run_line_magic({u}'pinfo', {u}'a')"),
125 "get_ipython().run_line_magic('pinfo', 'a')"),
126 (u'a*2 #comment?', 'a*2 #comment?'),
126 (u'a*2 #comment?', 'a*2 #comment?'),
127 ]],
127 ]],
128
128
129 # Explicit magic calls
129 # Explicit magic calls
130 escaped_magic =
130 escaped_magic =
131 [(i,py3compat.u_format(o)) for i,o in \
131 [(i,py3compat.u_format(o)) for i,o in \
132 [ (u'%cd', "get_ipython().run_line_magic({u}'cd', {u}'')"),
132 [ (u'%cd', "get_ipython().run_line_magic('cd', '')"),
133 (u'%cd /home', "get_ipython().run_line_magic({u}'cd', {u}'/home')"),
133 (u'%cd /home', "get_ipython().run_line_magic('cd', '/home')"),
134 # Backslashes need to be escaped.
134 # Backslashes need to be escaped.
135 (u'%cd C:\\User', "get_ipython().run_line_magic({u}'cd', {u}'C:\\\\User')"),
135 (u'%cd C:\\User', "get_ipython().run_line_magic('cd', 'C:\\\\User')"),
136 (u' %magic', " get_ipython().run_line_magic({u}'magic', {u}'')"),
136 (u' %magic', " get_ipython().run_line_magic('magic', '')"),
137 ]],
137 ]],
138
138
139 # Quoting with separate arguments
139 # Quoting with separate arguments
140 escaped_quote =
140 escaped_quote =
141 [ (',f', 'f("")'),
141 [ (',f', 'f("")'),
142 (',f x', 'f("x")'),
142 (',f x', 'f("x")'),
143 (' ,f y', ' f("y")'),
143 (' ,f y', ' f("y")'),
144 (',f a b', 'f("a", "b")'),
144 (',f a b', 'f("a", "b")'),
145 ],
145 ],
146
146
147 # Quoting with single argument
147 # Quoting with single argument
148 escaped_quote2 =
148 escaped_quote2 =
149 [ (';f', 'f("")'),
149 [ (';f', 'f("")'),
150 (';f x', 'f("x")'),
150 (';f x', 'f("x")'),
151 (' ;f y', ' f("y")'),
151 (' ;f y', ' f("y")'),
152 (';f a b', 'f("a b")'),
152 (';f a b', 'f("a b")'),
153 ],
153 ],
154
154
155 # Simply apply parens
155 # Simply apply parens
156 escaped_paren =
156 escaped_paren =
157 [ ('/f', 'f()'),
157 [ ('/f', 'f()'),
158 ('/f x', 'f(x)'),
158 ('/f x', 'f(x)'),
159 (' /f y', ' f(y)'),
159 (' /f y', ' f(y)'),
160 ('/f a b', 'f(a, b)'),
160 ('/f a b', 'f(a, b)'),
161 ],
161 ],
162
162
163 # Check that we transform prompts before other transforms
163 # Check that we transform prompts before other transforms
164 mixed =
164 mixed =
165 [(i,py3compat.u_format(o)) for i,o in \
165 [(i,py3compat.u_format(o)) for i,o in \
166 [ (u'In [1]: %lsmagic', "get_ipython().run_line_magic({u}'lsmagic', {u}'')"),
166 [ (u'In [1]: %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),
167 (u'>>> %lsmagic', "get_ipython().run_line_magic({u}'lsmagic', {u}'')"),
167 (u'>>> %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),
168 (u'In [2]: !ls', "get_ipython().system({u}'ls')"),
168 (u'In [2]: !ls', "get_ipython().system('ls')"),
169 (u'In [3]: abs?', "get_ipython().run_line_magic({u}'pinfo', {u}'abs')"),
169 (u'In [3]: abs?', "get_ipython().run_line_magic('pinfo', 'abs')"),
170 (u'In [4]: b = %who', "b = get_ipython().run_line_magic({u}'who', {u}'')"),
170 (u'In [4]: b = %who', "b = get_ipython().run_line_magic('who', '')"),
171 ]],
171 ]],
172 )
172 )
173
173
174 # multiline syntax examples. Each of these should be a list of lists, with
174 # multiline syntax examples. Each of these should be a list of lists, with
175 # each entry itself having pairs of raw/transformed input. The union (with
175 # each entry itself having pairs of raw/transformed input. The union (with
176 # '\n'.join() of the transformed inputs is what the splitter should produce
176 # '\n'.join() of the transformed inputs is what the splitter should produce
177 # when fed the raw lines one at a time via push.
177 # when fed the raw lines one at a time via push.
178 syntax_ml = \
178 syntax_ml = \
179 dict(classic_prompt =
179 dict(classic_prompt =
180 [ [('>>> for i in range(10):','for i in range(10):'),
180 [ [('>>> for i in range(10):','for i in range(10):'),
181 ('... print i',' print i'),
181 ('... print i',' print i'),
182 ('... ', ''),
182 ('... ', ''),
183 ],
183 ],
184 [('>>> a="""','a="""'),
184 [('>>> a="""','a="""'),
185 ('... 123"""','123"""'),
185 ('... 123"""','123"""'),
186 ],
186 ],
187 [('a="""','a="""'),
187 [('a="""','a="""'),
188 ('... 123','123'),
188 ('... 123','123'),
189 ('... 456"""','456"""'),
189 ('... 456"""','456"""'),
190 ],
190 ],
191 [('a="""','a="""'),
191 [('a="""','a="""'),
192 ('>>> 123','123'),
192 ('>>> 123','123'),
193 ('... 456"""','456"""'),
193 ('... 456"""','456"""'),
194 ],
194 ],
195 [('a="""','a="""'),
195 [('a="""','a="""'),
196 ('123','123'),
196 ('123','123'),
197 ('... 456"""','... 456"""'),
197 ('... 456"""','... 456"""'),
198 ],
198 ],
199 [('....__class__','....__class__'),
199 [('....__class__','....__class__'),
200 ],
200 ],
201 [('a=5', 'a=5'),
201 [('a=5', 'a=5'),
202 ('...', ''),
202 ('...', ''),
203 ],
203 ],
204 [('>>> def f(x):', 'def f(x):'),
204 [('>>> def f(x):', 'def f(x):'),
205 ('...', ''),
205 ('...', ''),
206 ('... return x', ' return x'),
206 ('... return x', ' return x'),
207 ],
207 ],
208 [('board = """....', 'board = """....'),
208 [('board = """....', 'board = """....'),
209 ('....', '....'),
209 ('....', '....'),
210 ('...."""', '...."""'),
210 ('...."""', '...."""'),
211 ],
211 ],
212 ],
212 ],
213
213
214 ipy_prompt =
214 ipy_prompt =
215 [ [('In [24]: for i in range(10):','for i in range(10):'),
215 [ [('In [24]: for i in range(10):','for i in range(10):'),
216 (' ....: print i',' print i'),
216 (' ....: print i',' print i'),
217 (' ....: ', ''),
217 (' ....: ', ''),
218 ],
218 ],
219 [('In [24]: for i in range(10):','for i in range(10):'),
219 [('In [24]: for i in range(10):','for i in range(10):'),
220 # Qt console prompts expand with spaces, not dots
220 # Qt console prompts expand with spaces, not dots
221 (' ...: print i',' print i'),
221 (' ...: print i',' print i'),
222 (' ...: ', ''),
222 (' ...: ', ''),
223 ],
223 ],
224 [('In [24]: for i in range(10):','for i in range(10):'),
224 [('In [24]: for i in range(10):','for i in range(10):'),
225 # Sometimes whitespace preceding '...' has been removed
225 # Sometimes whitespace preceding '...' has been removed
226 ('...: print i',' print i'),
226 ('...: print i',' print i'),
227 ('...: ', ''),
227 ('...: ', ''),
228 ],
228 ],
229 [('In [24]: for i in range(10):','for i in range(10):'),
229 [('In [24]: for i in range(10):','for i in range(10):'),
230 # Space after last continuation prompt has been removed (issue #6674)
230 # Space after last continuation prompt has been removed (issue #6674)
231 ('...: print i',' print i'),
231 ('...: print i',' print i'),
232 ('...:', ''),
232 ('...:', ''),
233 ],
233 ],
234 [('In [2]: a="""','a="""'),
234 [('In [2]: a="""','a="""'),
235 (' ...: 123"""','123"""'),
235 (' ...: 123"""','123"""'),
236 ],
236 ],
237 [('a="""','a="""'),
237 [('a="""','a="""'),
238 (' ...: 123','123'),
238 (' ...: 123','123'),
239 (' ...: 456"""','456"""'),
239 (' ...: 456"""','456"""'),
240 ],
240 ],
241 [('a="""','a="""'),
241 [('a="""','a="""'),
242 ('In [1]: 123','123'),
242 ('In [1]: 123','123'),
243 (' ...: 456"""','456"""'),
243 (' ...: 456"""','456"""'),
244 ],
244 ],
245 [('a="""','a="""'),
245 [('a="""','a="""'),
246 ('123','123'),
246 ('123','123'),
247 (' ...: 456"""',' ...: 456"""'),
247 (' ...: 456"""',' ...: 456"""'),
248 ],
248 ],
249 ],
249 ],
250
250
251 multiline_datastructure_prompt =
251 multiline_datastructure_prompt =
252 [ [('>>> a = [1,','a = [1,'),
252 [ [('>>> a = [1,','a = [1,'),
253 ('... 2]','2]'),
253 ('... 2]','2]'),
254 ],
254 ],
255 ],
255 ],
256
256
257 multiline_datastructure =
257 multiline_datastructure =
258 [ [('b = ("%s"', None),
258 [ [('b = ("%s"', None),
259 ('# comment', None),
259 ('# comment', None),
260 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
260 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
261 ],
261 ],
262 ],
262 ],
263
263
264 multiline_string =
264 multiline_string =
265 [ [("'''foo?", None),
265 [ [("'''foo?", None),
266 ("bar'''", "'''foo?\nbar'''"),
266 ("bar'''", "'''foo?\nbar'''"),
267 ],
267 ],
268 ],
268 ],
269
269
270 leading_indent =
270 leading_indent =
271 [ [(' print "hi"','print "hi"'),
271 [ [(' print "hi"','print "hi"'),
272 ],
272 ],
273 [(' for a in range(5):','for a in range(5):'),
273 [(' for a in range(5):','for a in range(5):'),
274 (' a*2',' a*2'),
274 (' a*2',' a*2'),
275 ],
275 ],
276 [(' a="""','a="""'),
276 [(' a="""','a="""'),
277 (' 123"""','123"""'),
277 (' 123"""','123"""'),
278 ],
278 ],
279 [('a="""','a="""'),
279 [('a="""','a="""'),
280 (' 123"""',' 123"""'),
280 (' 123"""',' 123"""'),
281 ],
281 ],
282 ],
282 ],
283
283
284 cellmagic =
284 cellmagic =
285 [ [(u'%%foo a', None),
285 [ [(u'%%foo a', None),
286 (None, u_fmt("get_ipython().run_cell_magic({u}'foo', {u}'a', {u}'')")),
286 (None, u_fmt("get_ipython().run_cell_magic('foo', 'a', '')")),
287 ],
287 ],
288 [(u'%%bar 123', None),
288 [(u'%%bar 123', None),
289 (u'hello', None),
289 (u'hello', None),
290 (None , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
290 (None , u_fmt("get_ipython().run_cell_magic('bar', '123', 'hello')")),
291 ],
291 ],
292 [(u'a=5', 'a=5'),
292 [(u'a=5', 'a=5'),
293 (u'%%cellmagic', '%%cellmagic'),
293 (u'%%cellmagic', '%%cellmagic'),
294 ],
294 ],
295 ],
295 ],
296
296
297 escaped =
297 escaped =
298 [ [('%abc def \\', None),
298 [ [('%abc def \\', None),
299 ('ghi', u_fmt("get_ipython().run_line_magic({u}'abc', {u}'def ghi')")),
299 ('ghi', u_fmt("get_ipython().run_line_magic('abc', 'def ghi')")),
300 ],
300 ],
301 [('%abc def \\', None),
301 [('%abc def \\', None),
302 ('ghi\\', None),
302 ('ghi\\', None),
303 (None, u_fmt("get_ipython().run_line_magic({u}'abc', {u}'def ghi')")),
303 (None, u_fmt("get_ipython().run_line_magic('abc', 'def ghi')")),
304 ],
304 ],
305 ],
305 ],
306
306
307 assign_magic =
307 assign_magic =
308 [ [(u'a = %bc de \\', None),
308 [ [(u'a = %bc de \\', None),
309 (u'fg', u_fmt("a = get_ipython().run_line_magic({u}'bc', {u}'de fg')")),
309 (u'fg', u_fmt("a = get_ipython().run_line_magic('bc', 'de fg')")),
310 ],
310 ],
311 [(u'a = %bc de \\', None),
311 [(u'a = %bc de \\', None),
312 (u'fg\\', None),
312 (u'fg\\', None),
313 (None, u_fmt("a = get_ipython().run_line_magic({u}'bc', {u}'de fg')")),
313 (None, u_fmt("a = get_ipython().run_line_magic('bc', 'de fg')")),
314 ],
314 ],
315 ],
315 ],
316
316
317 assign_system =
317 assign_system =
318 [ [(u'a = !bc de \\', None),
318 [ [(u'a = !bc de \\', None),
319 (u'fg', u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
319 (u'fg', u_fmt("a = get_ipython().getoutput('bc de fg')")),
320 ],
320 ],
321 [(u'a = !bc de \\', None),
321 [(u'a = !bc de \\', None),
322 (u'fg\\', None),
322 (u'fg\\', None),
323 (None, u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
323 (None, u_fmt("a = get_ipython().getoutput('bc de fg')")),
324 ],
324 ],
325 ],
325 ],
326 )
326 )
327
327
328
328
329 def test_assign_system():
329 def test_assign_system():
330 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
330 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
331
331
332 def test_assign_magic():
332 def test_assign_magic():
333 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
333 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
334
334
335 def test_classic_prompt():
335 def test_classic_prompt():
336 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
336 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
337 for example in syntax_ml['classic_prompt']:
337 for example in syntax_ml['classic_prompt']:
338 transform_checker(example, ipt.classic_prompt)
338 transform_checker(example, ipt.classic_prompt)
339 for example in syntax_ml['multiline_datastructure_prompt']:
339 for example in syntax_ml['multiline_datastructure_prompt']:
340 transform_checker(example, ipt.classic_prompt)
340 transform_checker(example, ipt.classic_prompt)
341
341
342 # Check that we don't transform the second line if the first is obviously
342 # Check that we don't transform the second line if the first is obviously
343 # IPython syntax
343 # IPython syntax
344 transform_checker([
344 transform_checker([
345 (u'%foo', '%foo'),
345 (u'%foo', '%foo'),
346 (u'>>> bar', '>>> bar'),
346 (u'>>> bar', '>>> bar'),
347 ], ipt.classic_prompt)
347 ], ipt.classic_prompt)
348
348
349
349
350 def test_ipy_prompt():
350 def test_ipy_prompt():
351 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
351 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
352 for example in syntax_ml['ipy_prompt']:
352 for example in syntax_ml['ipy_prompt']:
353 transform_checker(example, ipt.ipy_prompt)
353 transform_checker(example, ipt.ipy_prompt)
354
354
355 # Check that we don't transform the second line if we're inside a cell magic
355 # Check that we don't transform the second line if we're inside a cell magic
356 transform_checker([
356 transform_checker([
357 (u'%%foo', '%%foo'),
357 (u'%%foo', '%%foo'),
358 (u'In [1]: bar', 'In [1]: bar'),
358 (u'In [1]: bar', 'In [1]: bar'),
359 ], ipt.ipy_prompt)
359 ], ipt.ipy_prompt)
360
360
361 def test_assemble_logical_lines():
361 def test_assemble_logical_lines():
362 tests = \
362 tests = \
363 [ [(u"a = \\", None),
363 [ [(u"a = \\", None),
364 (u"123", u"a = 123"),
364 (u"123", u"a = 123"),
365 ],
365 ],
366 [(u"a = \\", None), # Test resetting when within a multi-line string
366 [(u"a = \\", None), # Test resetting when within a multi-line string
367 (u"12 *\\", None),
367 (u"12 *\\", None),
368 (None, u"a = 12 *"),
368 (None, u"a = 12 *"),
369 ],
369 ],
370 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
370 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
371 ],
371 ],
372 ]
372 ]
373 for example in tests:
373 for example in tests:
374 transform_checker(example, ipt.assemble_logical_lines)
374 transform_checker(example, ipt.assemble_logical_lines)
375
375
376 def test_assemble_python_lines():
376 def test_assemble_python_lines():
377 tests = \
377 tests = \
378 [ [(u"a = '''", None),
378 [ [(u"a = '''", None),
379 (u"abc'''", u"a = '''\nabc'''"),
379 (u"abc'''", u"a = '''\nabc'''"),
380 ],
380 ],
381 [(u"a = '''", None), # Test resetting when within a multi-line string
381 [(u"a = '''", None), # Test resetting when within a multi-line string
382 (u"def", None),
382 (u"def", None),
383 (None, u"a = '''\ndef"),
383 (None, u"a = '''\ndef"),
384 ],
384 ],
385 [(u"a = [1,", None),
385 [(u"a = [1,", None),
386 (u"2]", u"a = [1,\n2]"),
386 (u"2]", u"a = [1,\n2]"),
387 ],
387 ],
388 [(u"a = [1,", None), # Test resetting when within a multi-line string
388 [(u"a = [1,", None), # Test resetting when within a multi-line string
389 (u"2,", None),
389 (u"2,", None),
390 (None, u"a = [1,\n2,"),
390 (None, u"a = [1,\n2,"),
391 ],
391 ],
392 [(u"a = '''", None), # Test line continuation within a multi-line string
392 [(u"a = '''", None), # Test line continuation within a multi-line string
393 (u"abc\\", None),
393 (u"abc\\", None),
394 (u"def", None),
394 (u"def", None),
395 (u"'''", u"a = '''\nabc\\\ndef\n'''"),
395 (u"'''", u"a = '''\nabc\\\ndef\n'''"),
396 ],
396 ],
397 ] + syntax_ml['multiline_datastructure']
397 ] + syntax_ml['multiline_datastructure']
398 for example in tests:
398 for example in tests:
399 transform_checker(example, ipt.assemble_python_lines)
399 transform_checker(example, ipt.assemble_python_lines)
400
400
401
401
402 def test_help_end():
402 def test_help_end():
403 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
403 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
404
404
405 def test_escaped_noesc():
405 def test_escaped_noesc():
406 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
406 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
407
407
408
408
409 def test_escaped_shell():
409 def test_escaped_shell():
410 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
410 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
411
411
412
412
413 def test_escaped_help():
413 def test_escaped_help():
414 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
414 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
415
415
416
416
417 def test_escaped_magic():
417 def test_escaped_magic():
418 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
418 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
419
419
420
420
421 def test_escaped_quote():
421 def test_escaped_quote():
422 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
422 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
423
423
424
424
425 def test_escaped_quote2():
425 def test_escaped_quote2():
426 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
426 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
427
427
428
428
429 def test_escaped_paren():
429 def test_escaped_paren():
430 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
430 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
431
431
432
432
433 def test_cellmagic():
433 def test_cellmagic():
434 for example in syntax_ml['cellmagic']:
434 for example in syntax_ml['cellmagic']:
435 transform_checker(example, ipt.cellmagic)
435 transform_checker(example, ipt.cellmagic)
436
436
437 line_example = [(u'%%bar 123', None),
437 line_example = [(u'%%bar 123', None),
438 (u'hello', None),
438 (u'hello', None),
439 (u'' , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
439 (u'' , u_fmt("get_ipython().run_cell_magic('bar', '123', 'hello')")),
440 ]
440 ]
441 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
441 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
442
442
443 def test_has_comment():
443 def test_has_comment():
444 tests = [('text', False),
444 tests = [('text', False),
445 ('text #comment', True),
445 ('text #comment', True),
446 ('text #comment\n', True),
446 ('text #comment\n', True),
447 ('#comment', True),
447 ('#comment', True),
448 ('#comment\n', True),
448 ('#comment\n', True),
449 ('a = "#string"', False),
449 ('a = "#string"', False),
450 ('a = "#string" # comment', True),
450 ('a = "#string" # comment', True),
451 ('a #comment not "string"', True),
451 ('a #comment not "string"', True),
452 ]
452 ]
453 tt.check_pairs(ipt.has_comment, tests)
453 tt.check_pairs(ipt.has_comment, tests)
454
454
455 @ipt.TokenInputTransformer.wrap
455 @ipt.TokenInputTransformer.wrap
456 def decistmt(tokens):
456 def decistmt(tokens):
457 """Substitute Decimals for floats in a string of statements.
457 """Substitute Decimals for floats in a string of statements.
458
458
459 Based on an example from the tokenize module docs.
459 Based on an example from the tokenize module docs.
460 """
460 """
461 result = []
461 result = []
462 for toknum, tokval, _, _, _ in tokens:
462 for toknum, tokval, _, _, _ in tokens:
463 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
463 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
464 for newtok in [
464 for newtok in [
465 (tokenize.NAME, 'Decimal'),
465 (tokenize.NAME, 'Decimal'),
466 (tokenize.OP, '('),
466 (tokenize.OP, '('),
467 (tokenize.STRING, repr(tokval)),
467 (tokenize.STRING, repr(tokval)),
468 (tokenize.OP, ')')
468 (tokenize.OP, ')')
469 ]:
469 ]:
470 yield newtok
470 yield newtok
471 else:
471 else:
472 yield (toknum, tokval)
472 yield (toknum, tokval)
473
473
474
474
475
475
476 def test_token_input_transformer():
476 def test_token_input_transformer():
477 tests = [(u'1.2', u_fmt(u"Decimal ({u}'1.2')")),
477 tests = [(u'1.2', u_fmt(u"Decimal ('1.2')")),
478 (u'"1.2"', u'"1.2"'),
478 (u'"1.2"', u'"1.2"'),
479 ]
479 ]
480 tt.check_pairs(transform_and_reset(decistmt), tests)
480 tt.check_pairs(transform_and_reset(decistmt), tests)
481 ml_tests = \
481 ml_tests = \
482 [ [(u"a = 1.2; b = '''x", None),
482 [ [(u"a = 1.2; b = '''x", None),
483 (u"y'''", u_fmt(u"a =Decimal ({u}'1.2');b ='''x\ny'''")),
483 (u"y'''", u_fmt(u"a =Decimal ('1.2');b ='''x\ny'''")),
484 ],
484 ],
485 [(u"a = [1.2,", None),
485 [(u"a = [1.2,", None),
486 (u"3]", u_fmt(u"a =[Decimal ({u}'1.2'),\n3 ]")),
486 (u"3]", u_fmt(u"a =[Decimal ('1.2'),\n3 ]")),
487 ],
487 ],
488 [(u"a = '''foo", None), # Test resetting when within a multi-line string
488 [(u"a = '''foo", None), # Test resetting when within a multi-line string
489 (u"bar", None),
489 (u"bar", None),
490 (None, u"a = '''foo\nbar"),
490 (None, u"a = '''foo\nbar"),
491 ],
491 ],
492 ]
492 ]
493 for example in ml_tests:
493 for example in ml_tests:
494 transform_checker(example, decistmt)
494 transform_checker(example, decistmt)
@@ -1,1044 +1,1044 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions.
2 """Tests for various magic functions.
3
3
4 Needs to be run by nose (to make ipython session available).
4 Needs to be run by nose (to make ipython session available).
5 """
5 """
6
6
7 import io
7 import io
8 import os
8 import os
9 import re
9 import re
10 import sys
10 import sys
11 import warnings
11 import warnings
12 from unittest import TestCase
12 from unittest import TestCase
13 from importlib import invalidate_caches
13 from importlib import invalidate_caches
14 from io import StringIO
14 from io import StringIO
15
15
16 import nose.tools as nt
16 import nose.tools as nt
17
17
18 import shlex
18 import shlex
19
19
20 from IPython import get_ipython
20 from IPython import get_ipython
21 from IPython.core import magic
21 from IPython.core import magic
22 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
23 from IPython.core.magic import (Magics, magics_class, line_magic,
23 from IPython.core.magic import (Magics, magics_class, line_magic,
24 cell_magic,
24 cell_magic,
25 register_line_magic, register_cell_magic)
25 register_line_magic, register_cell_magic)
26 from IPython.core.magics import execution, script, code, logging
26 from IPython.core.magics import execution, script, code, logging
27 from IPython.testing import decorators as dec
27 from IPython.testing import decorators as dec
28 from IPython.testing import tools as tt
28 from IPython.testing import tools as tt
29 from IPython.utils import py3compat
29 from IPython.utils import py3compat
30 from IPython.utils.io import capture_output
30 from IPython.utils.io import capture_output
31 from IPython.utils.tempdir import TemporaryDirectory
31 from IPython.utils.tempdir import TemporaryDirectory
32 from IPython.utils.process import find_cmd
32 from IPython.utils.process import find_cmd
33
33
34
34
35
35
36 _ip = get_ipython()
36 _ip = get_ipython()
37
37
38 @magic.magics_class
38 @magic.magics_class
39 class DummyMagics(magic.Magics): pass
39 class DummyMagics(magic.Magics): pass
40
40
41 def test_extract_code_ranges():
41 def test_extract_code_ranges():
42 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
42 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
43 expected = [(0, 1),
43 expected = [(0, 1),
44 (2, 3),
44 (2, 3),
45 (4, 6),
45 (4, 6),
46 (6, 9),
46 (6, 9),
47 (9, 14),
47 (9, 14),
48 (16, None),
48 (16, None),
49 (None, 9),
49 (None, 9),
50 (9, None),
50 (9, None),
51 (None, 13),
51 (None, 13),
52 (None, None)]
52 (None, None)]
53 actual = list(code.extract_code_ranges(instr))
53 actual = list(code.extract_code_ranges(instr))
54 nt.assert_equal(actual, expected)
54 nt.assert_equal(actual, expected)
55
55
56 def test_extract_symbols():
56 def test_extract_symbols():
57 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
57 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
58 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
58 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
59 expected = [([], ['a']),
59 expected = [([], ['a']),
60 (["def b():\n return 42\n"], []),
60 (["def b():\n return 42\n"], []),
61 (["class A: pass\n"], []),
61 (["class A: pass\n"], []),
62 (["class A: pass\n", "def b():\n return 42\n"], []),
62 (["class A: pass\n", "def b():\n return 42\n"], []),
63 (["class A: pass\n"], ['a']),
63 (["class A: pass\n"], ['a']),
64 ([], ['z'])]
64 ([], ['z'])]
65 for symbols, exp in zip(symbols_args, expected):
65 for symbols, exp in zip(symbols_args, expected):
66 nt.assert_equal(code.extract_symbols(source, symbols), exp)
66 nt.assert_equal(code.extract_symbols(source, symbols), exp)
67
67
68
68
69 def test_extract_symbols_raises_exception_with_non_python_code():
69 def test_extract_symbols_raises_exception_with_non_python_code():
70 source = ("=begin A Ruby program :)=end\n"
70 source = ("=begin A Ruby program :)=end\n"
71 "def hello\n"
71 "def hello\n"
72 "puts 'Hello world'\n"
72 "puts 'Hello world'\n"
73 "end")
73 "end")
74 with nt.assert_raises(SyntaxError):
74 with nt.assert_raises(SyntaxError):
75 code.extract_symbols(source, "hello")
75 code.extract_symbols(source, "hello")
76
76
77 def test_config():
77 def test_config():
78 """ test that config magic does not raise
78 """ test that config magic does not raise
79 can happen if Configurable init is moved too early into
79 can happen if Configurable init is moved too early into
80 Magics.__init__ as then a Config object will be registerd as a
80 Magics.__init__ as then a Config object will be registerd as a
81 magic.
81 magic.
82 """
82 """
83 ## should not raise.
83 ## should not raise.
84 _ip.magic('config')
84 _ip.magic('config')
85
85
86 def test_config_available_configs():
86 def test_config_available_configs():
87 """ test that config magic prints available configs in unique and
87 """ test that config magic prints available configs in unique and
88 sorted order. """
88 sorted order. """
89 with capture_output() as captured:
89 with capture_output() as captured:
90 _ip.magic('config')
90 _ip.magic('config')
91
91
92 stdout = captured.stdout
92 stdout = captured.stdout
93 config_classes = stdout.strip().split('\n')[1:]
93 config_classes = stdout.strip().split('\n')[1:]
94 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
94 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
95
95
96 def test_config_print_class():
96 def test_config_print_class():
97 """ test that config with a classname prints the class's options. """
97 """ test that config with a classname prints the class's options. """
98 with capture_output() as captured:
98 with capture_output() as captured:
99 _ip.magic('config TerminalInteractiveShell')
99 _ip.magic('config TerminalInteractiveShell')
100
100
101 stdout = captured.stdout
101 stdout = captured.stdout
102 if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
102 if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
103 print(stdout)
103 print(stdout)
104 raise AssertionError("1st line of stdout not like "
104 raise AssertionError("1st line of stdout not like "
105 "'TerminalInteractiveShell.* options'")
105 "'TerminalInteractiveShell.* options'")
106
106
107 def test_rehashx():
107 def test_rehashx():
108 # clear up everything
108 # clear up everything
109 _ip.alias_manager.clear_aliases()
109 _ip.alias_manager.clear_aliases()
110 del _ip.db['syscmdlist']
110 del _ip.db['syscmdlist']
111
111
112 _ip.magic('rehashx')
112 _ip.magic('rehashx')
113 # Practically ALL ipython development systems will have more than 10 aliases
113 # Practically ALL ipython development systems will have more than 10 aliases
114
114
115 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
115 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
116 for name, cmd in _ip.alias_manager.aliases:
116 for name, cmd in _ip.alias_manager.aliases:
117 # we must strip dots from alias names
117 # we must strip dots from alias names
118 nt.assert_not_in('.', name)
118 nt.assert_not_in('.', name)
119
119
120 # rehashx must fill up syscmdlist
120 # rehashx must fill up syscmdlist
121 scoms = _ip.db['syscmdlist']
121 scoms = _ip.db['syscmdlist']
122 nt.assert_true(len(scoms) > 10)
122 nt.assert_true(len(scoms) > 10)
123
123
124
124
125 def test_magic_parse_options():
125 def test_magic_parse_options():
126 """Test that we don't mangle paths when parsing magic options."""
126 """Test that we don't mangle paths when parsing magic options."""
127 ip = get_ipython()
127 ip = get_ipython()
128 path = 'c:\\x'
128 path = 'c:\\x'
129 m = DummyMagics(ip)
129 m = DummyMagics(ip)
130 opts = m.parse_options('-f %s' % path,'f:')[0]
130 opts = m.parse_options('-f %s' % path,'f:')[0]
131 # argv splitting is os-dependent
131 # argv splitting is os-dependent
132 if os.name == 'posix':
132 if os.name == 'posix':
133 expected = 'c:x'
133 expected = 'c:x'
134 else:
134 else:
135 expected = path
135 expected = path
136 nt.assert_equal(opts['f'], expected)
136 nt.assert_equal(opts['f'], expected)
137
137
138 def test_magic_parse_long_options():
138 def test_magic_parse_long_options():
139 """Magic.parse_options can handle --foo=bar long options"""
139 """Magic.parse_options can handle --foo=bar long options"""
140 ip = get_ipython()
140 ip = get_ipython()
141 m = DummyMagics(ip)
141 m = DummyMagics(ip)
142 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
142 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
143 nt.assert_in('foo', opts)
143 nt.assert_in('foo', opts)
144 nt.assert_in('bar', opts)
144 nt.assert_in('bar', opts)
145 nt.assert_equal(opts['bar'], "bubble")
145 nt.assert_equal(opts['bar'], "bubble")
146
146
147
147
148 @dec.skip_without('sqlite3')
148 @dec.skip_without('sqlite3')
149 def doctest_hist_f():
149 def doctest_hist_f():
150 """Test %hist -f with temporary filename.
150 """Test %hist -f with temporary filename.
151
151
152 In [9]: import tempfile
152 In [9]: import tempfile
153
153
154 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
154 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
155
155
156 In [11]: %hist -nl -f $tfile 3
156 In [11]: %hist -nl -f $tfile 3
157
157
158 In [13]: import os; os.unlink(tfile)
158 In [13]: import os; os.unlink(tfile)
159 """
159 """
160
160
161
161
162 @dec.skip_without('sqlite3')
162 @dec.skip_without('sqlite3')
163 def doctest_hist_r():
163 def doctest_hist_r():
164 """Test %hist -r
164 """Test %hist -r
165
165
166 XXX - This test is not recording the output correctly. For some reason, in
166 XXX - This test is not recording the output correctly. For some reason, in
167 testing mode the raw history isn't getting populated. No idea why.
167 testing mode the raw history isn't getting populated. No idea why.
168 Disabling the output checking for now, though at least we do run it.
168 Disabling the output checking for now, though at least we do run it.
169
169
170 In [1]: 'hist' in _ip.lsmagic()
170 In [1]: 'hist' in _ip.lsmagic()
171 Out[1]: True
171 Out[1]: True
172
172
173 In [2]: x=1
173 In [2]: x=1
174
174
175 In [3]: %hist -rl 2
175 In [3]: %hist -rl 2
176 x=1 # random
176 x=1 # random
177 %hist -r 2
177 %hist -r 2
178 """
178 """
179
179
180
180
181 @dec.skip_without('sqlite3')
181 @dec.skip_without('sqlite3')
182 def doctest_hist_op():
182 def doctest_hist_op():
183 """Test %hist -op
183 """Test %hist -op
184
184
185 In [1]: class b(float):
185 In [1]: class b(float):
186 ...: pass
186 ...: pass
187 ...:
187 ...:
188
188
189 In [2]: class s(object):
189 In [2]: class s(object):
190 ...: def __str__(self):
190 ...: def __str__(self):
191 ...: return 's'
191 ...: return 's'
192 ...:
192 ...:
193
193
194 In [3]:
194 In [3]:
195
195
196 In [4]: class r(b):
196 In [4]: class r(b):
197 ...: def __repr__(self):
197 ...: def __repr__(self):
198 ...: return 'r'
198 ...: return 'r'
199 ...:
199 ...:
200
200
201 In [5]: class sr(s,r): pass
201 In [5]: class sr(s,r): pass
202 ...:
202 ...:
203
203
204 In [6]:
204 In [6]:
205
205
206 In [7]: bb=b()
206 In [7]: bb=b()
207
207
208 In [8]: ss=s()
208 In [8]: ss=s()
209
209
210 In [9]: rr=r()
210 In [9]: rr=r()
211
211
212 In [10]: ssrr=sr()
212 In [10]: ssrr=sr()
213
213
214 In [11]: 4.5
214 In [11]: 4.5
215 Out[11]: 4.5
215 Out[11]: 4.5
216
216
217 In [12]: str(ss)
217 In [12]: str(ss)
218 Out[12]: 's'
218 Out[12]: 's'
219
219
220 In [13]:
220 In [13]:
221
221
222 In [14]: %hist -op
222 In [14]: %hist -op
223 >>> class b:
223 >>> class b:
224 ... pass
224 ... pass
225 ...
225 ...
226 >>> class s(b):
226 >>> class s(b):
227 ... def __str__(self):
227 ... def __str__(self):
228 ... return 's'
228 ... return 's'
229 ...
229 ...
230 >>>
230 >>>
231 >>> class r(b):
231 >>> class r(b):
232 ... def __repr__(self):
232 ... def __repr__(self):
233 ... return 'r'
233 ... return 'r'
234 ...
234 ...
235 >>> class sr(s,r): pass
235 >>> class sr(s,r): pass
236 >>>
236 >>>
237 >>> bb=b()
237 >>> bb=b()
238 >>> ss=s()
238 >>> ss=s()
239 >>> rr=r()
239 >>> rr=r()
240 >>> ssrr=sr()
240 >>> ssrr=sr()
241 >>> 4.5
241 >>> 4.5
242 4.5
242 4.5
243 >>> str(ss)
243 >>> str(ss)
244 's'
244 's'
245 >>>
245 >>>
246 """
246 """
247
247
248 def test_hist_pof():
248 def test_hist_pof():
249 ip = get_ipython()
249 ip = get_ipython()
250 ip.run_cell(u"1+2", store_history=True)
250 ip.run_cell(u"1+2", store_history=True)
251 #raise Exception(ip.history_manager.session_number)
251 #raise Exception(ip.history_manager.session_number)
252 #raise Exception(list(ip.history_manager._get_range_session()))
252 #raise Exception(list(ip.history_manager._get_range_session()))
253 with TemporaryDirectory() as td:
253 with TemporaryDirectory() as td:
254 tf = os.path.join(td, 'hist.py')
254 tf = os.path.join(td, 'hist.py')
255 ip.run_line_magic('history', '-pof %s' % tf)
255 ip.run_line_magic('history', '-pof %s' % tf)
256 assert os.path.isfile(tf)
256 assert os.path.isfile(tf)
257
257
258
258
259 @dec.skip_without('sqlite3')
259 @dec.skip_without('sqlite3')
260 def test_macro():
260 def test_macro():
261 ip = get_ipython()
261 ip = get_ipython()
262 ip.history_manager.reset() # Clear any existing history.
262 ip.history_manager.reset() # Clear any existing history.
263 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
263 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
264 for i, cmd in enumerate(cmds, start=1):
264 for i, cmd in enumerate(cmds, start=1):
265 ip.history_manager.store_inputs(i, cmd)
265 ip.history_manager.store_inputs(i, cmd)
266 ip.magic("macro test 1-3")
266 ip.magic("macro test 1-3")
267 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
267 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
268
268
269 # List macros
269 # List macros
270 nt.assert_in("test", ip.magic("macro"))
270 nt.assert_in("test", ip.magic("macro"))
271
271
272
272
273 @dec.skip_without('sqlite3')
273 @dec.skip_without('sqlite3')
274 def test_macro_run():
274 def test_macro_run():
275 """Test that we can run a multi-line macro successfully."""
275 """Test that we can run a multi-line macro successfully."""
276 ip = get_ipython()
276 ip = get_ipython()
277 ip.history_manager.reset()
277 ip.history_manager.reset()
278 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
278 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
279 "%macro test 2-3"]
279 "%macro test 2-3"]
280 for cmd in cmds:
280 for cmd in cmds:
281 ip.run_cell(cmd, store_history=True)
281 ip.run_cell(cmd, store_history=True)
282 nt.assert_equal(ip.user_ns["test"].value,
282 nt.assert_equal(ip.user_ns["test"].value,
283 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
283 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
284 with tt.AssertPrints("12"):
284 with tt.AssertPrints("12"):
285 ip.run_cell("test")
285 ip.run_cell("test")
286 with tt.AssertPrints("13"):
286 with tt.AssertPrints("13"):
287 ip.run_cell("test")
287 ip.run_cell("test")
288
288
289
289
290 def test_magic_magic():
290 def test_magic_magic():
291 """Test %magic"""
291 """Test %magic"""
292 ip = get_ipython()
292 ip = get_ipython()
293 with capture_output() as captured:
293 with capture_output() as captured:
294 ip.magic("magic")
294 ip.magic("magic")
295
295
296 stdout = captured.stdout
296 stdout = captured.stdout
297 nt.assert_in('%magic', stdout)
297 nt.assert_in('%magic', stdout)
298 nt.assert_in('IPython', stdout)
298 nt.assert_in('IPython', stdout)
299 nt.assert_in('Available', stdout)
299 nt.assert_in('Available', stdout)
300
300
301
301
302 @dec.skipif_not_numpy
302 @dec.skipif_not_numpy
303 def test_numpy_reset_array_undec():
303 def test_numpy_reset_array_undec():
304 "Test '%reset array' functionality"
304 "Test '%reset array' functionality"
305 _ip.ex('import numpy as np')
305 _ip.ex('import numpy as np')
306 _ip.ex('a = np.empty(2)')
306 _ip.ex('a = np.empty(2)')
307 nt.assert_in('a', _ip.user_ns)
307 nt.assert_in('a', _ip.user_ns)
308 _ip.magic('reset -f array')
308 _ip.magic('reset -f array')
309 nt.assert_not_in('a', _ip.user_ns)
309 nt.assert_not_in('a', _ip.user_ns)
310
310
311 def test_reset_out():
311 def test_reset_out():
312 "Test '%reset out' magic"
312 "Test '%reset out' magic"
313 _ip.run_cell("parrot = 'dead'", store_history=True)
313 _ip.run_cell("parrot = 'dead'", store_history=True)
314 # test '%reset -f out', make an Out prompt
314 # test '%reset -f out', make an Out prompt
315 _ip.run_cell("parrot", store_history=True)
315 _ip.run_cell("parrot", store_history=True)
316 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
316 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
317 _ip.magic('reset -f out')
317 _ip.magic('reset -f out')
318 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
318 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
319 nt.assert_equal(len(_ip.user_ns['Out']), 0)
319 nt.assert_equal(len(_ip.user_ns['Out']), 0)
320
320
321 def test_reset_in():
321 def test_reset_in():
322 "Test '%reset in' magic"
322 "Test '%reset in' magic"
323 # test '%reset -f in'
323 # test '%reset -f in'
324 _ip.run_cell("parrot", store_history=True)
324 _ip.run_cell("parrot", store_history=True)
325 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
325 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
326 _ip.magic('%reset -f in')
326 _ip.magic('%reset -f in')
327 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
327 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
328 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
328 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
329
329
330 def test_reset_dhist():
330 def test_reset_dhist():
331 "Test '%reset dhist' magic"
331 "Test '%reset dhist' magic"
332 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
332 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
333 _ip.magic('cd ' + os.path.dirname(nt.__file__))
333 _ip.magic('cd ' + os.path.dirname(nt.__file__))
334 _ip.magic('cd -')
334 _ip.magic('cd -')
335 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
335 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
336 _ip.magic('reset -f dhist')
336 _ip.magic('reset -f dhist')
337 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
337 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
338 _ip.run_cell("_dh = [d for d in tmp]") #restore
338 _ip.run_cell("_dh = [d for d in tmp]") #restore
339
339
340 def test_reset_in_length():
340 def test_reset_in_length():
341 "Test that '%reset in' preserves In[] length"
341 "Test that '%reset in' preserves In[] length"
342 _ip.run_cell("print 'foo'")
342 _ip.run_cell("print 'foo'")
343 _ip.run_cell("reset -f in")
343 _ip.run_cell("reset -f in")
344 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
344 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
345
345
346 def test_tb_syntaxerror():
346 def test_tb_syntaxerror():
347 """test %tb after a SyntaxError"""
347 """test %tb after a SyntaxError"""
348 ip = get_ipython()
348 ip = get_ipython()
349 ip.run_cell("for")
349 ip.run_cell("for")
350
350
351 # trap and validate stdout
351 # trap and validate stdout
352 save_stdout = sys.stdout
352 save_stdout = sys.stdout
353 try:
353 try:
354 sys.stdout = StringIO()
354 sys.stdout = StringIO()
355 ip.run_cell("%tb")
355 ip.run_cell("%tb")
356 out = sys.stdout.getvalue()
356 out = sys.stdout.getvalue()
357 finally:
357 finally:
358 sys.stdout = save_stdout
358 sys.stdout = save_stdout
359 # trim output, and only check the last line
359 # trim output, and only check the last line
360 last_line = out.rstrip().splitlines()[-1].strip()
360 last_line = out.rstrip().splitlines()[-1].strip()
361 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
361 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
362
362
363
363
364 def test_time():
364 def test_time():
365 ip = get_ipython()
365 ip = get_ipython()
366
366
367 with tt.AssertPrints("Wall time: "):
367 with tt.AssertPrints("Wall time: "):
368 ip.run_cell("%time None")
368 ip.run_cell("%time None")
369
369
370 ip.run_cell("def f(kmjy):\n"
370 ip.run_cell("def f(kmjy):\n"
371 " %time print (2*kmjy)")
371 " %time print (2*kmjy)")
372
372
373 with tt.AssertPrints("Wall time: "):
373 with tt.AssertPrints("Wall time: "):
374 with tt.AssertPrints("hihi", suppress=False):
374 with tt.AssertPrints("hihi", suppress=False):
375 ip.run_cell("f('hi')")
375 ip.run_cell("f('hi')")
376
376
377
377
378 @dec.skip_win32
378 @dec.skip_win32
379 def test_time2():
379 def test_time2():
380 ip = get_ipython()
380 ip = get_ipython()
381
381
382 with tt.AssertPrints("CPU times: user "):
382 with tt.AssertPrints("CPU times: user "):
383 ip.run_cell("%time None")
383 ip.run_cell("%time None")
384
384
385 def test_time3():
385 def test_time3():
386 """Erroneous magic function calls, issue gh-3334"""
386 """Erroneous magic function calls, issue gh-3334"""
387 ip = get_ipython()
387 ip = get_ipython()
388 ip.user_ns.pop('run', None)
388 ip.user_ns.pop('run', None)
389
389
390 with tt.AssertNotPrints("not found", channel='stderr'):
390 with tt.AssertNotPrints("not found", channel='stderr'):
391 ip.run_cell("%%time\n"
391 ip.run_cell("%%time\n"
392 "run = 0\n"
392 "run = 0\n"
393 "run += 1")
393 "run += 1")
394
394
395 def test_doctest_mode():
395 def test_doctest_mode():
396 "Toggle doctest_mode twice, it should be a no-op and run without error"
396 "Toggle doctest_mode twice, it should be a no-op and run without error"
397 _ip.magic('doctest_mode')
397 _ip.magic('doctest_mode')
398 _ip.magic('doctest_mode')
398 _ip.magic('doctest_mode')
399
399
400
400
401 def test_parse_options():
401 def test_parse_options():
402 """Tests for basic options parsing in magics."""
402 """Tests for basic options parsing in magics."""
403 # These are only the most minimal of tests, more should be added later. At
403 # These are only the most minimal of tests, more should be added later. At
404 # the very least we check that basic text/unicode calls work OK.
404 # the very least we check that basic text/unicode calls work OK.
405 m = DummyMagics(_ip)
405 m = DummyMagics(_ip)
406 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
406 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
407 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
407 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
408
408
409
409
410 def test_dirops():
410 def test_dirops():
411 """Test various directory handling operations."""
411 """Test various directory handling operations."""
412 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
412 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
413 curpath = os.getcwd
413 curpath = os.getcwd
414 startdir = os.getcwd()
414 startdir = os.getcwd()
415 ipdir = os.path.realpath(_ip.ipython_dir)
415 ipdir = os.path.realpath(_ip.ipython_dir)
416 try:
416 try:
417 _ip.magic('cd "%s"' % ipdir)
417 _ip.magic('cd "%s"' % ipdir)
418 nt.assert_equal(curpath(), ipdir)
418 nt.assert_equal(curpath(), ipdir)
419 _ip.magic('cd -')
419 _ip.magic('cd -')
420 nt.assert_equal(curpath(), startdir)
420 nt.assert_equal(curpath(), startdir)
421 _ip.magic('pushd "%s"' % ipdir)
421 _ip.magic('pushd "%s"' % ipdir)
422 nt.assert_equal(curpath(), ipdir)
422 nt.assert_equal(curpath(), ipdir)
423 _ip.magic('popd')
423 _ip.magic('popd')
424 nt.assert_equal(curpath(), startdir)
424 nt.assert_equal(curpath(), startdir)
425 finally:
425 finally:
426 os.chdir(startdir)
426 os.chdir(startdir)
427
427
428
428
429 def test_xmode():
429 def test_xmode():
430 # Calling xmode three times should be a no-op
430 # Calling xmode three times should be a no-op
431 xmode = _ip.InteractiveTB.mode
431 xmode = _ip.InteractiveTB.mode
432 for i in range(3):
432 for i in range(3):
433 _ip.magic("xmode")
433 _ip.magic("xmode")
434 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
434 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
435
435
436 def test_reset_hard():
436 def test_reset_hard():
437 monitor = []
437 monitor = []
438 class A(object):
438 class A(object):
439 def __del__(self):
439 def __del__(self):
440 monitor.append(1)
440 monitor.append(1)
441 def __repr__(self):
441 def __repr__(self):
442 return "<A instance>"
442 return "<A instance>"
443
443
444 _ip.user_ns["a"] = A()
444 _ip.user_ns["a"] = A()
445 _ip.run_cell("a")
445 _ip.run_cell("a")
446
446
447 nt.assert_equal(monitor, [])
447 nt.assert_equal(monitor, [])
448 _ip.magic("reset -f")
448 _ip.magic("reset -f")
449 nt.assert_equal(monitor, [1])
449 nt.assert_equal(monitor, [1])
450
450
451 class TestXdel(tt.TempFileMixin):
451 class TestXdel(tt.TempFileMixin):
452 def test_xdel(self):
452 def test_xdel(self):
453 """Test that references from %run are cleared by xdel."""
453 """Test that references from %run are cleared by xdel."""
454 src = ("class A(object):\n"
454 src = ("class A(object):\n"
455 " monitor = []\n"
455 " monitor = []\n"
456 " def __del__(self):\n"
456 " def __del__(self):\n"
457 " self.monitor.append(1)\n"
457 " self.monitor.append(1)\n"
458 "a = A()\n")
458 "a = A()\n")
459 self.mktmp(src)
459 self.mktmp(src)
460 # %run creates some hidden references...
460 # %run creates some hidden references...
461 _ip.magic("run %s" % self.fname)
461 _ip.magic("run %s" % self.fname)
462 # ... as does the displayhook.
462 # ... as does the displayhook.
463 _ip.run_cell("a")
463 _ip.run_cell("a")
464
464
465 monitor = _ip.user_ns["A"].monitor
465 monitor = _ip.user_ns["A"].monitor
466 nt.assert_equal(monitor, [])
466 nt.assert_equal(monitor, [])
467
467
468 _ip.magic("xdel a")
468 _ip.magic("xdel a")
469
469
470 # Check that a's __del__ method has been called.
470 # Check that a's __del__ method has been called.
471 nt.assert_equal(monitor, [1])
471 nt.assert_equal(monitor, [1])
472
472
473 def doctest_who():
473 def doctest_who():
474 """doctest for %who
474 """doctest for %who
475
475
476 In [1]: %reset -f
476 In [1]: %reset -f
477
477
478 In [2]: alpha = 123
478 In [2]: alpha = 123
479
479
480 In [3]: beta = 'beta'
480 In [3]: beta = 'beta'
481
481
482 In [4]: %who int
482 In [4]: %who int
483 alpha
483 alpha
484
484
485 In [5]: %who str
485 In [5]: %who str
486 beta
486 beta
487
487
488 In [6]: %whos
488 In [6]: %whos
489 Variable Type Data/Info
489 Variable Type Data/Info
490 ----------------------------
490 ----------------------------
491 alpha int 123
491 alpha int 123
492 beta str beta
492 beta str beta
493
493
494 In [7]: %who_ls
494 In [7]: %who_ls
495 Out[7]: ['alpha', 'beta']
495 Out[7]: ['alpha', 'beta']
496 """
496 """
497
497
498 def test_whos():
498 def test_whos():
499 """Check that whos is protected against objects where repr() fails."""
499 """Check that whos is protected against objects where repr() fails."""
500 class A(object):
500 class A(object):
501 def __repr__(self):
501 def __repr__(self):
502 raise Exception()
502 raise Exception()
503 _ip.user_ns['a'] = A()
503 _ip.user_ns['a'] = A()
504 _ip.magic("whos")
504 _ip.magic("whos")
505
505
506 @py3compat.u_format
506 @py3compat.u_format
507 def doctest_precision():
507 def doctest_precision():
508 """doctest for %precision
508 """doctest for %precision
509
509
510 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
510 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
511
511
512 In [2]: %precision 5
512 In [2]: %precision 5
513 Out[2]: {u}'%.5f'
513 Out[2]: '%.5f'
514
514
515 In [3]: f.float_format
515 In [3]: f.float_format
516 Out[3]: {u}'%.5f'
516 Out[3]: '%.5f'
517
517
518 In [4]: %precision %e
518 In [4]: %precision %e
519 Out[4]: {u}'%e'
519 Out[4]: '%e'
520
520
521 In [5]: f(3.1415927)
521 In [5]: f(3.1415927)
522 Out[5]: {u}'3.141593e+00'
522 Out[5]: '3.141593e+00'
523 """
523 """
524
524
525 def test_psearch():
525 def test_psearch():
526 with tt.AssertPrints("dict.fromkeys"):
526 with tt.AssertPrints("dict.fromkeys"):
527 _ip.run_cell("dict.fr*?")
527 _ip.run_cell("dict.fr*?")
528
528
529 def test_timeit_shlex():
529 def test_timeit_shlex():
530 """test shlex issues with timeit (#1109)"""
530 """test shlex issues with timeit (#1109)"""
531 _ip.ex("def f(*a,**kw): pass")
531 _ip.ex("def f(*a,**kw): pass")
532 _ip.magic('timeit -n1 "this is a bug".count(" ")')
532 _ip.magic('timeit -n1 "this is a bug".count(" ")')
533 _ip.magic('timeit -r1 -n1 f(" ", 1)')
533 _ip.magic('timeit -r1 -n1 f(" ", 1)')
534 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
534 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
535 _ip.magic('timeit -r1 -n1 ("a " + "b")')
535 _ip.magic('timeit -r1 -n1 ("a " + "b")')
536 _ip.magic('timeit -r1 -n1 f("a " + "b")')
536 _ip.magic('timeit -r1 -n1 f("a " + "b")')
537 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
537 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
538
538
539
539
540 def test_timeit_arguments():
540 def test_timeit_arguments():
541 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
541 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
542 _ip.magic("timeit ('#')")
542 _ip.magic("timeit ('#')")
543
543
544
544
545 def test_timeit_special_syntax():
545 def test_timeit_special_syntax():
546 "Test %%timeit with IPython special syntax"
546 "Test %%timeit with IPython special syntax"
547 @register_line_magic
547 @register_line_magic
548 def lmagic(line):
548 def lmagic(line):
549 ip = get_ipython()
549 ip = get_ipython()
550 ip.user_ns['lmagic_out'] = line
550 ip.user_ns['lmagic_out'] = line
551
551
552 # line mode test
552 # line mode test
553 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
553 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
554 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
554 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
555 # cell mode test
555 # cell mode test
556 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
556 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
557 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
557 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
558
558
559 def test_timeit_return():
559 def test_timeit_return():
560 """
560 """
561 test wether timeit -o return object
561 test wether timeit -o return object
562 """
562 """
563
563
564 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
564 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
565 assert(res is not None)
565 assert(res is not None)
566
566
567 def test_timeit_quiet():
567 def test_timeit_quiet():
568 """
568 """
569 test quiet option of timeit magic
569 test quiet option of timeit magic
570 """
570 """
571 with tt.AssertNotPrints("loops"):
571 with tt.AssertNotPrints("loops"):
572 _ip.run_cell("%timeit -n1 -r1 -q 1")
572 _ip.run_cell("%timeit -n1 -r1 -q 1")
573
573
574 def test_timeit_return_quiet():
574 def test_timeit_return_quiet():
575 with tt.AssertNotPrints("loops"):
575 with tt.AssertNotPrints("loops"):
576 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
576 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
577 assert (res is not None)
577 assert (res is not None)
578
578
579 def test_timeit_invalid_return():
579 def test_timeit_invalid_return():
580 with nt.assert_raises_regexp(SyntaxError, "outside function"):
580 with nt.assert_raises_regexp(SyntaxError, "outside function"):
581 _ip.run_line_magic('timeit', 'return')
581 _ip.run_line_magic('timeit', 'return')
582
582
583 @dec.skipif(execution.profile is None)
583 @dec.skipif(execution.profile is None)
584 def test_prun_special_syntax():
584 def test_prun_special_syntax():
585 "Test %%prun with IPython special syntax"
585 "Test %%prun with IPython special syntax"
586 @register_line_magic
586 @register_line_magic
587 def lmagic(line):
587 def lmagic(line):
588 ip = get_ipython()
588 ip = get_ipython()
589 ip.user_ns['lmagic_out'] = line
589 ip.user_ns['lmagic_out'] = line
590
590
591 # line mode test
591 # line mode test
592 _ip.run_line_magic('prun', '-q %lmagic my line')
592 _ip.run_line_magic('prun', '-q %lmagic my line')
593 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
593 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
594 # cell mode test
594 # cell mode test
595 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
595 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
597
597
598 @dec.skipif(execution.profile is None)
598 @dec.skipif(execution.profile is None)
599 def test_prun_quotes():
599 def test_prun_quotes():
600 "Test that prun does not clobber string escapes (GH #1302)"
600 "Test that prun does not clobber string escapes (GH #1302)"
601 _ip.magic(r"prun -q x = '\t'")
601 _ip.magic(r"prun -q x = '\t'")
602 nt.assert_equal(_ip.user_ns['x'], '\t')
602 nt.assert_equal(_ip.user_ns['x'], '\t')
603
603
604 def test_extension():
604 def test_extension():
605 # Debugging information for failures of this test
605 # Debugging information for failures of this test
606 print('sys.path:')
606 print('sys.path:')
607 for p in sys.path:
607 for p in sys.path:
608 print(' ', p)
608 print(' ', p)
609 print('CWD', os.getcwd())
609 print('CWD', os.getcwd())
610
610
611 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
611 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
612 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
612 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
613 sys.path.insert(0, daft_path)
613 sys.path.insert(0, daft_path)
614 try:
614 try:
615 _ip.user_ns.pop('arq', None)
615 _ip.user_ns.pop('arq', None)
616 invalidate_caches() # Clear import caches
616 invalidate_caches() # Clear import caches
617 _ip.magic("load_ext daft_extension")
617 _ip.magic("load_ext daft_extension")
618 nt.assert_equal(_ip.user_ns['arq'], 185)
618 nt.assert_equal(_ip.user_ns['arq'], 185)
619 _ip.magic("unload_ext daft_extension")
619 _ip.magic("unload_ext daft_extension")
620 assert 'arq' not in _ip.user_ns
620 assert 'arq' not in _ip.user_ns
621 finally:
621 finally:
622 sys.path.remove(daft_path)
622 sys.path.remove(daft_path)
623
623
624
624
625 def test_notebook_export_json():
625 def test_notebook_export_json():
626 _ip = get_ipython()
626 _ip = get_ipython()
627 _ip.history_manager.reset() # Clear any existing history.
627 _ip.history_manager.reset() # Clear any existing history.
628 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
628 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
629 for i, cmd in enumerate(cmds, start=1):
629 for i, cmd in enumerate(cmds, start=1):
630 _ip.history_manager.store_inputs(i, cmd)
630 _ip.history_manager.store_inputs(i, cmd)
631 with TemporaryDirectory() as td:
631 with TemporaryDirectory() as td:
632 outfile = os.path.join(td, "nb.ipynb")
632 outfile = os.path.join(td, "nb.ipynb")
633 _ip.magic("notebook -e %s" % outfile)
633 _ip.magic("notebook -e %s" % outfile)
634
634
635
635
636 class TestEnv(TestCase):
636 class TestEnv(TestCase):
637
637
638 def test_env(self):
638 def test_env(self):
639 env = _ip.magic("env")
639 env = _ip.magic("env")
640 self.assertTrue(isinstance(env, dict))
640 self.assertTrue(isinstance(env, dict))
641
641
642 def test_env_get_set_simple(self):
642 def test_env_get_set_simple(self):
643 env = _ip.magic("env var val1")
643 env = _ip.magic("env var val1")
644 self.assertEqual(env, None)
644 self.assertEqual(env, None)
645 self.assertEqual(os.environ['var'], 'val1')
645 self.assertEqual(os.environ['var'], 'val1')
646 self.assertEqual(_ip.magic("env var"), 'val1')
646 self.assertEqual(_ip.magic("env var"), 'val1')
647 env = _ip.magic("env var=val2")
647 env = _ip.magic("env var=val2")
648 self.assertEqual(env, None)
648 self.assertEqual(env, None)
649 self.assertEqual(os.environ['var'], 'val2')
649 self.assertEqual(os.environ['var'], 'val2')
650
650
651 def test_env_get_set_complex(self):
651 def test_env_get_set_complex(self):
652 env = _ip.magic("env var 'val1 '' 'val2")
652 env = _ip.magic("env var 'val1 '' 'val2")
653 self.assertEqual(env, None)
653 self.assertEqual(env, None)
654 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
654 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
655 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
655 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
656 env = _ip.magic('env var=val2 val3="val4')
656 env = _ip.magic('env var=val2 val3="val4')
657 self.assertEqual(env, None)
657 self.assertEqual(env, None)
658 self.assertEqual(os.environ['var'], 'val2 val3="val4')
658 self.assertEqual(os.environ['var'], 'val2 val3="val4')
659
659
660 def test_env_set_bad_input(self):
660 def test_env_set_bad_input(self):
661 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
661 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
662
662
663 def test_env_set_whitespace(self):
663 def test_env_set_whitespace(self):
664 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
664 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
665
665
666
666
667 class CellMagicTestCase(TestCase):
667 class CellMagicTestCase(TestCase):
668
668
669 def check_ident(self, magic):
669 def check_ident(self, magic):
670 # Manually called, we get the result
670 # Manually called, we get the result
671 out = _ip.run_cell_magic(magic, 'a', 'b')
671 out = _ip.run_cell_magic(magic, 'a', 'b')
672 nt.assert_equal(out, ('a','b'))
672 nt.assert_equal(out, ('a','b'))
673 # Via run_cell, it goes into the user's namespace via displayhook
673 # Via run_cell, it goes into the user's namespace via displayhook
674 _ip.run_cell('%%' + magic +' c\nd')
674 _ip.run_cell('%%' + magic +' c\nd')
675 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
675 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
676
676
677 def test_cell_magic_func_deco(self):
677 def test_cell_magic_func_deco(self):
678 "Cell magic using simple decorator"
678 "Cell magic using simple decorator"
679 @register_cell_magic
679 @register_cell_magic
680 def cellm(line, cell):
680 def cellm(line, cell):
681 return line, cell
681 return line, cell
682
682
683 self.check_ident('cellm')
683 self.check_ident('cellm')
684
684
685 def test_cell_magic_reg(self):
685 def test_cell_magic_reg(self):
686 "Cell magic manually registered"
686 "Cell magic manually registered"
687 def cellm(line, cell):
687 def cellm(line, cell):
688 return line, cell
688 return line, cell
689
689
690 _ip.register_magic_function(cellm, 'cell', 'cellm2')
690 _ip.register_magic_function(cellm, 'cell', 'cellm2')
691 self.check_ident('cellm2')
691 self.check_ident('cellm2')
692
692
693 def test_cell_magic_class(self):
693 def test_cell_magic_class(self):
694 "Cell magics declared via a class"
694 "Cell magics declared via a class"
695 @magics_class
695 @magics_class
696 class MyMagics(Magics):
696 class MyMagics(Magics):
697
697
698 @cell_magic
698 @cell_magic
699 def cellm3(self, line, cell):
699 def cellm3(self, line, cell):
700 return line, cell
700 return line, cell
701
701
702 _ip.register_magics(MyMagics)
702 _ip.register_magics(MyMagics)
703 self.check_ident('cellm3')
703 self.check_ident('cellm3')
704
704
705 def test_cell_magic_class2(self):
705 def test_cell_magic_class2(self):
706 "Cell magics declared via a class, #2"
706 "Cell magics declared via a class, #2"
707 @magics_class
707 @magics_class
708 class MyMagics2(Magics):
708 class MyMagics2(Magics):
709
709
710 @cell_magic('cellm4')
710 @cell_magic('cellm4')
711 def cellm33(self, line, cell):
711 def cellm33(self, line, cell):
712 return line, cell
712 return line, cell
713
713
714 _ip.register_magics(MyMagics2)
714 _ip.register_magics(MyMagics2)
715 self.check_ident('cellm4')
715 self.check_ident('cellm4')
716 # Check that nothing is registered as 'cellm33'
716 # Check that nothing is registered as 'cellm33'
717 c33 = _ip.find_cell_magic('cellm33')
717 c33 = _ip.find_cell_magic('cellm33')
718 nt.assert_equal(c33, None)
718 nt.assert_equal(c33, None)
719
719
720 def test_file():
720 def test_file():
721 """Basic %%file"""
721 """Basic %%file"""
722 ip = get_ipython()
722 ip = get_ipython()
723 with TemporaryDirectory() as td:
723 with TemporaryDirectory() as td:
724 fname = os.path.join(td, 'file1')
724 fname = os.path.join(td, 'file1')
725 ip.run_cell_magic("file", fname, u'\n'.join([
725 ip.run_cell_magic("file", fname, u'\n'.join([
726 'line1',
726 'line1',
727 'line2',
727 'line2',
728 ]))
728 ]))
729 with open(fname) as f:
729 with open(fname) as f:
730 s = f.read()
730 s = f.read()
731 nt.assert_in('line1\n', s)
731 nt.assert_in('line1\n', s)
732 nt.assert_in('line2', s)
732 nt.assert_in('line2', s)
733
733
734 def test_file_var_expand():
734 def test_file_var_expand():
735 """%%file $filename"""
735 """%%file $filename"""
736 ip = get_ipython()
736 ip = get_ipython()
737 with TemporaryDirectory() as td:
737 with TemporaryDirectory() as td:
738 fname = os.path.join(td, 'file1')
738 fname = os.path.join(td, 'file1')
739 ip.user_ns['filename'] = fname
739 ip.user_ns['filename'] = fname
740 ip.run_cell_magic("file", '$filename', u'\n'.join([
740 ip.run_cell_magic("file", '$filename', u'\n'.join([
741 'line1',
741 'line1',
742 'line2',
742 'line2',
743 ]))
743 ]))
744 with open(fname) as f:
744 with open(fname) as f:
745 s = f.read()
745 s = f.read()
746 nt.assert_in('line1\n', s)
746 nt.assert_in('line1\n', s)
747 nt.assert_in('line2', s)
747 nt.assert_in('line2', s)
748
748
749 def test_file_unicode():
749 def test_file_unicode():
750 """%%file with unicode cell"""
750 """%%file with unicode cell"""
751 ip = get_ipython()
751 ip = get_ipython()
752 with TemporaryDirectory() as td:
752 with TemporaryDirectory() as td:
753 fname = os.path.join(td, 'file1')
753 fname = os.path.join(td, 'file1')
754 ip.run_cell_magic("file", fname, u'\n'.join([
754 ip.run_cell_magic("file", fname, u'\n'.join([
755 u'liné1',
755 u'liné1',
756 u'liné2',
756 u'liné2',
757 ]))
757 ]))
758 with io.open(fname, encoding='utf-8') as f:
758 with io.open(fname, encoding='utf-8') as f:
759 s = f.read()
759 s = f.read()
760 nt.assert_in(u'liné1\n', s)
760 nt.assert_in(u'liné1\n', s)
761 nt.assert_in(u'liné2', s)
761 nt.assert_in(u'liné2', s)
762
762
763 def test_file_amend():
763 def test_file_amend():
764 """%%file -a amends files"""
764 """%%file -a amends files"""
765 ip = get_ipython()
765 ip = get_ipython()
766 with TemporaryDirectory() as td:
766 with TemporaryDirectory() as td:
767 fname = os.path.join(td, 'file2')
767 fname = os.path.join(td, 'file2')
768 ip.run_cell_magic("file", fname, u'\n'.join([
768 ip.run_cell_magic("file", fname, u'\n'.join([
769 'line1',
769 'line1',
770 'line2',
770 'line2',
771 ]))
771 ]))
772 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
772 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
773 'line3',
773 'line3',
774 'line4',
774 'line4',
775 ]))
775 ]))
776 with open(fname) as f:
776 with open(fname) as f:
777 s = f.read()
777 s = f.read()
778 nt.assert_in('line1\n', s)
778 nt.assert_in('line1\n', s)
779 nt.assert_in('line3\n', s)
779 nt.assert_in('line3\n', s)
780
780
781
781
782 def test_script_config():
782 def test_script_config():
783 ip = get_ipython()
783 ip = get_ipython()
784 ip.config.ScriptMagics.script_magics = ['whoda']
784 ip.config.ScriptMagics.script_magics = ['whoda']
785 sm = script.ScriptMagics(shell=ip)
785 sm = script.ScriptMagics(shell=ip)
786 nt.assert_in('whoda', sm.magics['cell'])
786 nt.assert_in('whoda', sm.magics['cell'])
787
787
788 @dec.skip_win32
788 @dec.skip_win32
789 def test_script_out():
789 def test_script_out():
790 ip = get_ipython()
790 ip = get_ipython()
791 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
791 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
792 nt.assert_equal(ip.user_ns['output'], 'hi\n')
792 nt.assert_equal(ip.user_ns['output'], 'hi\n')
793
793
794 @dec.skip_win32
794 @dec.skip_win32
795 def test_script_err():
795 def test_script_err():
796 ip = get_ipython()
796 ip = get_ipython()
797 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
797 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
798 nt.assert_equal(ip.user_ns['error'], 'hello\n')
798 nt.assert_equal(ip.user_ns['error'], 'hello\n')
799
799
800 @dec.skip_win32
800 @dec.skip_win32
801 def test_script_out_err():
801 def test_script_out_err():
802 ip = get_ipython()
802 ip = get_ipython()
803 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
803 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
804 nt.assert_equal(ip.user_ns['output'], 'hi\n')
804 nt.assert_equal(ip.user_ns['output'], 'hi\n')
805 nt.assert_equal(ip.user_ns['error'], 'hello\n')
805 nt.assert_equal(ip.user_ns['error'], 'hello\n')
806
806
807 @dec.skip_win32
807 @dec.skip_win32
808 def test_script_bg_out():
808 def test_script_bg_out():
809 ip = get_ipython()
809 ip = get_ipython()
810 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
810 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
811 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
811 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
812
812
813 @dec.skip_win32
813 @dec.skip_win32
814 def test_script_bg_err():
814 def test_script_bg_err():
815 ip = get_ipython()
815 ip = get_ipython()
816 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
816 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
817 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
817 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
818
818
819 @dec.skip_win32
819 @dec.skip_win32
820 def test_script_bg_out_err():
820 def test_script_bg_out_err():
821 ip = get_ipython()
821 ip = get_ipython()
822 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
822 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
823 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
823 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
824 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
824 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
825
825
826 def test_script_defaults():
826 def test_script_defaults():
827 ip = get_ipython()
827 ip = get_ipython()
828 for cmd in ['sh', 'bash', 'perl', 'ruby']:
828 for cmd in ['sh', 'bash', 'perl', 'ruby']:
829 try:
829 try:
830 find_cmd(cmd)
830 find_cmd(cmd)
831 except Exception:
831 except Exception:
832 pass
832 pass
833 else:
833 else:
834 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
834 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
835
835
836
836
837 @magics_class
837 @magics_class
838 class FooFoo(Magics):
838 class FooFoo(Magics):
839 """class with both %foo and %%foo magics"""
839 """class with both %foo and %%foo magics"""
840 @line_magic('foo')
840 @line_magic('foo')
841 def line_foo(self, line):
841 def line_foo(self, line):
842 "I am line foo"
842 "I am line foo"
843 pass
843 pass
844
844
845 @cell_magic("foo")
845 @cell_magic("foo")
846 def cell_foo(self, line, cell):
846 def cell_foo(self, line, cell):
847 "I am cell foo, not line foo"
847 "I am cell foo, not line foo"
848 pass
848 pass
849
849
850 def test_line_cell_info():
850 def test_line_cell_info():
851 """%%foo and %foo magics are distinguishable to inspect"""
851 """%%foo and %foo magics are distinguishable to inspect"""
852 ip = get_ipython()
852 ip = get_ipython()
853 ip.magics_manager.register(FooFoo)
853 ip.magics_manager.register(FooFoo)
854 oinfo = ip.object_inspect('foo')
854 oinfo = ip.object_inspect('foo')
855 nt.assert_true(oinfo['found'])
855 nt.assert_true(oinfo['found'])
856 nt.assert_true(oinfo['ismagic'])
856 nt.assert_true(oinfo['ismagic'])
857
857
858 oinfo = ip.object_inspect('%%foo')
858 oinfo = ip.object_inspect('%%foo')
859 nt.assert_true(oinfo['found'])
859 nt.assert_true(oinfo['found'])
860 nt.assert_true(oinfo['ismagic'])
860 nt.assert_true(oinfo['ismagic'])
861 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
861 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
862
862
863 oinfo = ip.object_inspect('%foo')
863 oinfo = ip.object_inspect('%foo')
864 nt.assert_true(oinfo['found'])
864 nt.assert_true(oinfo['found'])
865 nt.assert_true(oinfo['ismagic'])
865 nt.assert_true(oinfo['ismagic'])
866 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
866 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
867
867
868 def test_multiple_magics():
868 def test_multiple_magics():
869 ip = get_ipython()
869 ip = get_ipython()
870 foo1 = FooFoo(ip)
870 foo1 = FooFoo(ip)
871 foo2 = FooFoo(ip)
871 foo2 = FooFoo(ip)
872 mm = ip.magics_manager
872 mm = ip.magics_manager
873 mm.register(foo1)
873 mm.register(foo1)
874 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
874 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
875 mm.register(foo2)
875 mm.register(foo2)
876 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
876 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
877
877
878 def test_alias_magic():
878 def test_alias_magic():
879 """Test %alias_magic."""
879 """Test %alias_magic."""
880 ip = get_ipython()
880 ip = get_ipython()
881 mm = ip.magics_manager
881 mm = ip.magics_manager
882
882
883 # Basic operation: both cell and line magics are created, if possible.
883 # Basic operation: both cell and line magics are created, if possible.
884 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
884 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
885 nt.assert_in('timeit_alias', mm.magics['line'])
885 nt.assert_in('timeit_alias', mm.magics['line'])
886 nt.assert_in('timeit_alias', mm.magics['cell'])
886 nt.assert_in('timeit_alias', mm.magics['cell'])
887
887
888 # --cell is specified, line magic not created.
888 # --cell is specified, line magic not created.
889 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
889 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
890 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
890 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
891 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
891 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
892
892
893 # Test that line alias is created successfully.
893 # Test that line alias is created successfully.
894 ip.run_line_magic('alias_magic', '--line env_alias env')
894 ip.run_line_magic('alias_magic', '--line env_alias env')
895 nt.assert_equal(ip.run_line_magic('env', ''),
895 nt.assert_equal(ip.run_line_magic('env', ''),
896 ip.run_line_magic('env_alias', ''))
896 ip.run_line_magic('env_alias', ''))
897
897
898 # Test that line alias with parameters passed in is created successfully.
898 # Test that line alias with parameters passed in is created successfully.
899 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
899 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
900 nt.assert_in('history_alias', mm.magics['line'])
900 nt.assert_in('history_alias', mm.magics['line'])
901
901
902
902
903 def test_save():
903 def test_save():
904 """Test %save."""
904 """Test %save."""
905 ip = get_ipython()
905 ip = get_ipython()
906 ip.history_manager.reset() # Clear any existing history.
906 ip.history_manager.reset() # Clear any existing history.
907 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
907 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
908 for i, cmd in enumerate(cmds, start=1):
908 for i, cmd in enumerate(cmds, start=1):
909 ip.history_manager.store_inputs(i, cmd)
909 ip.history_manager.store_inputs(i, cmd)
910 with TemporaryDirectory() as tmpdir:
910 with TemporaryDirectory() as tmpdir:
911 file = os.path.join(tmpdir, "testsave.py")
911 file = os.path.join(tmpdir, "testsave.py")
912 ip.run_line_magic("save", "%s 1-10" % file)
912 ip.run_line_magic("save", "%s 1-10" % file)
913 with open(file) as f:
913 with open(file) as f:
914 content = f.read()
914 content = f.read()
915 nt.assert_equal(content.count(cmds[0]), 1)
915 nt.assert_equal(content.count(cmds[0]), 1)
916 nt.assert_in('coding: utf-8', content)
916 nt.assert_in('coding: utf-8', content)
917 ip.run_line_magic("save", "-a %s 1-10" % file)
917 ip.run_line_magic("save", "-a %s 1-10" % file)
918 with open(file) as f:
918 with open(file) as f:
919 content = f.read()
919 content = f.read()
920 nt.assert_equal(content.count(cmds[0]), 2)
920 nt.assert_equal(content.count(cmds[0]), 2)
921 nt.assert_in('coding: utf-8', content)
921 nt.assert_in('coding: utf-8', content)
922
922
923
923
924 def test_store():
924 def test_store():
925 """Test %store."""
925 """Test %store."""
926 ip = get_ipython()
926 ip = get_ipython()
927 ip.run_line_magic('load_ext', 'storemagic')
927 ip.run_line_magic('load_ext', 'storemagic')
928
928
929 # make sure the storage is empty
929 # make sure the storage is empty
930 ip.run_line_magic('store', '-z')
930 ip.run_line_magic('store', '-z')
931 ip.user_ns['var'] = 42
931 ip.user_ns['var'] = 42
932 ip.run_line_magic('store', 'var')
932 ip.run_line_magic('store', 'var')
933 ip.user_ns['var'] = 39
933 ip.user_ns['var'] = 39
934 ip.run_line_magic('store', '-r')
934 ip.run_line_magic('store', '-r')
935 nt.assert_equal(ip.user_ns['var'], 42)
935 nt.assert_equal(ip.user_ns['var'], 42)
936
936
937 ip.run_line_magic('store', '-d var')
937 ip.run_line_magic('store', '-d var')
938 ip.user_ns['var'] = 39
938 ip.user_ns['var'] = 39
939 ip.run_line_magic('store' , '-r')
939 ip.run_line_magic('store' , '-r')
940 nt.assert_equal(ip.user_ns['var'], 39)
940 nt.assert_equal(ip.user_ns['var'], 39)
941
941
942
942
943 def _run_edit_test(arg_s, exp_filename=None,
943 def _run_edit_test(arg_s, exp_filename=None,
944 exp_lineno=-1,
944 exp_lineno=-1,
945 exp_contents=None,
945 exp_contents=None,
946 exp_is_temp=None):
946 exp_is_temp=None):
947 ip = get_ipython()
947 ip = get_ipython()
948 M = code.CodeMagics(ip)
948 M = code.CodeMagics(ip)
949 last_call = ['','']
949 last_call = ['','']
950 opts,args = M.parse_options(arg_s,'prxn:')
950 opts,args = M.parse_options(arg_s,'prxn:')
951 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
951 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
952
952
953 if exp_filename is not None:
953 if exp_filename is not None:
954 nt.assert_equal(exp_filename, filename)
954 nt.assert_equal(exp_filename, filename)
955 if exp_contents is not None:
955 if exp_contents is not None:
956 with io.open(filename, 'r', encoding='utf-8') as f:
956 with io.open(filename, 'r', encoding='utf-8') as f:
957 contents = f.read()
957 contents = f.read()
958 nt.assert_equal(exp_contents, contents)
958 nt.assert_equal(exp_contents, contents)
959 if exp_lineno != -1:
959 if exp_lineno != -1:
960 nt.assert_equal(exp_lineno, lineno)
960 nt.assert_equal(exp_lineno, lineno)
961 if exp_is_temp is not None:
961 if exp_is_temp is not None:
962 nt.assert_equal(exp_is_temp, is_temp)
962 nt.assert_equal(exp_is_temp, is_temp)
963
963
964
964
965 def test_edit_interactive():
965 def test_edit_interactive():
966 """%edit on interactively defined objects"""
966 """%edit on interactively defined objects"""
967 ip = get_ipython()
967 ip = get_ipython()
968 n = ip.execution_count
968 n = ip.execution_count
969 ip.run_cell(u"def foo(): return 1", store_history=True)
969 ip.run_cell(u"def foo(): return 1", store_history=True)
970
970
971 try:
971 try:
972 _run_edit_test("foo")
972 _run_edit_test("foo")
973 except code.InteractivelyDefined as e:
973 except code.InteractivelyDefined as e:
974 nt.assert_equal(e.index, n)
974 nt.assert_equal(e.index, n)
975 else:
975 else:
976 raise AssertionError("Should have raised InteractivelyDefined")
976 raise AssertionError("Should have raised InteractivelyDefined")
977
977
978
978
979 def test_edit_cell():
979 def test_edit_cell():
980 """%edit [cell id]"""
980 """%edit [cell id]"""
981 ip = get_ipython()
981 ip = get_ipython()
982
982
983 ip.run_cell(u"def foo(): return 1", store_history=True)
983 ip.run_cell(u"def foo(): return 1", store_history=True)
984
984
985 # test
985 # test
986 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
986 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
987
987
988 def test_bookmark():
988 def test_bookmark():
989 ip = get_ipython()
989 ip = get_ipython()
990 ip.run_line_magic('bookmark', 'bmname')
990 ip.run_line_magic('bookmark', 'bmname')
991 with tt.AssertPrints('bmname'):
991 with tt.AssertPrints('bmname'):
992 ip.run_line_magic('bookmark', '-l')
992 ip.run_line_magic('bookmark', '-l')
993 ip.run_line_magic('bookmark', '-d bmname')
993 ip.run_line_magic('bookmark', '-d bmname')
994
994
995 def test_ls_magic():
995 def test_ls_magic():
996 ip = get_ipython()
996 ip = get_ipython()
997 json_formatter = ip.display_formatter.formatters['application/json']
997 json_formatter = ip.display_formatter.formatters['application/json']
998 json_formatter.enabled = True
998 json_formatter.enabled = True
999 lsmagic = ip.magic('lsmagic')
999 lsmagic = ip.magic('lsmagic')
1000 with warnings.catch_warnings(record=True) as w:
1000 with warnings.catch_warnings(record=True) as w:
1001 j = json_formatter(lsmagic)
1001 j = json_formatter(lsmagic)
1002 nt.assert_equal(sorted(j), ['cell', 'line'])
1002 nt.assert_equal(sorted(j), ['cell', 'line'])
1003 nt.assert_equal(w, []) # no warnings
1003 nt.assert_equal(w, []) # no warnings
1004
1004
1005 def test_strip_initial_indent():
1005 def test_strip_initial_indent():
1006 def sii(s):
1006 def sii(s):
1007 lines = s.splitlines()
1007 lines = s.splitlines()
1008 return '\n'.join(code.strip_initial_indent(lines))
1008 return '\n'.join(code.strip_initial_indent(lines))
1009
1009
1010 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1010 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1011 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1011 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1012 nt.assert_equal(sii("a\n b"), "a\n b")
1012 nt.assert_equal(sii("a\n b"), "a\n b")
1013
1013
1014 def test_logging_magic_quiet_from_arg():
1014 def test_logging_magic_quiet_from_arg():
1015 _ip.config.LoggingMagics.quiet = False
1015 _ip.config.LoggingMagics.quiet = False
1016 lm = logging.LoggingMagics(shell=_ip)
1016 lm = logging.LoggingMagics(shell=_ip)
1017 with TemporaryDirectory() as td:
1017 with TemporaryDirectory() as td:
1018 try:
1018 try:
1019 with tt.AssertNotPrints(re.compile("Activating.*")):
1019 with tt.AssertNotPrints(re.compile("Activating.*")):
1020 lm.logstart('-q {}'.format(
1020 lm.logstart('-q {}'.format(
1021 os.path.join(td, "quiet_from_arg.log")))
1021 os.path.join(td, "quiet_from_arg.log")))
1022 finally:
1022 finally:
1023 _ip.logger.logstop()
1023 _ip.logger.logstop()
1024
1024
1025 def test_logging_magic_quiet_from_config():
1025 def test_logging_magic_quiet_from_config():
1026 _ip.config.LoggingMagics.quiet = True
1026 _ip.config.LoggingMagics.quiet = True
1027 lm = logging.LoggingMagics(shell=_ip)
1027 lm = logging.LoggingMagics(shell=_ip)
1028 with TemporaryDirectory() as td:
1028 with TemporaryDirectory() as td:
1029 try:
1029 try:
1030 with tt.AssertNotPrints(re.compile("Activating.*")):
1030 with tt.AssertNotPrints(re.compile("Activating.*")):
1031 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1031 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1032 finally:
1032 finally:
1033 _ip.logger.logstop()
1033 _ip.logger.logstop()
1034
1034
1035 def test_logging_magic_not_quiet():
1035 def test_logging_magic_not_quiet():
1036 _ip.config.LoggingMagics.quiet = False
1036 _ip.config.LoggingMagics.quiet = False
1037 lm = logging.LoggingMagics(shell=_ip)
1037 lm = logging.LoggingMagics(shell=_ip)
1038 with TemporaryDirectory() as td:
1038 with TemporaryDirectory() as td:
1039 try:
1039 try:
1040 with tt.AssertPrints(re.compile("Activating.*")):
1040 with tt.AssertPrints(re.compile("Activating.*")):
1041 lm.logstart(os.path.join(td, "not_quiet.log"))
1041 lm.logstart(os.path.join(td, "not_quiet.log"))
1042 finally:
1042 finally:
1043 _ip.logger.logstop()
1043 _ip.logger.logstop()
1044
1044
General Comments 0
You need to be logged in to leave comments. Login now