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