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