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