Show More
@@ -1,3220 +1,3212 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 __future__ |
|
14 | import __future__ | |
15 | import abc |
|
15 | import abc | |
16 | import ast |
|
16 | import ast | |
17 | import atexit |
|
17 | import atexit | |
18 | import functools |
|
18 | import functools | |
19 | import os |
|
19 | import os | |
20 | import re |
|
20 | import re | |
21 | import runpy |
|
21 | import runpy | |
22 | import sys |
|
22 | import sys | |
23 | import tempfile |
|
23 | import tempfile | |
24 | import traceback |
|
24 | import traceback | |
25 | import types |
|
25 | import types | |
26 | import subprocess |
|
26 | import subprocess | |
27 | import warnings |
|
27 | import warnings | |
28 | from io import open as io_open |
|
28 | from io import open as io_open | |
29 |
|
29 | |||
30 | from pickleshare import PickleShareDB |
|
30 | from pickleshare import PickleShareDB | |
31 |
|
31 | |||
32 | from traitlets.config.configurable import SingletonConfigurable |
|
32 | from traitlets.config.configurable import SingletonConfigurable | |
33 | from IPython.core import oinspect |
|
33 | from IPython.core import oinspect | |
34 | from IPython.core import magic |
|
34 | from IPython.core import magic | |
35 | from IPython.core import page |
|
35 | from IPython.core import page | |
36 | from IPython.core import prefilter |
|
36 | from IPython.core import prefilter | |
37 | from IPython.core import shadowns |
|
37 | from IPython.core import shadowns | |
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core.alias import Alias, AliasManager |
|
39 | from IPython.core.alias import Alias, AliasManager | |
40 | from IPython.core.autocall import ExitAutocall |
|
40 | from IPython.core.autocall import ExitAutocall | |
41 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | from IPython.core.builtin_trap import BuiltinTrap | |
42 | from IPython.core.events import EventManager, available_events |
|
42 | from IPython.core.events import EventManager, available_events | |
43 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
43 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython | |
44 | from IPython.core.debugger import Pdb |
|
44 | from IPython.core.debugger import Pdb | |
45 | from IPython.core.display_trap import DisplayTrap |
|
45 | from IPython.core.display_trap import DisplayTrap | |
46 | from IPython.core.displayhook import DisplayHook |
|
46 | from IPython.core.displayhook import DisplayHook | |
47 | from IPython.core.displaypub import DisplayPublisher |
|
47 | from IPython.core.displaypub import DisplayPublisher | |
48 | from IPython.core.error import InputRejected, UsageError |
|
48 | from IPython.core.error import InputRejected, UsageError | |
49 | from IPython.core.extensions import ExtensionManager |
|
49 | from IPython.core.extensions import ExtensionManager | |
50 | from IPython.core.formatters import DisplayFormatter |
|
50 | from IPython.core.formatters import DisplayFormatter | |
51 | from IPython.core.history import HistoryManager |
|
51 | from IPython.core.history import HistoryManager | |
52 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
52 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 | |
53 | from IPython.core.logger import Logger |
|
53 | from IPython.core.logger import Logger | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core.payload import PayloadManager |
|
55 | from IPython.core.payload import PayloadManager | |
56 | from IPython.core.prefilter import PrefilterManager |
|
56 | from IPython.core.prefilter import PrefilterManager | |
57 | from IPython.core.profiledir import ProfileDir |
|
57 | from IPython.core.profiledir import ProfileDir | |
58 | from IPython.core.usage import default_banner |
|
58 | from IPython.core.usage import default_banner | |
59 | from IPython.testing.skipdoctest import skip_doctest |
|
59 | from IPython.testing.skipdoctest import skip_doctest | |
60 | from IPython.utils import PyColorize |
|
60 | from IPython.utils import PyColorize | |
61 | from IPython.utils import io |
|
61 | from IPython.utils import io | |
62 | from IPython.utils import py3compat |
|
62 | from IPython.utils import py3compat | |
63 | from IPython.utils import openpy |
|
63 | from IPython.utils import openpy | |
64 | from IPython.utils.decorators import undoc |
|
64 | from IPython.utils.decorators import undoc | |
65 | from IPython.utils.io import ask_yes_no |
|
65 | from IPython.utils.io import ask_yes_no | |
66 | from IPython.utils.ipstruct import Struct |
|
66 | from IPython.utils.ipstruct import Struct | |
67 | from IPython.paths import get_ipython_dir |
|
67 | from IPython.paths import get_ipython_dir | |
68 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
68 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists | |
69 | from IPython.utils.process import system, getoutput |
|
69 | from IPython.utils.process import system, getoutput | |
70 | from IPython.utils.py3compat import builtin_mod |
|
70 | from IPython.utils.py3compat import builtin_mod | |
71 | from IPython.utils.strdispatch import StrDispatch |
|
71 | from IPython.utils.strdispatch import StrDispatch | |
72 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
72 | from IPython.utils.syspathcontext import prepended_to_syspath | |
73 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter |
|
73 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter | |
74 | from IPython.utils.tempdir import TemporaryDirectory |
|
74 | from IPython.utils.tempdir import TemporaryDirectory | |
75 | from traitlets import ( |
|
75 | from traitlets import ( | |
76 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
76 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, | |
77 | observe, default, |
|
77 | observe, default, | |
78 | ) |
|
78 | ) | |
79 | from warnings import warn |
|
79 | from warnings import warn | |
80 | from logging import error |
|
80 | from logging import error | |
81 | import IPython.core.hooks |
|
81 | import IPython.core.hooks | |
82 |
|
82 | |||
83 | # NoOpContext is deprecated, but ipykernel imports it from here. |
|
83 | # NoOpContext is deprecated, but ipykernel imports it from here. | |
84 | # See https://github.com/ipython/ipykernel/issues/157 |
|
84 | # See https://github.com/ipython/ipykernel/issues/157 | |
85 | from IPython.utils.contexts import NoOpContext |
|
85 | from IPython.utils.contexts import NoOpContext | |
86 |
|
86 | |||
87 | try: |
|
87 | try: | |
88 | import docrepr.sphinxify as sphx |
|
88 | import docrepr.sphinxify as sphx | |
89 |
|
89 | |||
90 | def sphinxify(doc): |
|
90 | def sphinxify(doc): | |
91 | with TemporaryDirectory() as dirname: |
|
91 | with TemporaryDirectory() as dirname: | |
92 | return { |
|
92 | return { | |
93 | 'text/html': sphx.sphinxify(doc, dirname), |
|
93 | 'text/html': sphx.sphinxify(doc, dirname), | |
94 | 'text/plain': doc |
|
94 | 'text/plain': doc | |
95 | } |
|
95 | } | |
96 | except ImportError: |
|
96 | except ImportError: | |
97 | sphinxify = None |
|
97 | sphinxify = None | |
98 |
|
98 | |||
99 |
|
99 | |||
100 | class ProvisionalWarning(DeprecationWarning): |
|
100 | class ProvisionalWarning(DeprecationWarning): | |
101 | """ |
|
101 | """ | |
102 | Warning class for unstable features |
|
102 | Warning class for unstable features | |
103 | """ |
|
103 | """ | |
104 | pass |
|
104 | pass | |
105 |
|
105 | |||
106 | #----------------------------------------------------------------------------- |
|
106 | #----------------------------------------------------------------------------- | |
107 | # Globals |
|
107 | # Globals | |
108 | #----------------------------------------------------------------------------- |
|
108 | #----------------------------------------------------------------------------- | |
109 |
|
109 | |||
110 | # compiled regexps for autoindent management |
|
110 | # compiled regexps for autoindent management | |
111 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
111 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
112 |
|
112 | |||
113 | #----------------------------------------------------------------------------- |
|
113 | #----------------------------------------------------------------------------- | |
114 | # Utilities |
|
114 | # Utilities | |
115 | #----------------------------------------------------------------------------- |
|
115 | #----------------------------------------------------------------------------- | |
116 |
|
116 | |||
117 | @undoc |
|
117 | @undoc | |
118 | def softspace(file, newvalue): |
|
118 | def softspace(file, newvalue): | |
119 | """Copied from code.py, to remove the dependency""" |
|
119 | """Copied from code.py, to remove the dependency""" | |
120 |
|
120 | |||
121 | oldvalue = 0 |
|
121 | oldvalue = 0 | |
122 | try: |
|
122 | try: | |
123 | oldvalue = file.softspace |
|
123 | oldvalue = file.softspace | |
124 | except AttributeError: |
|
124 | except AttributeError: | |
125 | pass |
|
125 | pass | |
126 | try: |
|
126 | try: | |
127 | file.softspace = newvalue |
|
127 | file.softspace = newvalue | |
128 | except (AttributeError, TypeError): |
|
128 | except (AttributeError, TypeError): | |
129 | # "attribute-less object" or "read-only attributes" |
|
129 | # "attribute-less object" or "read-only attributes" | |
130 | pass |
|
130 | pass | |
131 | return oldvalue |
|
131 | return oldvalue | |
132 |
|
132 | |||
133 | @undoc |
|
133 | @undoc | |
134 | def no_op(*a, **kw): pass |
|
134 | def no_op(*a, **kw): pass | |
135 |
|
135 | |||
136 |
|
136 | |||
137 | class SpaceInInput(Exception): pass |
|
137 | class SpaceInInput(Exception): pass | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | def get_default_colors(): |
|
140 | def get_default_colors(): | |
141 | "DEPRECATED" |
|
141 | "DEPRECATED" | |
142 | warn('get_default_color is Deprecated, and is `Neutral` on all platforms.', |
|
142 | warn('get_default_color is Deprecated, and is `Neutral` on all platforms.', | |
143 | DeprecationWarning, stacklevel=2) |
|
143 | DeprecationWarning, stacklevel=2) | |
144 | return 'Neutral' |
|
144 | return 'Neutral' | |
145 |
|
145 | |||
146 |
|
146 | |||
147 | class SeparateUnicode(Unicode): |
|
147 | class SeparateUnicode(Unicode): | |
148 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
148 | r"""A Unicode subclass to validate separate_in, separate_out, etc. | |
149 |
|
149 | |||
150 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
150 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. | |
151 | """ |
|
151 | """ | |
152 |
|
152 | |||
153 | def validate(self, obj, value): |
|
153 | def validate(self, obj, value): | |
154 | if value == '0': value = '' |
|
154 | if value == '0': value = '' | |
155 | value = value.replace('\\n','\n') |
|
155 | value = value.replace('\\n','\n') | |
156 | return super(SeparateUnicode, self).validate(obj, value) |
|
156 | return super(SeparateUnicode, self).validate(obj, value) | |
157 |
|
157 | |||
158 |
|
158 | |||
159 | @undoc |
|
159 | @undoc | |
160 | class DummyMod(object): |
|
160 | class DummyMod(object): | |
161 | """A dummy module used for IPython's interactive module when |
|
161 | """A dummy module used for IPython's interactive module when | |
162 | a namespace must be assigned to the module's __dict__.""" |
|
162 | a namespace must be assigned to the module's __dict__.""" | |
163 | pass |
|
163 | pass | |
164 |
|
164 | |||
165 |
|
165 | |||
166 | class ExecutionResult(object): |
|
166 | class ExecutionResult(object): | |
167 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
167 | """The result of a call to :meth:`InteractiveShell.run_cell` | |
168 |
|
168 | |||
169 | Stores information about what took place. |
|
169 | Stores information about what took place. | |
170 | """ |
|
170 | """ | |
171 | execution_count = None |
|
171 | execution_count = None | |
172 | error_before_exec = None |
|
172 | error_before_exec = None | |
173 | error_in_exec = None |
|
173 | error_in_exec = None | |
174 | result = None |
|
174 | result = None | |
175 |
|
175 | |||
176 | @property |
|
176 | @property | |
177 | def success(self): |
|
177 | def success(self): | |
178 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
178 | return (self.error_before_exec is None) and (self.error_in_exec is None) | |
179 |
|
179 | |||
180 | def raise_error(self): |
|
180 | def raise_error(self): | |
181 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
181 | """Reraises error if `success` is `False`, otherwise does nothing""" | |
182 | if self.error_before_exec is not None: |
|
182 | if self.error_before_exec is not None: | |
183 | raise self.error_before_exec |
|
183 | raise self.error_before_exec | |
184 | if self.error_in_exec is not None: |
|
184 | if self.error_in_exec is not None: | |
185 | raise self.error_in_exec |
|
185 | raise self.error_in_exec | |
186 |
|
186 | |||
187 | def __repr__(self): |
|
187 | def __repr__(self): | |
188 | name = self.__class__.__qualname__ |
|
188 | name = self.__class__.__qualname__ | |
189 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ |
|
189 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ | |
190 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) |
|
190 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) | |
191 |
|
191 | |||
192 |
|
192 | |||
193 | class InteractiveShell(SingletonConfigurable): |
|
193 | class InteractiveShell(SingletonConfigurable): | |
194 | """An enhanced, interactive shell for Python.""" |
|
194 | """An enhanced, interactive shell for Python.""" | |
195 |
|
195 | |||
196 | _instance = None |
|
196 | _instance = None | |
197 |
|
197 | |||
198 | ast_transformers = List([], help= |
|
198 | ast_transformers = List([], help= | |
199 | """ |
|
199 | """ | |
200 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
200 | A list of ast.NodeTransformer subclass instances, which will be applied | |
201 | to user input before code is run. |
|
201 | to user input before code is run. | |
202 | """ |
|
202 | """ | |
203 | ).tag(config=True) |
|
203 | ).tag(config=True) | |
204 |
|
204 | |||
205 | autocall = Enum((0,1,2), default_value=0, help= |
|
205 | autocall = Enum((0,1,2), default_value=0, help= | |
206 | """ |
|
206 | """ | |
207 | Make IPython automatically call any callable object even if you didn't |
|
207 | Make IPython automatically call any callable object even if you didn't | |
208 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
208 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
209 | automatically. The value can be '0' to disable the feature, '1' for |
|
209 | automatically. The value can be '0' to disable the feature, '1' for | |
210 | 'smart' autocall, where it is not applied if there are no more |
|
210 | 'smart' autocall, where it is not applied if there are no more | |
211 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
211 | arguments on the line, and '2' for 'full' autocall, where all callable | |
212 | objects are automatically called (even if no arguments are present). |
|
212 | objects are automatically called (even if no arguments are present). | |
213 | """ |
|
213 | """ | |
214 | ).tag(config=True) |
|
214 | ).tag(config=True) | |
215 | # TODO: remove all autoindent logic and put into frontends. |
|
215 | # TODO: remove all autoindent logic and put into frontends. | |
216 | # We can't do this yet because even runlines uses the autoindent. |
|
216 | # We can't do this yet because even runlines uses the autoindent. | |
217 | autoindent = Bool(True, help= |
|
217 | autoindent = Bool(True, help= | |
218 | """ |
|
218 | """ | |
219 | Autoindent IPython code entered interactively. |
|
219 | Autoindent IPython code entered interactively. | |
220 | """ |
|
220 | """ | |
221 | ).tag(config=True) |
|
221 | ).tag(config=True) | |
222 |
|
222 | |||
223 | automagic = Bool(True, help= |
|
223 | automagic = Bool(True, help= | |
224 | """ |
|
224 | """ | |
225 | Enable magic commands to be called without the leading %. |
|
225 | Enable magic commands to be called without the leading %. | |
226 | """ |
|
226 | """ | |
227 | ).tag(config=True) |
|
227 | ).tag(config=True) | |
228 |
|
228 | |||
229 | banner1 = Unicode(default_banner, |
|
229 | banner1 = Unicode(default_banner, | |
230 | help="""The part of the banner to be printed before the profile""" |
|
230 | help="""The part of the banner to be printed before the profile""" | |
231 | ).tag(config=True) |
|
231 | ).tag(config=True) | |
232 | banner2 = Unicode('', |
|
232 | banner2 = Unicode('', | |
233 | help="""The part of the banner to be printed after the profile""" |
|
233 | help="""The part of the banner to be printed after the profile""" | |
234 | ).tag(config=True) |
|
234 | ).tag(config=True) | |
235 |
|
235 | |||
236 | cache_size = Integer(1000, help= |
|
236 | cache_size = Integer(1000, help= | |
237 | """ |
|
237 | """ | |
238 | Set the size of the output cache. The default is 1000, you can |
|
238 | Set the size of the output cache. The default is 1000, you can | |
239 | change it permanently in your config file. Setting it to 0 completely |
|
239 | change it permanently in your config file. Setting it to 0 completely | |
240 | disables the caching system, and the minimum value accepted is 20 (if |
|
240 | disables the caching system, and the minimum value accepted is 20 (if | |
241 | you provide a value less than 20, it is reset to 0 and a warning is |
|
241 | you provide a value less than 20, it is reset to 0 and a warning is | |
242 | issued). This limit is defined because otherwise you'll spend more |
|
242 | issued). This limit is defined because otherwise you'll spend more | |
243 | time re-flushing a too small cache than working |
|
243 | time re-flushing a too small cache than working | |
244 | """ |
|
244 | """ | |
245 | ).tag(config=True) |
|
245 | ).tag(config=True) | |
246 | color_info = Bool(True, help= |
|
246 | color_info = Bool(True, help= | |
247 | """ |
|
247 | """ | |
248 | Use colors for displaying information about objects. Because this |
|
248 | Use colors for displaying information about objects. Because this | |
249 | information is passed through a pager (like 'less'), and some pagers |
|
249 | information is passed through a pager (like 'less'), and some pagers | |
250 | get confused with color codes, this capability can be turned off. |
|
250 | get confused with color codes, this capability can be turned off. | |
251 | """ |
|
251 | """ | |
252 | ).tag(config=True) |
|
252 | ).tag(config=True) | |
253 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), |
|
253 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), | |
254 | default_value='Neutral', |
|
254 | default_value='Neutral', | |
255 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." |
|
255 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." | |
256 | ).tag(config=True) |
|
256 | ).tag(config=True) | |
257 | debug = Bool(False).tag(config=True) |
|
257 | debug = Bool(False).tag(config=True) | |
258 | disable_failing_post_execute = Bool(False, |
|
258 | disable_failing_post_execute = Bool(False, | |
259 | help="Don't call post-execute functions that have failed in the past." |
|
259 | help="Don't call post-execute functions that have failed in the past." | |
260 | ).tag(config=True) |
|
260 | ).tag(config=True) | |
261 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
261 | display_formatter = Instance(DisplayFormatter, allow_none=True) | |
262 | displayhook_class = Type(DisplayHook) |
|
262 | displayhook_class = Type(DisplayHook) | |
263 | display_pub_class = Type(DisplayPublisher) |
|
263 | display_pub_class = Type(DisplayPublisher) | |
264 |
|
264 | |||
265 | sphinxify_docstring = Bool(False, help= |
|
265 | sphinxify_docstring = Bool(False, help= | |
266 | """ |
|
266 | """ | |
267 | Enables rich html representation of docstrings. (This requires the |
|
267 | Enables rich html representation of docstrings. (This requires the | |
268 | docrepr module). |
|
268 | docrepr module). | |
269 | """).tag(config=True) |
|
269 | """).tag(config=True) | |
270 |
|
270 | |||
271 | @observe("sphinxify_docstring") |
|
271 | @observe("sphinxify_docstring") | |
272 | def _sphinxify_docstring_changed(self, change): |
|
272 | def _sphinxify_docstring_changed(self, change): | |
273 | if change['new']: |
|
273 | if change['new']: | |
274 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) |
|
274 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) | |
275 |
|
275 | |||
276 | enable_html_pager = Bool(False, help= |
|
276 | enable_html_pager = Bool(False, help= | |
277 | """ |
|
277 | """ | |
278 | (Provisional API) enables html representation in mime bundles sent |
|
278 | (Provisional API) enables html representation in mime bundles sent | |
279 | to pagers. |
|
279 | to pagers. | |
280 | """).tag(config=True) |
|
280 | """).tag(config=True) | |
281 |
|
281 | |||
282 | @observe("enable_html_pager") |
|
282 | @observe("enable_html_pager") | |
283 | def _enable_html_pager_changed(self, change): |
|
283 | def _enable_html_pager_changed(self, change): | |
284 | if change['new']: |
|
284 | if change['new']: | |
285 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) |
|
285 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) | |
286 |
|
286 | |||
287 | data_pub_class = None |
|
287 | data_pub_class = None | |
288 |
|
288 | |||
289 | exit_now = Bool(False) |
|
289 | exit_now = Bool(False) | |
290 | exiter = Instance(ExitAutocall) |
|
290 | exiter = Instance(ExitAutocall) | |
291 | @default('exiter') |
|
291 | @default('exiter') | |
292 | def _exiter_default(self): |
|
292 | def _exiter_default(self): | |
293 | return ExitAutocall(self) |
|
293 | return ExitAutocall(self) | |
294 | # Monotonically increasing execution counter |
|
294 | # Monotonically increasing execution counter | |
295 | execution_count = Integer(1) |
|
295 | execution_count = Integer(1) | |
296 | filename = Unicode("<ipython console>") |
|
296 | filename = Unicode("<ipython console>") | |
297 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
297 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ | |
298 |
|
298 | |||
299 | # Input splitter, to transform input line by line and detect when a block |
|
299 | # Input splitter, to transform input line by line and detect when a block | |
300 | # is ready to be executed. |
|
300 | # is ready to be executed. | |
301 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
301 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
302 | (), {'line_input_checker': True}) |
|
302 | (), {'line_input_checker': True}) | |
303 |
|
303 | |||
304 | # This InputSplitter instance is used to transform completed cells before |
|
304 | # This InputSplitter instance is used to transform completed cells before | |
305 | # running them. It allows cell magics to contain blank lines. |
|
305 | # running them. It allows cell magics to contain blank lines. | |
306 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
306 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
307 | (), {'line_input_checker': False}) |
|
307 | (), {'line_input_checker': False}) | |
308 |
|
308 | |||
309 | logstart = Bool(False, help= |
|
309 | logstart = Bool(False, help= | |
310 | """ |
|
310 | """ | |
311 | Start logging to the default log file in overwrite mode. |
|
311 | Start logging to the default log file in overwrite mode. | |
312 | Use `logappend` to specify a log file to **append** logs to. |
|
312 | Use `logappend` to specify a log file to **append** logs to. | |
313 | """ |
|
313 | """ | |
314 | ).tag(config=True) |
|
314 | ).tag(config=True) | |
315 | logfile = Unicode('', help= |
|
315 | logfile = Unicode('', help= | |
316 | """ |
|
316 | """ | |
317 | The name of the logfile to use. |
|
317 | The name of the logfile to use. | |
318 | """ |
|
318 | """ | |
319 | ).tag(config=True) |
|
319 | ).tag(config=True) | |
320 | logappend = Unicode('', help= |
|
320 | logappend = Unicode('', help= | |
321 | """ |
|
321 | """ | |
322 | Start logging to the given file in append mode. |
|
322 | Start logging to the given file in append mode. | |
323 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
323 | Use `logfile` to specify a log file to **overwrite** logs to. | |
324 | """ |
|
324 | """ | |
325 | ).tag(config=True) |
|
325 | ).tag(config=True) | |
326 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
326 | object_info_string_level = Enum((0,1,2), default_value=0, | |
327 | ).tag(config=True) |
|
327 | ).tag(config=True) | |
328 | pdb = Bool(False, help= |
|
328 | pdb = Bool(False, help= | |
329 | """ |
|
329 | """ | |
330 | Automatically call the pdb debugger after every exception. |
|
330 | Automatically call the pdb debugger after every exception. | |
331 | """ |
|
331 | """ | |
332 | ).tag(config=True) |
|
332 | ).tag(config=True) | |
333 | display_page = Bool(False, |
|
333 | display_page = Bool(False, | |
334 | help="""If True, anything that would be passed to the pager |
|
334 | help="""If True, anything that would be passed to the pager | |
335 | will be displayed as regular output instead.""" |
|
335 | will be displayed as regular output instead.""" | |
336 | ).tag(config=True) |
|
336 | ).tag(config=True) | |
337 |
|
337 | |||
338 | # deprecated prompt traits: |
|
338 | # deprecated prompt traits: | |
339 |
|
339 | |||
340 | prompt_in1 = Unicode('In [\\#]: ', |
|
340 | prompt_in1 = Unicode('In [\\#]: ', | |
341 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
341 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
342 | ).tag(config=True) |
|
342 | ).tag(config=True) | |
343 | prompt_in2 = Unicode(' .\\D.: ', |
|
343 | prompt_in2 = Unicode(' .\\D.: ', | |
344 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
344 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
345 | ).tag(config=True) |
|
345 | ).tag(config=True) | |
346 | prompt_out = Unicode('Out[\\#]: ', |
|
346 | prompt_out = Unicode('Out[\\#]: ', | |
347 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
347 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
348 | ).tag(config=True) |
|
348 | ).tag(config=True) | |
349 | prompts_pad_left = Bool(True, |
|
349 | prompts_pad_left = Bool(True, | |
350 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
350 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
351 | ).tag(config=True) |
|
351 | ).tag(config=True) | |
352 |
|
352 | |||
353 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
353 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') | |
354 | def _prompt_trait_changed(self, change): |
|
354 | def _prompt_trait_changed(self, change): | |
355 | name = change['name'] |
|
355 | name = change['name'] | |
356 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" |
|
356 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" | |
357 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" |
|
357 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" | |
358 | " object directly.".format(name=name)) |
|
358 | " object directly.".format(name=name)) | |
359 |
|
359 | |||
360 | # protect against weird cases where self.config may not exist: |
|
360 | # protect against weird cases where self.config may not exist: | |
361 |
|
361 | |||
362 | show_rewritten_input = Bool(True, |
|
362 | show_rewritten_input = Bool(True, | |
363 | help="Show rewritten input, e.g. for autocall." |
|
363 | help="Show rewritten input, e.g. for autocall." | |
364 | ).tag(config=True) |
|
364 | ).tag(config=True) | |
365 |
|
365 | |||
366 | quiet = Bool(False).tag(config=True) |
|
366 | quiet = Bool(False).tag(config=True) | |
367 |
|
367 | |||
368 | history_length = Integer(10000, |
|
368 | history_length = Integer(10000, | |
369 | help='Total length of command history' |
|
369 | help='Total length of command history' | |
370 | ).tag(config=True) |
|
370 | ).tag(config=True) | |
371 |
|
371 | |||
372 | history_load_length = Integer(1000, help= |
|
372 | history_load_length = Integer(1000, help= | |
373 | """ |
|
373 | """ | |
374 | The number of saved history entries to be loaded |
|
374 | The number of saved history entries to be loaded | |
375 | into the history buffer at startup. |
|
375 | into the history buffer at startup. | |
376 | """ |
|
376 | """ | |
377 | ).tag(config=True) |
|
377 | ).tag(config=True) | |
378 |
|
378 | |||
379 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
379 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], | |
380 | default_value='last_expr', |
|
380 | default_value='last_expr', | |
381 | help=""" |
|
381 | help=""" | |
382 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
382 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
383 | run interactively (displaying output from expressions).""" |
|
383 | run interactively (displaying output from expressions).""" | |
384 | ).tag(config=True) |
|
384 | ).tag(config=True) | |
385 |
|
385 | |||
386 | # TODO: this part of prompt management should be moved to the frontends. |
|
386 | # TODO: this part of prompt management should be moved to the frontends. | |
387 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
387 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
388 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
388 | separate_in = SeparateUnicode('\n').tag(config=True) | |
389 | separate_out = SeparateUnicode('').tag(config=True) |
|
389 | separate_out = SeparateUnicode('').tag(config=True) | |
390 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
390 | separate_out2 = SeparateUnicode('').tag(config=True) | |
391 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
391 | wildcards_case_sensitive = Bool(True).tag(config=True) | |
392 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
392 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
393 | default_value='Context').tag(config=True) |
|
393 | default_value='Context').tag(config=True) | |
394 |
|
394 | |||
395 | # Subcomponents of InteractiveShell |
|
395 | # Subcomponents of InteractiveShell | |
396 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
396 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) | |
397 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
397 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) | |
398 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
398 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) | |
399 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
399 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) | |
400 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
400 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) | |
401 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
401 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) | |
402 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
402 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) | |
403 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
403 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) | |
404 |
|
404 | |||
405 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
405 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) | |
406 | @property |
|
406 | @property | |
407 | def profile(self): |
|
407 | def profile(self): | |
408 | if self.profile_dir is not None: |
|
408 | if self.profile_dir is not None: | |
409 | name = os.path.basename(self.profile_dir.location) |
|
409 | name = os.path.basename(self.profile_dir.location) | |
410 | return name.replace('profile_','') |
|
410 | return name.replace('profile_','') | |
411 |
|
411 | |||
412 |
|
412 | |||
413 | # Private interface |
|
413 | # Private interface | |
414 | _post_execute = Dict() |
|
414 | _post_execute = Dict() | |
415 |
|
415 | |||
416 | # Tracks any GUI loop loaded for pylab |
|
416 | # Tracks any GUI loop loaded for pylab | |
417 | pylab_gui_select = None |
|
417 | pylab_gui_select = None | |
418 |
|
418 | |||
419 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
419 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') | |
420 |
|
420 | |||
421 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
421 | def __init__(self, ipython_dir=None, profile_dir=None, | |
422 | user_module=None, user_ns=None, |
|
422 | user_module=None, user_ns=None, | |
423 | custom_exceptions=((), None), **kwargs): |
|
423 | custom_exceptions=((), None), **kwargs): | |
424 |
|
424 | |||
425 | # This is where traits with a config_key argument are updated |
|
425 | # This is where traits with a config_key argument are updated | |
426 | # from the values on config. |
|
426 | # from the values on config. | |
427 | super(InteractiveShell, self).__init__(**kwargs) |
|
427 | super(InteractiveShell, self).__init__(**kwargs) | |
428 | if 'PromptManager' in self.config: |
|
428 | if 'PromptManager' in self.config: | |
429 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
429 | warn('As of IPython 5.0 `PromptManager` config will have no effect' | |
430 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
430 | ' and has been replaced by TerminalInteractiveShell.prompts_class') | |
431 | self.configurables = [self] |
|
431 | self.configurables = [self] | |
432 |
|
432 | |||
433 | # These are relatively independent and stateless |
|
433 | # These are relatively independent and stateless | |
434 | self.init_ipython_dir(ipython_dir) |
|
434 | self.init_ipython_dir(ipython_dir) | |
435 | self.init_profile_dir(profile_dir) |
|
435 | self.init_profile_dir(profile_dir) | |
436 | self.init_instance_attrs() |
|
436 | self.init_instance_attrs() | |
437 | self.init_environment() |
|
437 | self.init_environment() | |
438 |
|
438 | |||
439 | # Check if we're in a virtualenv, and set up sys.path. |
|
439 | # Check if we're in a virtualenv, and set up sys.path. | |
440 | self.init_virtualenv() |
|
440 | self.init_virtualenv() | |
441 |
|
441 | |||
442 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
442 | # Create namespaces (user_ns, user_global_ns, etc.) | |
443 | self.init_create_namespaces(user_module, user_ns) |
|
443 | self.init_create_namespaces(user_module, user_ns) | |
444 | # This has to be done after init_create_namespaces because it uses |
|
444 | # This has to be done after init_create_namespaces because it uses | |
445 | # something in self.user_ns, but before init_sys_modules, which |
|
445 | # something in self.user_ns, but before init_sys_modules, which | |
446 | # is the first thing to modify sys. |
|
446 | # is the first thing to modify sys. | |
447 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
447 | # TODO: When we override sys.stdout and sys.stderr before this class | |
448 | # is created, we are saving the overridden ones here. Not sure if this |
|
448 | # is created, we are saving the overridden ones here. Not sure if this | |
449 | # is what we want to do. |
|
449 | # is what we want to do. | |
450 | self.save_sys_module_state() |
|
450 | self.save_sys_module_state() | |
451 | self.init_sys_modules() |
|
451 | self.init_sys_modules() | |
452 |
|
452 | |||
453 | # While we're trying to have each part of the code directly access what |
|
453 | # While we're trying to have each part of the code directly access what | |
454 | # it needs without keeping redundant references to objects, we have too |
|
454 | # it needs without keeping redundant references to objects, we have too | |
455 | # much legacy code that expects ip.db to exist. |
|
455 | # much legacy code that expects ip.db to exist. | |
456 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
456 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
457 |
|
457 | |||
458 | self.init_history() |
|
458 | self.init_history() | |
459 | self.init_encoding() |
|
459 | self.init_encoding() | |
460 | self.init_prefilter() |
|
460 | self.init_prefilter() | |
461 |
|
461 | |||
462 | self.init_syntax_highlighting() |
|
462 | self.init_syntax_highlighting() | |
463 | self.init_hooks() |
|
463 | self.init_hooks() | |
464 | self.init_events() |
|
464 | self.init_events() | |
465 | self.init_pushd_popd_magic() |
|
465 | self.init_pushd_popd_magic() | |
466 | self.init_user_ns() |
|
466 | self.init_user_ns() | |
467 | self.init_logger() |
|
467 | self.init_logger() | |
468 | self.init_builtins() |
|
468 | self.init_builtins() | |
469 |
|
469 | |||
470 | # The following was in post_config_initialization |
|
470 | # The following was in post_config_initialization | |
471 | self.init_inspector() |
|
471 | self.init_inspector() | |
472 | self.raw_input_original = input |
|
472 | self.raw_input_original = input | |
473 | self.init_completer() |
|
473 | self.init_completer() | |
474 | # TODO: init_io() needs to happen before init_traceback handlers |
|
474 | # TODO: init_io() needs to happen before init_traceback handlers | |
475 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
475 | # because the traceback handlers hardcode the stdout/stderr streams. | |
476 | # This logic in in debugger.Pdb and should eventually be changed. |
|
476 | # This logic in in debugger.Pdb and should eventually be changed. | |
477 | self.init_io() |
|
477 | self.init_io() | |
478 | self.init_traceback_handlers(custom_exceptions) |
|
478 | self.init_traceback_handlers(custom_exceptions) | |
479 | self.init_prompts() |
|
479 | self.init_prompts() | |
480 | self.init_display_formatter() |
|
480 | self.init_display_formatter() | |
481 | self.init_display_pub() |
|
481 | self.init_display_pub() | |
482 | self.init_data_pub() |
|
482 | self.init_data_pub() | |
483 | self.init_displayhook() |
|
483 | self.init_displayhook() | |
484 | self.init_magics() |
|
484 | self.init_magics() | |
485 | self.init_alias() |
|
485 | self.init_alias() | |
486 | self.init_logstart() |
|
486 | self.init_logstart() | |
487 | self.init_pdb() |
|
487 | self.init_pdb() | |
488 | self.init_extension_manager() |
|
488 | self.init_extension_manager() | |
489 | self.init_payload() |
|
489 | self.init_payload() | |
490 | self.init_deprecation_warnings() |
|
490 | self.init_deprecation_warnings() | |
491 | self.hooks.late_startup_hook() |
|
491 | self.hooks.late_startup_hook() | |
492 | self.events.trigger('shell_initialized', self) |
|
492 | self.events.trigger('shell_initialized', self) | |
493 | atexit.register(self.atexit_operations) |
|
493 | atexit.register(self.atexit_operations) | |
494 |
|
494 | |||
495 | def get_ipython(self): |
|
495 | def get_ipython(self): | |
496 | """Return the currently running IPython instance.""" |
|
496 | """Return the currently running IPython instance.""" | |
497 | return self |
|
497 | return self | |
498 |
|
498 | |||
499 | #------------------------------------------------------------------------- |
|
499 | #------------------------------------------------------------------------- | |
500 | # Trait changed handlers |
|
500 | # Trait changed handlers | |
501 | #------------------------------------------------------------------------- |
|
501 | #------------------------------------------------------------------------- | |
502 | @observe('ipython_dir') |
|
502 | @observe('ipython_dir') | |
503 | def _ipython_dir_changed(self, change): |
|
503 | def _ipython_dir_changed(self, change): | |
504 | ensure_dir_exists(change['new']) |
|
504 | ensure_dir_exists(change['new']) | |
505 |
|
505 | |||
506 | def set_autoindent(self,value=None): |
|
506 | def set_autoindent(self,value=None): | |
507 | """Set the autoindent flag. |
|
507 | """Set the autoindent flag. | |
508 |
|
508 | |||
509 | If called with no arguments, it acts as a toggle.""" |
|
509 | If called with no arguments, it acts as a toggle.""" | |
510 | if value is None: |
|
510 | if value is None: | |
511 | self.autoindent = not self.autoindent |
|
511 | self.autoindent = not self.autoindent | |
512 | else: |
|
512 | else: | |
513 | self.autoindent = value |
|
513 | self.autoindent = value | |
514 |
|
514 | |||
515 | #------------------------------------------------------------------------- |
|
515 | #------------------------------------------------------------------------- | |
516 | # init_* methods called by __init__ |
|
516 | # init_* methods called by __init__ | |
517 | #------------------------------------------------------------------------- |
|
517 | #------------------------------------------------------------------------- | |
518 |
|
518 | |||
519 | def init_ipython_dir(self, ipython_dir): |
|
519 | def init_ipython_dir(self, ipython_dir): | |
520 | if ipython_dir is not None: |
|
520 | if ipython_dir is not None: | |
521 | self.ipython_dir = ipython_dir |
|
521 | self.ipython_dir = ipython_dir | |
522 | return |
|
522 | return | |
523 |
|
523 | |||
524 | self.ipython_dir = get_ipython_dir() |
|
524 | self.ipython_dir = get_ipython_dir() | |
525 |
|
525 | |||
526 | def init_profile_dir(self, profile_dir): |
|
526 | def init_profile_dir(self, profile_dir): | |
527 | if profile_dir is not None: |
|
527 | if profile_dir is not None: | |
528 | self.profile_dir = profile_dir |
|
528 | self.profile_dir = profile_dir | |
529 | return |
|
529 | return | |
530 | self.profile_dir =\ |
|
530 | self.profile_dir =\ | |
531 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
531 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
532 |
|
532 | |||
533 | def init_instance_attrs(self): |
|
533 | def init_instance_attrs(self): | |
534 | self.more = False |
|
534 | self.more = False | |
535 |
|
535 | |||
536 | # command compiler |
|
536 | # command compiler | |
537 | self.compile = CachingCompiler() |
|
537 | self.compile = CachingCompiler() | |
538 |
|
538 | |||
539 | # Make an empty namespace, which extension writers can rely on both |
|
539 | # Make an empty namespace, which extension writers can rely on both | |
540 | # existing and NEVER being used by ipython itself. This gives them a |
|
540 | # existing and NEVER being used by ipython itself. This gives them a | |
541 | # convenient location for storing additional information and state |
|
541 | # convenient location for storing additional information and state | |
542 | # their extensions may require, without fear of collisions with other |
|
542 | # their extensions may require, without fear of collisions with other | |
543 | # ipython names that may develop later. |
|
543 | # ipython names that may develop later. | |
544 | self.meta = Struct() |
|
544 | self.meta = Struct() | |
545 |
|
545 | |||
546 | # Temporary files used for various purposes. Deleted at exit. |
|
546 | # Temporary files used for various purposes. Deleted at exit. | |
547 | self.tempfiles = [] |
|
547 | self.tempfiles = [] | |
548 | self.tempdirs = [] |
|
548 | self.tempdirs = [] | |
549 |
|
549 | |||
550 | # keep track of where we started running (mainly for crash post-mortem) |
|
550 | # keep track of where we started running (mainly for crash post-mortem) | |
551 | # This is not being used anywhere currently. |
|
551 | # This is not being used anywhere currently. | |
552 | self.starting_dir = os.getcwd() |
|
552 | self.starting_dir = os.getcwd() | |
553 |
|
553 | |||
554 | # Indentation management |
|
554 | # Indentation management | |
555 | self.indent_current_nsp = 0 |
|
555 | self.indent_current_nsp = 0 | |
556 |
|
556 | |||
557 | # Dict to track post-execution functions that have been registered |
|
557 | # Dict to track post-execution functions that have been registered | |
558 | self._post_execute = {} |
|
558 | self._post_execute = {} | |
559 |
|
559 | |||
560 | def init_environment(self): |
|
560 | def init_environment(self): | |
561 | """Any changes we need to make to the user's environment.""" |
|
561 | """Any changes we need to make to the user's environment.""" | |
562 | pass |
|
562 | pass | |
563 |
|
563 | |||
564 | def init_encoding(self): |
|
564 | def init_encoding(self): | |
565 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
565 | # Get system encoding at startup time. Certain terminals (like Emacs | |
566 | # under Win32 have it set to None, and we need to have a known valid |
|
566 | # under Win32 have it set to None, and we need to have a known valid | |
567 | # encoding to use in the raw_input() method |
|
567 | # encoding to use in the raw_input() method | |
568 | try: |
|
568 | try: | |
569 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
569 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
570 | except AttributeError: |
|
570 | except AttributeError: | |
571 | self.stdin_encoding = 'ascii' |
|
571 | self.stdin_encoding = 'ascii' | |
572 |
|
572 | |||
573 |
|
573 | |||
574 | @observe('colors') |
|
574 | @observe('colors') | |
575 | def init_syntax_highlighting(self, changes=None): |
|
575 | def init_syntax_highlighting(self, changes=None): | |
576 | # Python source parser/formatter for syntax highlighting |
|
576 | # Python source parser/formatter for syntax highlighting | |
577 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format |
|
577 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format | |
578 | self.pycolorize = lambda src: pyformat(src,'str') |
|
578 | self.pycolorize = lambda src: pyformat(src,'str') | |
579 |
|
579 | |||
580 | def refresh_style(self): |
|
580 | def refresh_style(self): | |
581 | # No-op here, used in subclass |
|
581 | # No-op here, used in subclass | |
582 | pass |
|
582 | pass | |
583 |
|
583 | |||
584 | def init_pushd_popd_magic(self): |
|
584 | def init_pushd_popd_magic(self): | |
585 | # for pushd/popd management |
|
585 | # for pushd/popd management | |
586 | self.home_dir = get_home_dir() |
|
586 | self.home_dir = get_home_dir() | |
587 |
|
587 | |||
588 | self.dir_stack = [] |
|
588 | self.dir_stack = [] | |
589 |
|
589 | |||
590 | def init_logger(self): |
|
590 | def init_logger(self): | |
591 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
591 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
592 | logmode='rotate') |
|
592 | logmode='rotate') | |
593 |
|
593 | |||
594 | def init_logstart(self): |
|
594 | def init_logstart(self): | |
595 | """Initialize logging in case it was requested at the command line. |
|
595 | """Initialize logging in case it was requested at the command line. | |
596 | """ |
|
596 | """ | |
597 | if self.logappend: |
|
597 | if self.logappend: | |
598 | self.magic('logstart %s append' % self.logappend) |
|
598 | self.magic('logstart %s append' % self.logappend) | |
599 | elif self.logfile: |
|
599 | elif self.logfile: | |
600 | self.magic('logstart %s' % self.logfile) |
|
600 | self.magic('logstart %s' % self.logfile) | |
601 | elif self.logstart: |
|
601 | elif self.logstart: | |
602 | self.magic('logstart') |
|
602 | self.magic('logstart') | |
603 |
|
603 | |||
604 | def init_deprecation_warnings(self): |
|
604 | def init_deprecation_warnings(self): | |
605 | """ |
|
605 | """ | |
606 | register default filter for deprecation warning. |
|
606 | register default filter for deprecation warning. | |
607 |
|
607 | |||
608 | This will allow deprecation warning of function used interactively to show |
|
608 | This will allow deprecation warning of function used interactively to show | |
609 | warning to users, and still hide deprecation warning from libraries import. |
|
609 | warning to users, and still hide deprecation warning from libraries import. | |
610 | """ |
|
610 | """ | |
611 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
611 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) | |
612 |
|
612 | |||
613 | def init_builtins(self): |
|
613 | def init_builtins(self): | |
614 | # A single, static flag that we set to True. Its presence indicates |
|
614 | # A single, static flag that we set to True. Its presence indicates | |
615 | # that an IPython shell has been created, and we make no attempts at |
|
615 | # that an IPython shell has been created, and we make no attempts at | |
616 | # removing on exit or representing the existence of more than one |
|
616 | # removing on exit or representing the existence of more than one | |
617 | # IPython at a time. |
|
617 | # IPython at a time. | |
618 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
618 | builtin_mod.__dict__['__IPYTHON__'] = True | |
619 |
|
619 | |||
620 | self.builtin_trap = BuiltinTrap(shell=self) |
|
620 | self.builtin_trap = BuiltinTrap(shell=self) | |
621 |
|
621 | |||
622 | def init_inspector(self): |
|
622 | def init_inspector(self): | |
623 | # Object inspector |
|
623 | # Object inspector | |
624 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
624 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
625 | PyColorize.ANSICodeColors, |
|
625 | PyColorize.ANSICodeColors, | |
626 | 'NoColor', |
|
626 | 'NoColor', | |
627 | self.object_info_string_level) |
|
627 | self.object_info_string_level) | |
628 |
|
628 | |||
629 | def init_io(self): |
|
629 | def init_io(self): | |
630 | # This will just use sys.stdout and sys.stderr. If you want to |
|
630 | # This will just use sys.stdout and sys.stderr. If you want to | |
631 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
631 | # override sys.stdout and sys.stderr themselves, you need to do that | |
632 | # *before* instantiating this class, because io holds onto |
|
632 | # *before* instantiating this class, because io holds onto | |
633 | # references to the underlying streams. |
|
633 | # references to the underlying streams. | |
634 | # io.std* are deprecated, but don't show our own deprecation warnings |
|
634 | # io.std* are deprecated, but don't show our own deprecation warnings | |
635 | # during initialization of the deprecated API. |
|
635 | # during initialization of the deprecated API. | |
636 | with warnings.catch_warnings(): |
|
636 | with warnings.catch_warnings(): | |
637 | warnings.simplefilter('ignore', DeprecationWarning) |
|
637 | warnings.simplefilter('ignore', DeprecationWarning) | |
638 | io.stdout = io.IOStream(sys.stdout) |
|
638 | io.stdout = io.IOStream(sys.stdout) | |
639 | io.stderr = io.IOStream(sys.stderr) |
|
639 | io.stderr = io.IOStream(sys.stderr) | |
640 |
|
640 | |||
641 | def init_prompts(self): |
|
641 | def init_prompts(self): | |
642 | # Set system prompts, so that scripts can decide if they are running |
|
642 | # Set system prompts, so that scripts can decide if they are running | |
643 | # interactively. |
|
643 | # interactively. | |
644 | sys.ps1 = 'In : ' |
|
644 | sys.ps1 = 'In : ' | |
645 | sys.ps2 = '...: ' |
|
645 | sys.ps2 = '...: ' | |
646 | sys.ps3 = 'Out: ' |
|
646 | sys.ps3 = 'Out: ' | |
647 |
|
647 | |||
648 | def init_display_formatter(self): |
|
648 | def init_display_formatter(self): | |
649 | self.display_formatter = DisplayFormatter(parent=self) |
|
649 | self.display_formatter = DisplayFormatter(parent=self) | |
650 | self.configurables.append(self.display_formatter) |
|
650 | self.configurables.append(self.display_formatter) | |
651 |
|
651 | |||
652 | def init_display_pub(self): |
|
652 | def init_display_pub(self): | |
653 | self.display_pub = self.display_pub_class(parent=self) |
|
653 | self.display_pub = self.display_pub_class(parent=self) | |
654 | self.configurables.append(self.display_pub) |
|
654 | self.configurables.append(self.display_pub) | |
655 |
|
655 | |||
656 | def init_data_pub(self): |
|
656 | def init_data_pub(self): | |
657 | if not self.data_pub_class: |
|
657 | if not self.data_pub_class: | |
658 | self.data_pub = None |
|
658 | self.data_pub = None | |
659 | return |
|
659 | return | |
660 | self.data_pub = self.data_pub_class(parent=self) |
|
660 | self.data_pub = self.data_pub_class(parent=self) | |
661 | self.configurables.append(self.data_pub) |
|
661 | self.configurables.append(self.data_pub) | |
662 |
|
662 | |||
663 | def init_displayhook(self): |
|
663 | def init_displayhook(self): | |
664 | # Initialize displayhook, set in/out prompts and printing system |
|
664 | # Initialize displayhook, set in/out prompts and printing system | |
665 | self.displayhook = self.displayhook_class( |
|
665 | self.displayhook = self.displayhook_class( | |
666 | parent=self, |
|
666 | parent=self, | |
667 | shell=self, |
|
667 | shell=self, | |
668 | cache_size=self.cache_size, |
|
668 | cache_size=self.cache_size, | |
669 | ) |
|
669 | ) | |
670 | self.configurables.append(self.displayhook) |
|
670 | self.configurables.append(self.displayhook) | |
671 | # This is a context manager that installs/revmoes the displayhook at |
|
671 | # This is a context manager that installs/revmoes the displayhook at | |
672 | # the appropriate time. |
|
672 | # the appropriate time. | |
673 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
673 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
674 |
|
674 | |||
675 | def init_virtualenv(self): |
|
675 | def init_virtualenv(self): | |
676 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
676 | """Add a virtualenv to sys.path so the user can import modules from it. | |
677 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
677 | This isn't perfect: it doesn't use the Python interpreter with which the | |
678 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
678 | virtualenv was built, and it ignores the --no-site-packages option. A | |
679 | warning will appear suggesting the user installs IPython in the |
|
679 | warning will appear suggesting the user installs IPython in the | |
680 | virtualenv, but for many cases, it probably works well enough. |
|
680 | virtualenv, but for many cases, it probably works well enough. | |
681 |
|
681 | |||
682 | Adapted from code snippets online. |
|
682 | Adapted from code snippets online. | |
683 |
|
683 | |||
684 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
684 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv | |
685 | """ |
|
685 | """ | |
686 | if 'VIRTUAL_ENV' not in os.environ: |
|
686 | if 'VIRTUAL_ENV' not in os.environ: | |
687 | # Not in a virtualenv |
|
687 | # Not in a virtualenv | |
688 | return |
|
688 | return | |
689 |
|
689 | |||
690 | # venv detection: |
|
690 | # venv detection: | |
691 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
691 | # stdlib venv may symlink sys.executable, so we can't use realpath. | |
692 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
692 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. | |
693 | # So we just check every item in the symlink tree (generally <= 3) |
|
693 | # So we just check every item in the symlink tree (generally <= 3) | |
694 | p = os.path.normcase(sys.executable) |
|
694 | p = os.path.normcase(sys.executable) | |
695 | paths = [p] |
|
695 | paths = [p] | |
696 | while os.path.islink(p): |
|
696 | while os.path.islink(p): | |
697 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
697 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) | |
698 | paths.append(p) |
|
698 | paths.append(p) | |
699 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
699 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) | |
700 | if any(p.startswith(p_venv) for p in paths): |
|
700 | if any(p.startswith(p_venv) for p in paths): | |
701 | # Running properly in the virtualenv, don't need to do anything |
|
701 | # Running properly in the virtualenv, don't need to do anything | |
702 | return |
|
702 | return | |
703 |
|
703 | |||
704 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
704 | warn("Attempting to work in a virtualenv. If you encounter problems, please " | |
705 | "install IPython inside the virtualenv.") |
|
705 | "install IPython inside the virtualenv.") | |
706 | if sys.platform == "win32": |
|
706 | if sys.platform == "win32": | |
707 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
707 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') | |
708 | else: |
|
708 | else: | |
709 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
709 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', | |
710 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
710 | 'python%d.%d' % sys.version_info[:2], 'site-packages') | |
711 |
|
711 | |||
712 | import site |
|
712 | import site | |
713 | sys.path.insert(0, virtual_env) |
|
713 | sys.path.insert(0, virtual_env) | |
714 | site.addsitedir(virtual_env) |
|
714 | site.addsitedir(virtual_env) | |
715 |
|
715 | |||
716 | #------------------------------------------------------------------------- |
|
716 | #------------------------------------------------------------------------- | |
717 | # Things related to injections into the sys module |
|
717 | # Things related to injections into the sys module | |
718 | #------------------------------------------------------------------------- |
|
718 | #------------------------------------------------------------------------- | |
719 |
|
719 | |||
720 | def save_sys_module_state(self): |
|
720 | def save_sys_module_state(self): | |
721 | """Save the state of hooks in the sys module. |
|
721 | """Save the state of hooks in the sys module. | |
722 |
|
722 | |||
723 | This has to be called after self.user_module is created. |
|
723 | This has to be called after self.user_module is created. | |
724 | """ |
|
724 | """ | |
725 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
725 | self._orig_sys_module_state = {'stdin': sys.stdin, | |
726 | 'stdout': sys.stdout, |
|
726 | 'stdout': sys.stdout, | |
727 | 'stderr': sys.stderr, |
|
727 | 'stderr': sys.stderr, | |
728 | 'excepthook': sys.excepthook} |
|
728 | 'excepthook': sys.excepthook} | |
729 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
729 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
730 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
730 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) | |
731 |
|
731 | |||
732 | def restore_sys_module_state(self): |
|
732 | def restore_sys_module_state(self): | |
733 | """Restore the state of the sys module.""" |
|
733 | """Restore the state of the sys module.""" | |
734 | try: |
|
734 | try: | |
735 | for k, v in self._orig_sys_module_state.items(): |
|
735 | for k, v in self._orig_sys_module_state.items(): | |
736 | setattr(sys, k, v) |
|
736 | setattr(sys, k, v) | |
737 | except AttributeError: |
|
737 | except AttributeError: | |
738 | pass |
|
738 | pass | |
739 | # Reset what what done in self.init_sys_modules |
|
739 | # Reset what what done in self.init_sys_modules | |
740 | if self._orig_sys_modules_main_mod is not None: |
|
740 | if self._orig_sys_modules_main_mod is not None: | |
741 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
741 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | |
742 |
|
742 | |||
743 | #------------------------------------------------------------------------- |
|
743 | #------------------------------------------------------------------------- | |
744 | # Things related to the banner |
|
744 | # Things related to the banner | |
745 | #------------------------------------------------------------------------- |
|
745 | #------------------------------------------------------------------------- | |
746 |
|
746 | |||
747 | @property |
|
747 | @property | |
748 | def banner(self): |
|
748 | def banner(self): | |
749 | banner = self.banner1 |
|
749 | banner = self.banner1 | |
750 | if self.profile and self.profile != 'default': |
|
750 | if self.profile and self.profile != 'default': | |
751 | banner += '\nIPython profile: %s\n' % self.profile |
|
751 | banner += '\nIPython profile: %s\n' % self.profile | |
752 | if self.banner2: |
|
752 | if self.banner2: | |
753 | banner += '\n' + self.banner2 |
|
753 | banner += '\n' + self.banner2 | |
754 | return banner |
|
754 | return banner | |
755 |
|
755 | |||
756 | def show_banner(self, banner=None): |
|
756 | def show_banner(self, banner=None): | |
757 | if banner is None: |
|
757 | if banner is None: | |
758 | banner = self.banner |
|
758 | banner = self.banner | |
759 | sys.stdout.write(banner) |
|
759 | sys.stdout.write(banner) | |
760 |
|
760 | |||
761 | #------------------------------------------------------------------------- |
|
761 | #------------------------------------------------------------------------- | |
762 | # Things related to hooks |
|
762 | # Things related to hooks | |
763 | #------------------------------------------------------------------------- |
|
763 | #------------------------------------------------------------------------- | |
764 |
|
764 | |||
765 | def init_hooks(self): |
|
765 | def init_hooks(self): | |
766 | # hooks holds pointers used for user-side customizations |
|
766 | # hooks holds pointers used for user-side customizations | |
767 | self.hooks = Struct() |
|
767 | self.hooks = Struct() | |
768 |
|
768 | |||
769 | self.strdispatchers = {} |
|
769 | self.strdispatchers = {} | |
770 |
|
770 | |||
771 | # Set all default hooks, defined in the IPython.hooks module. |
|
771 | # Set all default hooks, defined in the IPython.hooks module. | |
772 | hooks = IPython.core.hooks |
|
772 | hooks = IPython.core.hooks | |
773 | for hook_name in hooks.__all__: |
|
773 | for hook_name in hooks.__all__: | |
774 | # default hooks have priority 100, i.e. low; user hooks should have |
|
774 | # default hooks have priority 100, i.e. low; user hooks should have | |
775 | # 0-100 priority |
|
775 | # 0-100 priority | |
776 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
776 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) | |
777 |
|
777 | |||
778 | if self.display_page: |
|
778 | if self.display_page: | |
779 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
779 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) | |
780 |
|
780 | |||
781 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
781 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, | |
782 | _warn_deprecated=True): |
|
782 | _warn_deprecated=True): | |
783 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
783 | """set_hook(name,hook) -> sets an internal IPython hook. | |
784 |
|
784 | |||
785 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
785 | IPython exposes some of its internal API as user-modifiable hooks. By | |
786 | adding your function to one of these hooks, you can modify IPython's |
|
786 | adding your function to one of these hooks, you can modify IPython's | |
787 | behavior to call at runtime your own routines.""" |
|
787 | behavior to call at runtime your own routines.""" | |
788 |
|
788 | |||
789 | # At some point in the future, this should validate the hook before it |
|
789 | # At some point in the future, this should validate the hook before it | |
790 | # accepts it. Probably at least check that the hook takes the number |
|
790 | # accepts it. Probably at least check that the hook takes the number | |
791 | # of args it's supposed to. |
|
791 | # of args it's supposed to. | |
792 |
|
792 | |||
793 | f = types.MethodType(hook,self) |
|
793 | f = types.MethodType(hook,self) | |
794 |
|
794 | |||
795 | # check if the hook is for strdispatcher first |
|
795 | # check if the hook is for strdispatcher first | |
796 | if str_key is not None: |
|
796 | if str_key is not None: | |
797 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
797 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
798 | sdp.add_s(str_key, f, priority ) |
|
798 | sdp.add_s(str_key, f, priority ) | |
799 | self.strdispatchers[name] = sdp |
|
799 | self.strdispatchers[name] = sdp | |
800 | return |
|
800 | return | |
801 | if re_key is not None: |
|
801 | if re_key is not None: | |
802 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
802 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
803 | sdp.add_re(re.compile(re_key), f, priority ) |
|
803 | sdp.add_re(re.compile(re_key), f, priority ) | |
804 | self.strdispatchers[name] = sdp |
|
804 | self.strdispatchers[name] = sdp | |
805 | return |
|
805 | return | |
806 |
|
806 | |||
807 | dp = getattr(self.hooks, name, None) |
|
807 | dp = getattr(self.hooks, name, None) | |
808 | if name not in IPython.core.hooks.__all__: |
|
808 | if name not in IPython.core.hooks.__all__: | |
809 | print("Warning! Hook '%s' is not one of %s" % \ |
|
809 | print("Warning! Hook '%s' is not one of %s" % \ | |
810 | (name, IPython.core.hooks.__all__ )) |
|
810 | (name, IPython.core.hooks.__all__ )) | |
811 |
|
811 | |||
812 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
812 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): | |
813 | alternative = IPython.core.hooks.deprecated[name] |
|
813 | alternative = IPython.core.hooks.deprecated[name] | |
814 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) |
|
814 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) | |
815 |
|
815 | |||
816 | if not dp: |
|
816 | if not dp: | |
817 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
817 | dp = IPython.core.hooks.CommandChainDispatcher() | |
818 |
|
818 | |||
819 | try: |
|
819 | try: | |
820 | dp.add(f,priority) |
|
820 | dp.add(f,priority) | |
821 | except AttributeError: |
|
821 | except AttributeError: | |
822 | # it was not commandchain, plain old func - replace |
|
822 | # it was not commandchain, plain old func - replace | |
823 | dp = f |
|
823 | dp = f | |
824 |
|
824 | |||
825 | setattr(self.hooks,name, dp) |
|
825 | setattr(self.hooks,name, dp) | |
826 |
|
826 | |||
827 | #------------------------------------------------------------------------- |
|
827 | #------------------------------------------------------------------------- | |
828 | # Things related to events |
|
828 | # Things related to events | |
829 | #------------------------------------------------------------------------- |
|
829 | #------------------------------------------------------------------------- | |
830 |
|
830 | |||
831 | def init_events(self): |
|
831 | def init_events(self): | |
832 | self.events = EventManager(self, available_events) |
|
832 | self.events = EventManager(self, available_events) | |
833 |
|
833 | |||
834 | self.events.register("pre_execute", self._clear_warning_registry) |
|
834 | self.events.register("pre_execute", self._clear_warning_registry) | |
835 |
|
835 | |||
836 | def register_post_execute(self, func): |
|
836 | def register_post_execute(self, func): | |
837 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
837 | """DEPRECATED: Use ip.events.register('post_run_cell', func) | |
838 |
|
838 | |||
839 | Register a function for calling after code execution. |
|
839 | Register a function for calling after code execution. | |
840 | """ |
|
840 | """ | |
841 | warn("ip.register_post_execute is deprecated, use " |
|
841 | warn("ip.register_post_execute is deprecated, use " | |
842 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) |
|
842 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) | |
843 | self.events.register('post_run_cell', func) |
|
843 | self.events.register('post_run_cell', func) | |
844 |
|
844 | |||
845 | def _clear_warning_registry(self): |
|
845 | def _clear_warning_registry(self): | |
846 | # clear the warning registry, so that different code blocks with |
|
846 | # clear the warning registry, so that different code blocks with | |
847 | # overlapping line number ranges don't cause spurious suppression of |
|
847 | # overlapping line number ranges don't cause spurious suppression of | |
848 | # warnings (see gh-6611 for details) |
|
848 | # warnings (see gh-6611 for details) | |
849 | if "__warningregistry__" in self.user_global_ns: |
|
849 | if "__warningregistry__" in self.user_global_ns: | |
850 | del self.user_global_ns["__warningregistry__"] |
|
850 | del self.user_global_ns["__warningregistry__"] | |
851 |
|
851 | |||
852 | #------------------------------------------------------------------------- |
|
852 | #------------------------------------------------------------------------- | |
853 | # Things related to the "main" module |
|
853 | # Things related to the "main" module | |
854 | #------------------------------------------------------------------------- |
|
854 | #------------------------------------------------------------------------- | |
855 |
|
855 | |||
856 | def new_main_mod(self, filename, modname): |
|
856 | def new_main_mod(self, filename, modname): | |
857 | """Return a new 'main' module object for user code execution. |
|
857 | """Return a new 'main' module object for user code execution. | |
858 |
|
858 | |||
859 | ``filename`` should be the path of the script which will be run in the |
|
859 | ``filename`` should be the path of the script which will be run in the | |
860 | module. Requests with the same filename will get the same module, with |
|
860 | module. Requests with the same filename will get the same module, with | |
861 | its namespace cleared. |
|
861 | its namespace cleared. | |
862 |
|
862 | |||
863 | ``modname`` should be the module name - normally either '__main__' or |
|
863 | ``modname`` should be the module name - normally either '__main__' or | |
864 | the basename of the file without the extension. |
|
864 | the basename of the file without the extension. | |
865 |
|
865 | |||
866 | When scripts are executed via %run, we must keep a reference to their |
|
866 | When scripts are executed via %run, we must keep a reference to their | |
867 | __main__ module around so that Python doesn't |
|
867 | __main__ module around so that Python doesn't | |
868 | clear it, rendering references to module globals useless. |
|
868 | clear it, rendering references to module globals useless. | |
869 |
|
869 | |||
870 | This method keeps said reference in a private dict, keyed by the |
|
870 | This method keeps said reference in a private dict, keyed by the | |
871 | absolute path of the script. This way, for multiple executions of the |
|
871 | absolute path of the script. This way, for multiple executions of the | |
872 | same script we only keep one copy of the namespace (the last one), |
|
872 | same script we only keep one copy of the namespace (the last one), | |
873 | thus preventing memory leaks from old references while allowing the |
|
873 | thus preventing memory leaks from old references while allowing the | |
874 | objects from the last execution to be accessible. |
|
874 | objects from the last execution to be accessible. | |
875 | """ |
|
875 | """ | |
876 | filename = os.path.abspath(filename) |
|
876 | filename = os.path.abspath(filename) | |
877 | try: |
|
877 | try: | |
878 | main_mod = self._main_mod_cache[filename] |
|
878 | main_mod = self._main_mod_cache[filename] | |
879 | except KeyError: |
|
879 | except KeyError: | |
880 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
880 | main_mod = self._main_mod_cache[filename] = types.ModuleType( | |
881 | py3compat.cast_bytes_py2(modname), |
|
881 | py3compat.cast_bytes_py2(modname), | |
882 | doc="Module created for script run in IPython") |
|
882 | doc="Module created for script run in IPython") | |
883 | else: |
|
883 | else: | |
884 | main_mod.__dict__.clear() |
|
884 | main_mod.__dict__.clear() | |
885 | main_mod.__name__ = modname |
|
885 | main_mod.__name__ = modname | |
886 |
|
886 | |||
887 | main_mod.__file__ = filename |
|
887 | main_mod.__file__ = filename | |
888 | # It seems pydoc (and perhaps others) needs any module instance to |
|
888 | # It seems pydoc (and perhaps others) needs any module instance to | |
889 | # implement a __nonzero__ method |
|
889 | # implement a __nonzero__ method | |
890 | main_mod.__nonzero__ = lambda : True |
|
890 | main_mod.__nonzero__ = lambda : True | |
891 |
|
891 | |||
892 | return main_mod |
|
892 | return main_mod | |
893 |
|
893 | |||
894 | def clear_main_mod_cache(self): |
|
894 | def clear_main_mod_cache(self): | |
895 | """Clear the cache of main modules. |
|
895 | """Clear the cache of main modules. | |
896 |
|
896 | |||
897 | Mainly for use by utilities like %reset. |
|
897 | Mainly for use by utilities like %reset. | |
898 |
|
898 | |||
899 | Examples |
|
899 | Examples | |
900 | -------- |
|
900 | -------- | |
901 |
|
901 | |||
902 | In [15]: import IPython |
|
902 | In [15]: import IPython | |
903 |
|
903 | |||
904 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
904 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') | |
905 |
|
905 | |||
906 | In [17]: len(_ip._main_mod_cache) > 0 |
|
906 | In [17]: len(_ip._main_mod_cache) > 0 | |
907 | Out[17]: True |
|
907 | Out[17]: True | |
908 |
|
908 | |||
909 | In [18]: _ip.clear_main_mod_cache() |
|
909 | In [18]: _ip.clear_main_mod_cache() | |
910 |
|
910 | |||
911 | In [19]: len(_ip._main_mod_cache) == 0 |
|
911 | In [19]: len(_ip._main_mod_cache) == 0 | |
912 | Out[19]: True |
|
912 | Out[19]: True | |
913 | """ |
|
913 | """ | |
914 | self._main_mod_cache.clear() |
|
914 | self._main_mod_cache.clear() | |
915 |
|
915 | |||
916 | #------------------------------------------------------------------------- |
|
916 | #------------------------------------------------------------------------- | |
917 | # Things related to debugging |
|
917 | # Things related to debugging | |
918 | #------------------------------------------------------------------------- |
|
918 | #------------------------------------------------------------------------- | |
919 |
|
919 | |||
920 | def init_pdb(self): |
|
920 | def init_pdb(self): | |
921 | # Set calling of pdb on exceptions |
|
921 | # Set calling of pdb on exceptions | |
922 | # self.call_pdb is a property |
|
922 | # self.call_pdb is a property | |
923 | self.call_pdb = self.pdb |
|
923 | self.call_pdb = self.pdb | |
924 |
|
924 | |||
925 | def _get_call_pdb(self): |
|
925 | def _get_call_pdb(self): | |
926 | return self._call_pdb |
|
926 | return self._call_pdb | |
927 |
|
927 | |||
928 | def _set_call_pdb(self,val): |
|
928 | def _set_call_pdb(self,val): | |
929 |
|
929 | |||
930 | if val not in (0,1,False,True): |
|
930 | if val not in (0,1,False,True): | |
931 | raise ValueError('new call_pdb value must be boolean') |
|
931 | raise ValueError('new call_pdb value must be boolean') | |
932 |
|
932 | |||
933 | # store value in instance |
|
933 | # store value in instance | |
934 | self._call_pdb = val |
|
934 | self._call_pdb = val | |
935 |
|
935 | |||
936 | # notify the actual exception handlers |
|
936 | # notify the actual exception handlers | |
937 | self.InteractiveTB.call_pdb = val |
|
937 | self.InteractiveTB.call_pdb = val | |
938 |
|
938 | |||
939 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
939 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
940 | 'Control auto-activation of pdb at exceptions') |
|
940 | 'Control auto-activation of pdb at exceptions') | |
941 |
|
941 | |||
942 | def debugger(self,force=False): |
|
942 | def debugger(self,force=False): | |
943 | """Call the pdb debugger. |
|
943 | """Call the pdb debugger. | |
944 |
|
944 | |||
945 | Keywords: |
|
945 | Keywords: | |
946 |
|
946 | |||
947 | - force(False): by default, this routine checks the instance call_pdb |
|
947 | - force(False): by default, this routine checks the instance call_pdb | |
948 | flag and does not actually invoke the debugger if the flag is false. |
|
948 | flag and does not actually invoke the debugger if the flag is false. | |
949 | The 'force' option forces the debugger to activate even if the flag |
|
949 | The 'force' option forces the debugger to activate even if the flag | |
950 | is false. |
|
950 | is false. | |
951 | """ |
|
951 | """ | |
952 |
|
952 | |||
953 | if not (force or self.call_pdb): |
|
953 | if not (force or self.call_pdb): | |
954 | return |
|
954 | return | |
955 |
|
955 | |||
956 | if not hasattr(sys,'last_traceback'): |
|
956 | if not hasattr(sys,'last_traceback'): | |
957 | error('No traceback has been produced, nothing to debug.') |
|
957 | error('No traceback has been produced, nothing to debug.') | |
958 | return |
|
958 | return | |
959 |
|
959 | |||
960 | self.InteractiveTB.debugger(force=True) |
|
960 | self.InteractiveTB.debugger(force=True) | |
961 |
|
961 | |||
962 | #------------------------------------------------------------------------- |
|
962 | #------------------------------------------------------------------------- | |
963 | # Things related to IPython's various namespaces |
|
963 | # Things related to IPython's various namespaces | |
964 | #------------------------------------------------------------------------- |
|
964 | #------------------------------------------------------------------------- | |
965 | default_user_namespaces = True |
|
965 | default_user_namespaces = True | |
966 |
|
966 | |||
967 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
967 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
968 | # Create the namespace where the user will operate. user_ns is |
|
968 | # Create the namespace where the user will operate. user_ns is | |
969 | # normally the only one used, and it is passed to the exec calls as |
|
969 | # normally the only one used, and it is passed to the exec calls as | |
970 | # the locals argument. But we do carry a user_global_ns namespace |
|
970 | # the locals argument. But we do carry a user_global_ns namespace | |
971 | # given as the exec 'globals' argument, This is useful in embedding |
|
971 | # given as the exec 'globals' argument, This is useful in embedding | |
972 | # situations where the ipython shell opens in a context where the |
|
972 | # situations where the ipython shell opens in a context where the | |
973 | # distinction between locals and globals is meaningful. For |
|
973 | # distinction between locals and globals is meaningful. For | |
974 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
974 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
975 |
|
975 | |||
976 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
976 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
977 | # level as a dict instead of a module. This is a manual fix, but I |
|
977 | # level as a dict instead of a module. This is a manual fix, but I | |
978 | # should really track down where the problem is coming from. Alex |
|
978 | # should really track down where the problem is coming from. Alex | |
979 | # Schmolck reported this problem first. |
|
979 | # Schmolck reported this problem first. | |
980 |
|
980 | |||
981 | # A useful post by Alex Martelli on this topic: |
|
981 | # A useful post by Alex Martelli on this topic: | |
982 | # Re: inconsistent value from __builtins__ |
|
982 | # Re: inconsistent value from __builtins__ | |
983 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
983 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
984 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
984 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
985 | # Gruppen: comp.lang.python |
|
985 | # Gruppen: comp.lang.python | |
986 |
|
986 | |||
987 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
987 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
988 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
988 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
989 | # > <type 'dict'> |
|
989 | # > <type 'dict'> | |
990 | # > >>> print type(__builtins__) |
|
990 | # > >>> print type(__builtins__) | |
991 | # > <type 'module'> |
|
991 | # > <type 'module'> | |
992 | # > Is this difference in return value intentional? |
|
992 | # > Is this difference in return value intentional? | |
993 |
|
993 | |||
994 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
994 | # Well, it's documented that '__builtins__' can be either a dictionary | |
995 | # or a module, and it's been that way for a long time. Whether it's |
|
995 | # or a module, and it's been that way for a long time. Whether it's | |
996 | # intentional (or sensible), I don't know. In any case, the idea is |
|
996 | # intentional (or sensible), I don't know. In any case, the idea is | |
997 | # that if you need to access the built-in namespace directly, you |
|
997 | # that if you need to access the built-in namespace directly, you | |
998 | # should start with "import __builtin__" (note, no 's') which will |
|
998 | # should start with "import __builtin__" (note, no 's') which will | |
999 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
999 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
1000 |
|
1000 | |||
1001 | # These routines return a properly built module and dict as needed by |
|
1001 | # These routines return a properly built module and dict as needed by | |
1002 | # the rest of the code, and can also be used by extension writers to |
|
1002 | # the rest of the code, and can also be used by extension writers to | |
1003 | # generate properly initialized namespaces. |
|
1003 | # generate properly initialized namespaces. | |
1004 | if (user_ns is not None) or (user_module is not None): |
|
1004 | if (user_ns is not None) or (user_module is not None): | |
1005 | self.default_user_namespaces = False |
|
1005 | self.default_user_namespaces = False | |
1006 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1006 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) | |
1007 |
|
1007 | |||
1008 | # A record of hidden variables we have added to the user namespace, so |
|
1008 | # A record of hidden variables we have added to the user namespace, so | |
1009 | # we can list later only variables defined in actual interactive use. |
|
1009 | # we can list later only variables defined in actual interactive use. | |
1010 | self.user_ns_hidden = {} |
|
1010 | self.user_ns_hidden = {} | |
1011 |
|
1011 | |||
1012 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1012 | # Now that FakeModule produces a real module, we've run into a nasty | |
1013 | # problem: after script execution (via %run), the module where the user |
|
1013 | # problem: after script execution (via %run), the module where the user | |
1014 | # code ran is deleted. Now that this object is a true module (needed |
|
1014 | # code ran is deleted. Now that this object is a true module (needed | |
1015 | # so doctest and other tools work correctly), the Python module |
|
1015 | # so doctest and other tools work correctly), the Python module | |
1016 | # teardown mechanism runs over it, and sets to None every variable |
|
1016 | # teardown mechanism runs over it, and sets to None every variable | |
1017 | # present in that module. Top-level references to objects from the |
|
1017 | # present in that module. Top-level references to objects from the | |
1018 | # script survive, because the user_ns is updated with them. However, |
|
1018 | # script survive, because the user_ns is updated with them. However, | |
1019 | # calling functions defined in the script that use other things from |
|
1019 | # calling functions defined in the script that use other things from | |
1020 | # the script will fail, because the function's closure had references |
|
1020 | # the script will fail, because the function's closure had references | |
1021 | # to the original objects, which are now all None. So we must protect |
|
1021 | # to the original objects, which are now all None. So we must protect | |
1022 | # these modules from deletion by keeping a cache. |
|
1022 | # these modules from deletion by keeping a cache. | |
1023 | # |
|
1023 | # | |
1024 | # To avoid keeping stale modules around (we only need the one from the |
|
1024 | # To avoid keeping stale modules around (we only need the one from the | |
1025 | # last run), we use a dict keyed with the full path to the script, so |
|
1025 | # last run), we use a dict keyed with the full path to the script, so | |
1026 | # only the last version of the module is held in the cache. Note, |
|
1026 | # only the last version of the module is held in the cache. Note, | |
1027 | # however, that we must cache the module *namespace contents* (their |
|
1027 | # however, that we must cache the module *namespace contents* (their | |
1028 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1028 | # __dict__). Because if we try to cache the actual modules, old ones | |
1029 | # (uncached) could be destroyed while still holding references (such as |
|
1029 | # (uncached) could be destroyed while still holding references (such as | |
1030 | # those held by GUI objects that tend to be long-lived)> |
|
1030 | # those held by GUI objects that tend to be long-lived)> | |
1031 | # |
|
1031 | # | |
1032 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1032 | # The %reset command will flush this cache. See the cache_main_mod() | |
1033 | # and clear_main_mod_cache() methods for details on use. |
|
1033 | # and clear_main_mod_cache() methods for details on use. | |
1034 |
|
1034 | |||
1035 | # This is the cache used for 'main' namespaces |
|
1035 | # This is the cache used for 'main' namespaces | |
1036 | self._main_mod_cache = {} |
|
1036 | self._main_mod_cache = {} | |
1037 |
|
1037 | |||
1038 | # A table holding all the namespaces IPython deals with, so that |
|
1038 | # A table holding all the namespaces IPython deals with, so that | |
1039 | # introspection facilities can search easily. |
|
1039 | # introspection facilities can search easily. | |
1040 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1040 | self.ns_table = {'user_global':self.user_module.__dict__, | |
1041 | 'user_local':self.user_ns, |
|
1041 | 'user_local':self.user_ns, | |
1042 | 'builtin':builtin_mod.__dict__ |
|
1042 | 'builtin':builtin_mod.__dict__ | |
1043 | } |
|
1043 | } | |
1044 |
|
1044 | |||
1045 | @property |
|
1045 | @property | |
1046 | def user_global_ns(self): |
|
1046 | def user_global_ns(self): | |
1047 | return self.user_module.__dict__ |
|
1047 | return self.user_module.__dict__ | |
1048 |
|
1048 | |||
1049 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1049 | def prepare_user_module(self, user_module=None, user_ns=None): | |
1050 | """Prepare the module and namespace in which user code will be run. |
|
1050 | """Prepare the module and namespace in which user code will be run. | |
1051 |
|
1051 | |||
1052 | When IPython is started normally, both parameters are None: a new module |
|
1052 | When IPython is started normally, both parameters are None: a new module | |
1053 | is created automatically, and its __dict__ used as the namespace. |
|
1053 | is created automatically, and its __dict__ used as the namespace. | |
1054 |
|
1054 | |||
1055 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1055 | If only user_module is provided, its __dict__ is used as the namespace. | |
1056 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1056 | If only user_ns is provided, a dummy module is created, and user_ns | |
1057 | becomes the global namespace. If both are provided (as they may be |
|
1057 | becomes the global namespace. If both are provided (as they may be | |
1058 | when embedding), user_ns is the local namespace, and user_module |
|
1058 | when embedding), user_ns is the local namespace, and user_module | |
1059 | provides the global namespace. |
|
1059 | provides the global namespace. | |
1060 |
|
1060 | |||
1061 | Parameters |
|
1061 | Parameters | |
1062 | ---------- |
|
1062 | ---------- | |
1063 | user_module : module, optional |
|
1063 | user_module : module, optional | |
1064 | The current user module in which IPython is being run. If None, |
|
1064 | The current user module in which IPython is being run. If None, | |
1065 | a clean module will be created. |
|
1065 | a clean module will be created. | |
1066 | user_ns : dict, optional |
|
1066 | user_ns : dict, optional | |
1067 | A namespace in which to run interactive commands. |
|
1067 | A namespace in which to run interactive commands. | |
1068 |
|
1068 | |||
1069 | Returns |
|
1069 | Returns | |
1070 | ------- |
|
1070 | ------- | |
1071 | A tuple of user_module and user_ns, each properly initialised. |
|
1071 | A tuple of user_module and user_ns, each properly initialised. | |
1072 | """ |
|
1072 | """ | |
1073 | if user_module is None and user_ns is not None: |
|
1073 | if user_module is None and user_ns is not None: | |
1074 | user_ns.setdefault("__name__", "__main__") |
|
1074 | user_ns.setdefault("__name__", "__main__") | |
1075 | user_module = DummyMod() |
|
1075 | user_module = DummyMod() | |
1076 | user_module.__dict__ = user_ns |
|
1076 | user_module.__dict__ = user_ns | |
1077 |
|
1077 | |||
1078 | if user_module is None: |
|
1078 | if user_module is None: | |
1079 | user_module = types.ModuleType("__main__", |
|
1079 | user_module = types.ModuleType("__main__", | |
1080 | doc="Automatically created module for IPython interactive environment") |
|
1080 | doc="Automatically created module for IPython interactive environment") | |
1081 |
|
1081 | |||
1082 | # We must ensure that __builtin__ (without the final 's') is always |
|
1082 | # We must ensure that __builtin__ (without the final 's') is always | |
1083 | # available and pointing to the __builtin__ *module*. For more details: |
|
1083 | # available and pointing to the __builtin__ *module*. For more details: | |
1084 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1084 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1085 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1085 | user_module.__dict__.setdefault('__builtin__', builtin_mod) | |
1086 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1086 | user_module.__dict__.setdefault('__builtins__', builtin_mod) | |
1087 |
|
1087 | |||
1088 | if user_ns is None: |
|
1088 | if user_ns is None: | |
1089 | user_ns = user_module.__dict__ |
|
1089 | user_ns = user_module.__dict__ | |
1090 |
|
1090 | |||
1091 | return user_module, user_ns |
|
1091 | return user_module, user_ns | |
1092 |
|
1092 | |||
1093 | def init_sys_modules(self): |
|
1093 | def init_sys_modules(self): | |
1094 | # We need to insert into sys.modules something that looks like a |
|
1094 | # We need to insert into sys.modules something that looks like a | |
1095 | # module but which accesses the IPython namespace, for shelve and |
|
1095 | # module but which accesses the IPython namespace, for shelve and | |
1096 | # pickle to work interactively. Normally they rely on getting |
|
1096 | # pickle to work interactively. Normally they rely on getting | |
1097 | # everything out of __main__, but for embedding purposes each IPython |
|
1097 | # everything out of __main__, but for embedding purposes each IPython | |
1098 | # instance has its own private namespace, so we can't go shoving |
|
1098 | # instance has its own private namespace, so we can't go shoving | |
1099 | # everything into __main__. |
|
1099 | # everything into __main__. | |
1100 |
|
1100 | |||
1101 | # note, however, that we should only do this for non-embedded |
|
1101 | # note, however, that we should only do this for non-embedded | |
1102 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1102 | # ipythons, which really mimic the __main__.__dict__ with their own | |
1103 | # namespace. Embedded instances, on the other hand, should not do |
|
1103 | # namespace. Embedded instances, on the other hand, should not do | |
1104 | # this because they need to manage the user local/global namespaces |
|
1104 | # this because they need to manage the user local/global namespaces | |
1105 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1105 | # only, but they live within a 'normal' __main__ (meaning, they | |
1106 | # shouldn't overtake the execution environment of the script they're |
|
1106 | # shouldn't overtake the execution environment of the script they're | |
1107 | # embedded in). |
|
1107 | # embedded in). | |
1108 |
|
1108 | |||
1109 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1109 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1110 | main_name = self.user_module.__name__ |
|
1110 | main_name = self.user_module.__name__ | |
1111 | sys.modules[main_name] = self.user_module |
|
1111 | sys.modules[main_name] = self.user_module | |
1112 |
|
1112 | |||
1113 | def init_user_ns(self): |
|
1113 | def init_user_ns(self): | |
1114 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1114 | """Initialize all user-visible namespaces to their minimum defaults. | |
1115 |
|
1115 | |||
1116 | Certain history lists are also initialized here, as they effectively |
|
1116 | Certain history lists are also initialized here, as they effectively | |
1117 | act as user namespaces. |
|
1117 | act as user namespaces. | |
1118 |
|
1118 | |||
1119 | Notes |
|
1119 | Notes | |
1120 | ----- |
|
1120 | ----- | |
1121 | All data structures here are only filled in, they are NOT reset by this |
|
1121 | All data structures here are only filled in, they are NOT reset by this | |
1122 | method. If they were not empty before, data will simply be added to |
|
1122 | method. If they were not empty before, data will simply be added to | |
1123 | therm. |
|
1123 | therm. | |
1124 | """ |
|
1124 | """ | |
1125 | # This function works in two parts: first we put a few things in |
|
1125 | # This function works in two parts: first we put a few things in | |
1126 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1126 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1127 | # initial variables aren't shown by %who. After the sync, we add the |
|
1127 | # initial variables aren't shown by %who. After the sync, we add the | |
1128 | # rest of what we *do* want the user to see with %who even on a new |
|
1128 | # rest of what we *do* want the user to see with %who even on a new | |
1129 | # session (probably nothing, so they really only see their own stuff) |
|
1129 | # session (probably nothing, so they really only see their own stuff) | |
1130 |
|
1130 | |||
1131 | # The user dict must *always* have a __builtin__ reference to the |
|
1131 | # The user dict must *always* have a __builtin__ reference to the | |
1132 | # Python standard __builtin__ namespace, which must be imported. |
|
1132 | # Python standard __builtin__ namespace, which must be imported. | |
1133 | # This is so that certain operations in prompt evaluation can be |
|
1133 | # This is so that certain operations in prompt evaluation can be | |
1134 | # reliably executed with builtins. Note that we can NOT use |
|
1134 | # reliably executed with builtins. Note that we can NOT use | |
1135 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1135 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1136 | # module, and can even mutate at runtime, depending on the context |
|
1136 | # module, and can even mutate at runtime, depending on the context | |
1137 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1137 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1138 | # always a module object, though it must be explicitly imported. |
|
1138 | # always a module object, though it must be explicitly imported. | |
1139 |
|
1139 | |||
1140 | # For more details: |
|
1140 | # For more details: | |
1141 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1141 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1142 | ns = dict() |
|
1142 | ns = dict() | |
1143 |
|
1143 | |||
1144 | # make global variables for user access to the histories |
|
1144 | # make global variables for user access to the histories | |
1145 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1145 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1146 | ns['_oh'] = self.history_manager.output_hist |
|
1146 | ns['_oh'] = self.history_manager.output_hist | |
1147 | ns['_dh'] = self.history_manager.dir_hist |
|
1147 | ns['_dh'] = self.history_manager.dir_hist | |
1148 |
|
1148 | |||
1149 | ns['_sh'] = shadowns |
|
1149 | ns['_sh'] = shadowns | |
1150 |
|
1150 | |||
1151 | # user aliases to input and output histories. These shouldn't show up |
|
1151 | # user aliases to input and output histories. These shouldn't show up | |
1152 | # in %who, as they can have very large reprs. |
|
1152 | # in %who, as they can have very large reprs. | |
1153 | ns['In'] = self.history_manager.input_hist_parsed |
|
1153 | ns['In'] = self.history_manager.input_hist_parsed | |
1154 | ns['Out'] = self.history_manager.output_hist |
|
1154 | ns['Out'] = self.history_manager.output_hist | |
1155 |
|
1155 | |||
1156 | # Store myself as the public api!!! |
|
1156 | # Store myself as the public api!!! | |
1157 | ns['get_ipython'] = self.get_ipython |
|
1157 | ns['get_ipython'] = self.get_ipython | |
1158 |
|
1158 | |||
1159 | ns['exit'] = self.exiter |
|
1159 | ns['exit'] = self.exiter | |
1160 | ns['quit'] = self.exiter |
|
1160 | ns['quit'] = self.exiter | |
1161 |
|
1161 | |||
1162 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1162 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1163 | # by %who |
|
1163 | # by %who | |
1164 | self.user_ns_hidden.update(ns) |
|
1164 | self.user_ns_hidden.update(ns) | |
1165 |
|
1165 | |||
1166 | # Anything put into ns now would show up in %who. Think twice before |
|
1166 | # Anything put into ns now would show up in %who. Think twice before | |
1167 | # putting anything here, as we really want %who to show the user their |
|
1167 | # putting anything here, as we really want %who to show the user their | |
1168 | # stuff, not our variables. |
|
1168 | # stuff, not our variables. | |
1169 |
|
1169 | |||
1170 | # Finally, update the real user's namespace |
|
1170 | # Finally, update the real user's namespace | |
1171 | self.user_ns.update(ns) |
|
1171 | self.user_ns.update(ns) | |
1172 |
|
1172 | |||
1173 | @property |
|
1173 | @property | |
1174 | def all_ns_refs(self): |
|
1174 | def all_ns_refs(self): | |
1175 | """Get a list of references to all the namespace dictionaries in which |
|
1175 | """Get a list of references to all the namespace dictionaries in which | |
1176 | IPython might store a user-created object. |
|
1176 | IPython might store a user-created object. | |
1177 |
|
1177 | |||
1178 | Note that this does not include the displayhook, which also caches |
|
1178 | Note that this does not include the displayhook, which also caches | |
1179 | objects from the output.""" |
|
1179 | objects from the output.""" | |
1180 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1180 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ | |
1181 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1181 | [m.__dict__ for m in self._main_mod_cache.values()] | |
1182 |
|
1182 | |||
1183 | def reset(self, new_session=True): |
|
1183 | def reset(self, new_session=True): | |
1184 | """Clear all internal namespaces, and attempt to release references to |
|
1184 | """Clear all internal namespaces, and attempt to release references to | |
1185 | user objects. |
|
1185 | user objects. | |
1186 |
|
1186 | |||
1187 | If new_session is True, a new history session will be opened. |
|
1187 | If new_session is True, a new history session will be opened. | |
1188 | """ |
|
1188 | """ | |
1189 | # Clear histories |
|
1189 | # Clear histories | |
1190 | self.history_manager.reset(new_session) |
|
1190 | self.history_manager.reset(new_session) | |
1191 | # Reset counter used to index all histories |
|
1191 | # Reset counter used to index all histories | |
1192 | if new_session: |
|
1192 | if new_session: | |
1193 | self.execution_count = 1 |
|
1193 | self.execution_count = 1 | |
1194 |
|
1194 | |||
1195 | # Flush cached output items |
|
1195 | # Flush cached output items | |
1196 | if self.displayhook.do_full_cache: |
|
1196 | if self.displayhook.do_full_cache: | |
1197 | self.displayhook.flush() |
|
1197 | self.displayhook.flush() | |
1198 |
|
1198 | |||
1199 | # The main execution namespaces must be cleared very carefully, |
|
1199 | # The main execution namespaces must be cleared very carefully, | |
1200 | # skipping the deletion of the builtin-related keys, because doing so |
|
1200 | # skipping the deletion of the builtin-related keys, because doing so | |
1201 | # would cause errors in many object's __del__ methods. |
|
1201 | # would cause errors in many object's __del__ methods. | |
1202 | if self.user_ns is not self.user_global_ns: |
|
1202 | if self.user_ns is not self.user_global_ns: | |
1203 | self.user_ns.clear() |
|
1203 | self.user_ns.clear() | |
1204 | ns = self.user_global_ns |
|
1204 | ns = self.user_global_ns | |
1205 | drop_keys = set(ns.keys()) |
|
1205 | drop_keys = set(ns.keys()) | |
1206 | drop_keys.discard('__builtin__') |
|
1206 | drop_keys.discard('__builtin__') | |
1207 | drop_keys.discard('__builtins__') |
|
1207 | drop_keys.discard('__builtins__') | |
1208 | drop_keys.discard('__name__') |
|
1208 | drop_keys.discard('__name__') | |
1209 | for k in drop_keys: |
|
1209 | for k in drop_keys: | |
1210 | del ns[k] |
|
1210 | del ns[k] | |
1211 |
|
1211 | |||
1212 | self.user_ns_hidden.clear() |
|
1212 | self.user_ns_hidden.clear() | |
1213 |
|
1213 | |||
1214 | # Restore the user namespaces to minimal usability |
|
1214 | # Restore the user namespaces to minimal usability | |
1215 | self.init_user_ns() |
|
1215 | self.init_user_ns() | |
1216 |
|
1216 | |||
1217 | # Restore the default and user aliases |
|
1217 | # Restore the default and user aliases | |
1218 | self.alias_manager.clear_aliases() |
|
1218 | self.alias_manager.clear_aliases() | |
1219 | self.alias_manager.init_aliases() |
|
1219 | self.alias_manager.init_aliases() | |
1220 |
|
1220 | |||
1221 | # Flush the private list of module references kept for script |
|
1221 | # Flush the private list of module references kept for script | |
1222 | # execution protection |
|
1222 | # execution protection | |
1223 | self.clear_main_mod_cache() |
|
1223 | self.clear_main_mod_cache() | |
1224 |
|
1224 | |||
1225 | def del_var(self, varname, by_name=False): |
|
1225 | def del_var(self, varname, by_name=False): | |
1226 | """Delete a variable from the various namespaces, so that, as |
|
1226 | """Delete a variable from the various namespaces, so that, as | |
1227 | far as possible, we're not keeping any hidden references to it. |
|
1227 | far as possible, we're not keeping any hidden references to it. | |
1228 |
|
1228 | |||
1229 | Parameters |
|
1229 | Parameters | |
1230 | ---------- |
|
1230 | ---------- | |
1231 | varname : str |
|
1231 | varname : str | |
1232 | The name of the variable to delete. |
|
1232 | The name of the variable to delete. | |
1233 | by_name : bool |
|
1233 | by_name : bool | |
1234 | If True, delete variables with the given name in each |
|
1234 | If True, delete variables with the given name in each | |
1235 | namespace. If False (default), find the variable in the user |
|
1235 | namespace. If False (default), find the variable in the user | |
1236 | namespace, and delete references to it. |
|
1236 | namespace, and delete references to it. | |
1237 | """ |
|
1237 | """ | |
1238 | if varname in ('__builtin__', '__builtins__'): |
|
1238 | if varname in ('__builtin__', '__builtins__'): | |
1239 | raise ValueError("Refusing to delete %s" % varname) |
|
1239 | raise ValueError("Refusing to delete %s" % varname) | |
1240 |
|
1240 | |||
1241 | ns_refs = self.all_ns_refs |
|
1241 | ns_refs = self.all_ns_refs | |
1242 |
|
1242 | |||
1243 | if by_name: # Delete by name |
|
1243 | if by_name: # Delete by name | |
1244 | for ns in ns_refs: |
|
1244 | for ns in ns_refs: | |
1245 | try: |
|
1245 | try: | |
1246 | del ns[varname] |
|
1246 | del ns[varname] | |
1247 | except KeyError: |
|
1247 | except KeyError: | |
1248 | pass |
|
1248 | pass | |
1249 | else: # Delete by object |
|
1249 | else: # Delete by object | |
1250 | try: |
|
1250 | try: | |
1251 | obj = self.user_ns[varname] |
|
1251 | obj = self.user_ns[varname] | |
1252 | except KeyError: |
|
1252 | except KeyError: | |
1253 | raise NameError("name '%s' is not defined" % varname) |
|
1253 | raise NameError("name '%s' is not defined" % varname) | |
1254 | # Also check in output history |
|
1254 | # Also check in output history | |
1255 | ns_refs.append(self.history_manager.output_hist) |
|
1255 | ns_refs.append(self.history_manager.output_hist) | |
1256 | for ns in ns_refs: |
|
1256 | for ns in ns_refs: | |
1257 | to_delete = [n for n, o in ns.items() if o is obj] |
|
1257 | to_delete = [n for n, o in ns.items() if o is obj] | |
1258 | for name in to_delete: |
|
1258 | for name in to_delete: | |
1259 | del ns[name] |
|
1259 | del ns[name] | |
1260 |
|
1260 | |||
1261 | # displayhook keeps extra references, but not in a dictionary |
|
1261 | # displayhook keeps extra references, but not in a dictionary | |
1262 | for name in ('_', '__', '___'): |
|
1262 | for name in ('_', '__', '___'): | |
1263 | if getattr(self.displayhook, name) is obj: |
|
1263 | if getattr(self.displayhook, name) is obj: | |
1264 | setattr(self.displayhook, name, None) |
|
1264 | setattr(self.displayhook, name, None) | |
1265 |
|
1265 | |||
1266 | def reset_selective(self, regex=None): |
|
1266 | def reset_selective(self, regex=None): | |
1267 | """Clear selective variables from internal namespaces based on a |
|
1267 | """Clear selective variables from internal namespaces based on a | |
1268 | specified regular expression. |
|
1268 | specified regular expression. | |
1269 |
|
1269 | |||
1270 | Parameters |
|
1270 | Parameters | |
1271 | ---------- |
|
1271 | ---------- | |
1272 | regex : string or compiled pattern, optional |
|
1272 | regex : string or compiled pattern, optional | |
1273 | A regular expression pattern that will be used in searching |
|
1273 | A regular expression pattern that will be used in searching | |
1274 | variable names in the users namespaces. |
|
1274 | variable names in the users namespaces. | |
1275 | """ |
|
1275 | """ | |
1276 | if regex is not None: |
|
1276 | if regex is not None: | |
1277 | try: |
|
1277 | try: | |
1278 | m = re.compile(regex) |
|
1278 | m = re.compile(regex) | |
1279 | except TypeError: |
|
1279 | except TypeError: | |
1280 | raise TypeError('regex must be a string or compiled pattern') |
|
1280 | raise TypeError('regex must be a string or compiled pattern') | |
1281 | # Search for keys in each namespace that match the given regex |
|
1281 | # Search for keys in each namespace that match the given regex | |
1282 | # If a match is found, delete the key/value pair. |
|
1282 | # If a match is found, delete the key/value pair. | |
1283 | for ns in self.all_ns_refs: |
|
1283 | for ns in self.all_ns_refs: | |
1284 | for var in ns: |
|
1284 | for var in ns: | |
1285 | if m.search(var): |
|
1285 | if m.search(var): | |
1286 | del ns[var] |
|
1286 | del ns[var] | |
1287 |
|
1287 | |||
1288 | def push(self, variables, interactive=True): |
|
1288 | def push(self, variables, interactive=True): | |
1289 | """Inject a group of variables into the IPython user namespace. |
|
1289 | """Inject a group of variables into the IPython user namespace. | |
1290 |
|
1290 | |||
1291 | Parameters |
|
1291 | Parameters | |
1292 | ---------- |
|
1292 | ---------- | |
1293 | variables : dict, str or list/tuple of str |
|
1293 | variables : dict, str or list/tuple of str | |
1294 | The variables to inject into the user's namespace. If a dict, a |
|
1294 | The variables to inject into the user's namespace. If a dict, a | |
1295 | simple update is done. If a str, the string is assumed to have |
|
1295 | simple update is done. If a str, the string is assumed to have | |
1296 | variable names separated by spaces. A list/tuple of str can also |
|
1296 | variable names separated by spaces. A list/tuple of str can also | |
1297 | be used to give the variable names. If just the variable names are |
|
1297 | be used to give the variable names. If just the variable names are | |
1298 | give (list/tuple/str) then the variable values looked up in the |
|
1298 | give (list/tuple/str) then the variable values looked up in the | |
1299 | callers frame. |
|
1299 | callers frame. | |
1300 | interactive : bool |
|
1300 | interactive : bool | |
1301 | If True (default), the variables will be listed with the ``who`` |
|
1301 | If True (default), the variables will be listed with the ``who`` | |
1302 | magic. |
|
1302 | magic. | |
1303 | """ |
|
1303 | """ | |
1304 | vdict = None |
|
1304 | vdict = None | |
1305 |
|
1305 | |||
1306 | # We need a dict of name/value pairs to do namespace updates. |
|
1306 | # We need a dict of name/value pairs to do namespace updates. | |
1307 | if isinstance(variables, dict): |
|
1307 | if isinstance(variables, dict): | |
1308 | vdict = variables |
|
1308 | vdict = variables | |
1309 | elif isinstance(variables, (str, list, tuple)): |
|
1309 | elif isinstance(variables, (str, list, tuple)): | |
1310 | if isinstance(variables, str): |
|
1310 | if isinstance(variables, str): | |
1311 | vlist = variables.split() |
|
1311 | vlist = variables.split() | |
1312 | else: |
|
1312 | else: | |
1313 | vlist = variables |
|
1313 | vlist = variables | |
1314 | vdict = {} |
|
1314 | vdict = {} | |
1315 | cf = sys._getframe(1) |
|
1315 | cf = sys._getframe(1) | |
1316 | for name in vlist: |
|
1316 | for name in vlist: | |
1317 | try: |
|
1317 | try: | |
1318 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1318 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1319 | except: |
|
1319 | except: | |
1320 | print('Could not get variable %s from %s' % |
|
1320 | print('Could not get variable %s from %s' % | |
1321 | (name,cf.f_code.co_name)) |
|
1321 | (name,cf.f_code.co_name)) | |
1322 | else: |
|
1322 | else: | |
1323 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1323 | raise ValueError('variables must be a dict/str/list/tuple') | |
1324 |
|
1324 | |||
1325 | # Propagate variables to user namespace |
|
1325 | # Propagate variables to user namespace | |
1326 | self.user_ns.update(vdict) |
|
1326 | self.user_ns.update(vdict) | |
1327 |
|
1327 | |||
1328 | # And configure interactive visibility |
|
1328 | # And configure interactive visibility | |
1329 | user_ns_hidden = self.user_ns_hidden |
|
1329 | user_ns_hidden = self.user_ns_hidden | |
1330 | if interactive: |
|
1330 | if interactive: | |
1331 | for name in vdict: |
|
1331 | for name in vdict: | |
1332 | user_ns_hidden.pop(name, None) |
|
1332 | user_ns_hidden.pop(name, None) | |
1333 | else: |
|
1333 | else: | |
1334 | user_ns_hidden.update(vdict) |
|
1334 | user_ns_hidden.update(vdict) | |
1335 |
|
1335 | |||
1336 | def drop_by_id(self, variables): |
|
1336 | def drop_by_id(self, variables): | |
1337 | """Remove a dict of variables from the user namespace, if they are the |
|
1337 | """Remove a dict of variables from the user namespace, if they are the | |
1338 | same as the values in the dictionary. |
|
1338 | same as the values in the dictionary. | |
1339 |
|
1339 | |||
1340 | This is intended for use by extensions: variables that they've added can |
|
1340 | This is intended for use by extensions: variables that they've added can | |
1341 | be taken back out if they are unloaded, without removing any that the |
|
1341 | be taken back out if they are unloaded, without removing any that the | |
1342 | user has overwritten. |
|
1342 | user has overwritten. | |
1343 |
|
1343 | |||
1344 | Parameters |
|
1344 | Parameters | |
1345 | ---------- |
|
1345 | ---------- | |
1346 | variables : dict |
|
1346 | variables : dict | |
1347 | A dictionary mapping object names (as strings) to the objects. |
|
1347 | A dictionary mapping object names (as strings) to the objects. | |
1348 | """ |
|
1348 | """ | |
1349 | for name, obj in variables.items(): |
|
1349 | for name, obj in variables.items(): | |
1350 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1350 | if name in self.user_ns and self.user_ns[name] is obj: | |
1351 | del self.user_ns[name] |
|
1351 | del self.user_ns[name] | |
1352 | self.user_ns_hidden.pop(name, None) |
|
1352 | self.user_ns_hidden.pop(name, None) | |
1353 |
|
1353 | |||
1354 | #------------------------------------------------------------------------- |
|
1354 | #------------------------------------------------------------------------- | |
1355 | # Things related to object introspection |
|
1355 | # Things related to object introspection | |
1356 | #------------------------------------------------------------------------- |
|
1356 | #------------------------------------------------------------------------- | |
1357 |
|
1357 | |||
1358 | def _ofind(self, oname, namespaces=None): |
|
1358 | def _ofind(self, oname, namespaces=None): | |
1359 | """Find an object in the available namespaces. |
|
1359 | """Find an object in the available namespaces. | |
1360 |
|
1360 | |||
1361 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1361 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1362 |
|
1362 | |||
1363 | Has special code to detect magic functions. |
|
1363 | Has special code to detect magic functions. | |
1364 | """ |
|
1364 | """ | |
1365 | oname = oname.strip() |
|
1365 | oname = oname.strip() | |
1366 | #print '1- oname: <%r>' % oname # dbg |
|
1366 | #print '1- oname: <%r>' % oname # dbg | |
1367 | if not oname.startswith(ESC_MAGIC) and \ |
|
1367 | if not oname.startswith(ESC_MAGIC) and \ | |
1368 | not oname.startswith(ESC_MAGIC2) and \ |
|
1368 | not oname.startswith(ESC_MAGIC2) and \ | |
1369 | not py3compat.isidentifier(oname, dotted=True): |
|
1369 | not py3compat.isidentifier(oname, dotted=True): | |
1370 | return dict(found=False) |
|
1370 | return dict(found=False) | |
1371 |
|
1371 | |||
1372 | if namespaces is None: |
|
1372 | if namespaces is None: | |
1373 | # Namespaces to search in: |
|
1373 | # Namespaces to search in: | |
1374 | # Put them in a list. The order is important so that we |
|
1374 | # Put them in a list. The order is important so that we | |
1375 | # find things in the same order that Python finds them. |
|
1375 | # find things in the same order that Python finds them. | |
1376 | namespaces = [ ('Interactive', self.user_ns), |
|
1376 | namespaces = [ ('Interactive', self.user_ns), | |
1377 | ('Interactive (global)', self.user_global_ns), |
|
1377 | ('Interactive (global)', self.user_global_ns), | |
1378 | ('Python builtin', builtin_mod.__dict__), |
|
1378 | ('Python builtin', builtin_mod.__dict__), | |
1379 | ] |
|
1379 | ] | |
1380 |
|
1380 | |||
1381 | # initialize results to 'null' |
|
1381 | # initialize results to 'null' | |
1382 | found = False; obj = None; ospace = None; |
|
1382 | found = False; obj = None; ospace = None; | |
1383 | ismagic = False; isalias = False; parent = None |
|
1383 | ismagic = False; isalias = False; parent = None | |
1384 |
|
1384 | |||
1385 | # We need to special-case 'print', which as of python2.6 registers as a |
|
|||
1386 | # function but should only be treated as one if print_function was |
|
|||
1387 | # loaded with a future import. In this case, just bail. |
|
|||
1388 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
|||
1389 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
|||
1390 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
|||
1391 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
|||
1392 |
|
||||
1393 | # Look for the given name by splitting it in parts. If the head is |
|
1385 | # Look for the given name by splitting it in parts. If the head is | |
1394 | # found, then we look for all the remaining parts as members, and only |
|
1386 | # found, then we look for all the remaining parts as members, and only | |
1395 | # declare success if we can find them all. |
|
1387 | # declare success if we can find them all. | |
1396 | oname_parts = oname.split('.') |
|
1388 | oname_parts = oname.split('.') | |
1397 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1389 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1398 | for nsname,ns in namespaces: |
|
1390 | for nsname,ns in namespaces: | |
1399 | try: |
|
1391 | try: | |
1400 | obj = ns[oname_head] |
|
1392 | obj = ns[oname_head] | |
1401 | except KeyError: |
|
1393 | except KeyError: | |
1402 | continue |
|
1394 | continue | |
1403 | else: |
|
1395 | else: | |
1404 | #print 'oname_rest:', oname_rest # dbg |
|
1396 | #print 'oname_rest:', oname_rest # dbg | |
1405 | for idx, part in enumerate(oname_rest): |
|
1397 | for idx, part in enumerate(oname_rest): | |
1406 | try: |
|
1398 | try: | |
1407 | parent = obj |
|
1399 | parent = obj | |
1408 | # The last part is looked up in a special way to avoid |
|
1400 | # The last part is looked up in a special way to avoid | |
1409 | # descriptor invocation as it may raise or have side |
|
1401 | # descriptor invocation as it may raise or have side | |
1410 | # effects. |
|
1402 | # effects. | |
1411 | if idx == len(oname_rest) - 1: |
|
1403 | if idx == len(oname_rest) - 1: | |
1412 | obj = self._getattr_property(obj, part) |
|
1404 | obj = self._getattr_property(obj, part) | |
1413 | else: |
|
1405 | else: | |
1414 | obj = getattr(obj, part) |
|
1406 | obj = getattr(obj, part) | |
1415 | except: |
|
1407 | except: | |
1416 | # Blanket except b/c some badly implemented objects |
|
1408 | # Blanket except b/c some badly implemented objects | |
1417 | # allow __getattr__ to raise exceptions other than |
|
1409 | # allow __getattr__ to raise exceptions other than | |
1418 | # AttributeError, which then crashes IPython. |
|
1410 | # AttributeError, which then crashes IPython. | |
1419 | break |
|
1411 | break | |
1420 | else: |
|
1412 | else: | |
1421 | # If we finish the for loop (no break), we got all members |
|
1413 | # If we finish the for loop (no break), we got all members | |
1422 | found = True |
|
1414 | found = True | |
1423 | ospace = nsname |
|
1415 | ospace = nsname | |
1424 | break # namespace loop |
|
1416 | break # namespace loop | |
1425 |
|
1417 | |||
1426 | # Try to see if it's magic |
|
1418 | # Try to see if it's magic | |
1427 | if not found: |
|
1419 | if not found: | |
1428 | obj = None |
|
1420 | obj = None | |
1429 | if oname.startswith(ESC_MAGIC2): |
|
1421 | if oname.startswith(ESC_MAGIC2): | |
1430 | oname = oname.lstrip(ESC_MAGIC2) |
|
1422 | oname = oname.lstrip(ESC_MAGIC2) | |
1431 | obj = self.find_cell_magic(oname) |
|
1423 | obj = self.find_cell_magic(oname) | |
1432 | elif oname.startswith(ESC_MAGIC): |
|
1424 | elif oname.startswith(ESC_MAGIC): | |
1433 | oname = oname.lstrip(ESC_MAGIC) |
|
1425 | oname = oname.lstrip(ESC_MAGIC) | |
1434 | obj = self.find_line_magic(oname) |
|
1426 | obj = self.find_line_magic(oname) | |
1435 | else: |
|
1427 | else: | |
1436 | # search without prefix, so run? will find %run? |
|
1428 | # search without prefix, so run? will find %run? | |
1437 | obj = self.find_line_magic(oname) |
|
1429 | obj = self.find_line_magic(oname) | |
1438 | if obj is None: |
|
1430 | if obj is None: | |
1439 | obj = self.find_cell_magic(oname) |
|
1431 | obj = self.find_cell_magic(oname) | |
1440 | if obj is not None: |
|
1432 | if obj is not None: | |
1441 | found = True |
|
1433 | found = True | |
1442 | ospace = 'IPython internal' |
|
1434 | ospace = 'IPython internal' | |
1443 | ismagic = True |
|
1435 | ismagic = True | |
1444 | isalias = isinstance(obj, Alias) |
|
1436 | isalias = isinstance(obj, Alias) | |
1445 |
|
1437 | |||
1446 | # Last try: special-case some literals like '', [], {}, etc: |
|
1438 | # Last try: special-case some literals like '', [], {}, etc: | |
1447 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1439 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1448 | obj = eval(oname_head) |
|
1440 | obj = eval(oname_head) | |
1449 | found = True |
|
1441 | found = True | |
1450 | ospace = 'Interactive' |
|
1442 | ospace = 'Interactive' | |
1451 |
|
1443 | |||
1452 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1444 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1453 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1445 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1454 |
|
1446 | |||
1455 | @staticmethod |
|
1447 | @staticmethod | |
1456 | def _getattr_property(obj, attrname): |
|
1448 | def _getattr_property(obj, attrname): | |
1457 | """Property-aware getattr to use in object finding. |
|
1449 | """Property-aware getattr to use in object finding. | |
1458 |
|
1450 | |||
1459 | If attrname represents a property, return it unevaluated (in case it has |
|
1451 | If attrname represents a property, return it unevaluated (in case it has | |
1460 | side effects or raises an error. |
|
1452 | side effects or raises an error. | |
1461 |
|
1453 | |||
1462 | """ |
|
1454 | """ | |
1463 | if not isinstance(obj, type): |
|
1455 | if not isinstance(obj, type): | |
1464 | try: |
|
1456 | try: | |
1465 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1457 | # `getattr(type(obj), attrname)` is not guaranteed to return | |
1466 | # `obj`, but does so for property: |
|
1458 | # `obj`, but does so for property: | |
1467 | # |
|
1459 | # | |
1468 | # property.__get__(self, None, cls) -> self |
|
1460 | # property.__get__(self, None, cls) -> self | |
1469 | # |
|
1461 | # | |
1470 | # The universal alternative is to traverse the mro manually |
|
1462 | # The universal alternative is to traverse the mro manually | |
1471 | # searching for attrname in class dicts. |
|
1463 | # searching for attrname in class dicts. | |
1472 | attr = getattr(type(obj), attrname) |
|
1464 | attr = getattr(type(obj), attrname) | |
1473 | except AttributeError: |
|
1465 | except AttributeError: | |
1474 | pass |
|
1466 | pass | |
1475 | else: |
|
1467 | else: | |
1476 | # This relies on the fact that data descriptors (with both |
|
1468 | # This relies on the fact that data descriptors (with both | |
1477 | # __get__ & __set__ magic methods) take precedence over |
|
1469 | # __get__ & __set__ magic methods) take precedence over | |
1478 | # instance-level attributes: |
|
1470 | # instance-level attributes: | |
1479 | # |
|
1471 | # | |
1480 | # class A(object): |
|
1472 | # class A(object): | |
1481 | # @property |
|
1473 | # @property | |
1482 | # def foobar(self): return 123 |
|
1474 | # def foobar(self): return 123 | |
1483 | # a = A() |
|
1475 | # a = A() | |
1484 | # a.__dict__['foobar'] = 345 |
|
1476 | # a.__dict__['foobar'] = 345 | |
1485 | # a.foobar # == 123 |
|
1477 | # a.foobar # == 123 | |
1486 | # |
|
1478 | # | |
1487 | # So, a property may be returned right away. |
|
1479 | # So, a property may be returned right away. | |
1488 | if isinstance(attr, property): |
|
1480 | if isinstance(attr, property): | |
1489 | return attr |
|
1481 | return attr | |
1490 |
|
1482 | |||
1491 | # Nothing helped, fall back. |
|
1483 | # Nothing helped, fall back. | |
1492 | return getattr(obj, attrname) |
|
1484 | return getattr(obj, attrname) | |
1493 |
|
1485 | |||
1494 | def _object_find(self, oname, namespaces=None): |
|
1486 | def _object_find(self, oname, namespaces=None): | |
1495 | """Find an object and return a struct with info about it.""" |
|
1487 | """Find an object and return a struct with info about it.""" | |
1496 | return Struct(self._ofind(oname, namespaces)) |
|
1488 | return Struct(self._ofind(oname, namespaces)) | |
1497 |
|
1489 | |||
1498 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1490 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1499 | """Generic interface to the inspector system. |
|
1491 | """Generic interface to the inspector system. | |
1500 |
|
1492 | |||
1501 | This function is meant to be called by pdef, pdoc & friends. |
|
1493 | This function is meant to be called by pdef, pdoc & friends. | |
1502 | """ |
|
1494 | """ | |
1503 | info = self._object_find(oname, namespaces) |
|
1495 | info = self._object_find(oname, namespaces) | |
1504 | docformat = sphinxify if self.sphinxify_docstring else None |
|
1496 | docformat = sphinxify if self.sphinxify_docstring else None | |
1505 | if info.found: |
|
1497 | if info.found: | |
1506 | pmethod = getattr(self.inspector, meth) |
|
1498 | pmethod = getattr(self.inspector, meth) | |
1507 | # TODO: only apply format_screen to the plain/text repr of the mime |
|
1499 | # TODO: only apply format_screen to the plain/text repr of the mime | |
1508 | # bundle. |
|
1500 | # bundle. | |
1509 | formatter = format_screen if info.ismagic else docformat |
|
1501 | formatter = format_screen if info.ismagic else docformat | |
1510 | if meth == 'pdoc': |
|
1502 | if meth == 'pdoc': | |
1511 | pmethod(info.obj, oname, formatter) |
|
1503 | pmethod(info.obj, oname, formatter) | |
1512 | elif meth == 'pinfo': |
|
1504 | elif meth == 'pinfo': | |
1513 | pmethod(info.obj, oname, formatter, info, |
|
1505 | pmethod(info.obj, oname, formatter, info, | |
1514 | enable_html_pager=self.enable_html_pager, **kw) |
|
1506 | enable_html_pager=self.enable_html_pager, **kw) | |
1515 | else: |
|
1507 | else: | |
1516 | pmethod(info.obj, oname) |
|
1508 | pmethod(info.obj, oname) | |
1517 | else: |
|
1509 | else: | |
1518 | print('Object `%s` not found.' % oname) |
|
1510 | print('Object `%s` not found.' % oname) | |
1519 | return 'not found' # so callers can take other action |
|
1511 | return 'not found' # so callers can take other action | |
1520 |
|
1512 | |||
1521 | def object_inspect(self, oname, detail_level=0): |
|
1513 | def object_inspect(self, oname, detail_level=0): | |
1522 | """Get object info about oname""" |
|
1514 | """Get object info about oname""" | |
1523 | with self.builtin_trap: |
|
1515 | with self.builtin_trap: | |
1524 | info = self._object_find(oname) |
|
1516 | info = self._object_find(oname) | |
1525 | if info.found: |
|
1517 | if info.found: | |
1526 | return self.inspector.info(info.obj, oname, info=info, |
|
1518 | return self.inspector.info(info.obj, oname, info=info, | |
1527 | detail_level=detail_level |
|
1519 | detail_level=detail_level | |
1528 | ) |
|
1520 | ) | |
1529 | else: |
|
1521 | else: | |
1530 | return oinspect.object_info(name=oname, found=False) |
|
1522 | return oinspect.object_info(name=oname, found=False) | |
1531 |
|
1523 | |||
1532 | def object_inspect_text(self, oname, detail_level=0): |
|
1524 | def object_inspect_text(self, oname, detail_level=0): | |
1533 | """Get object info as formatted text""" |
|
1525 | """Get object info as formatted text""" | |
1534 | return self.object_inspect_mime(oname, detail_level)['text/plain'] |
|
1526 | return self.object_inspect_mime(oname, detail_level)['text/plain'] | |
1535 |
|
1527 | |||
1536 | def object_inspect_mime(self, oname, detail_level=0): |
|
1528 | def object_inspect_mime(self, oname, detail_level=0): | |
1537 | """Get object info as a mimebundle of formatted representations. |
|
1529 | """Get object info as a mimebundle of formatted representations. | |
1538 |
|
1530 | |||
1539 | A mimebundle is a dictionary, keyed by mime-type. |
|
1531 | A mimebundle is a dictionary, keyed by mime-type. | |
1540 | It must always have the key `'text/plain'`. |
|
1532 | It must always have the key `'text/plain'`. | |
1541 | """ |
|
1533 | """ | |
1542 | with self.builtin_trap: |
|
1534 | with self.builtin_trap: | |
1543 | info = self._object_find(oname) |
|
1535 | info = self._object_find(oname) | |
1544 | if info.found: |
|
1536 | if info.found: | |
1545 | return self.inspector._get_info(info.obj, oname, info=info, |
|
1537 | return self.inspector._get_info(info.obj, oname, info=info, | |
1546 | detail_level=detail_level |
|
1538 | detail_level=detail_level | |
1547 | ) |
|
1539 | ) | |
1548 | else: |
|
1540 | else: | |
1549 | raise KeyError(oname) |
|
1541 | raise KeyError(oname) | |
1550 |
|
1542 | |||
1551 | #------------------------------------------------------------------------- |
|
1543 | #------------------------------------------------------------------------- | |
1552 | # Things related to history management |
|
1544 | # Things related to history management | |
1553 | #------------------------------------------------------------------------- |
|
1545 | #------------------------------------------------------------------------- | |
1554 |
|
1546 | |||
1555 | def init_history(self): |
|
1547 | def init_history(self): | |
1556 | """Sets up the command history, and starts regular autosaves.""" |
|
1548 | """Sets up the command history, and starts regular autosaves.""" | |
1557 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1549 | self.history_manager = HistoryManager(shell=self, parent=self) | |
1558 | self.configurables.append(self.history_manager) |
|
1550 | self.configurables.append(self.history_manager) | |
1559 |
|
1551 | |||
1560 | #------------------------------------------------------------------------- |
|
1552 | #------------------------------------------------------------------------- | |
1561 | # Things related to exception handling and tracebacks (not debugging) |
|
1553 | # Things related to exception handling and tracebacks (not debugging) | |
1562 | #------------------------------------------------------------------------- |
|
1554 | #------------------------------------------------------------------------- | |
1563 |
|
1555 | |||
1564 | debugger_cls = Pdb |
|
1556 | debugger_cls = Pdb | |
1565 |
|
1557 | |||
1566 | def init_traceback_handlers(self, custom_exceptions): |
|
1558 | def init_traceback_handlers(self, custom_exceptions): | |
1567 | # Syntax error handler. |
|
1559 | # Syntax error handler. | |
1568 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) |
|
1560 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) | |
1569 |
|
1561 | |||
1570 | # The interactive one is initialized with an offset, meaning we always |
|
1562 | # The interactive one is initialized with an offset, meaning we always | |
1571 | # want to remove the topmost item in the traceback, which is our own |
|
1563 | # want to remove the topmost item in the traceback, which is our own | |
1572 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1564 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1573 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1565 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1574 | color_scheme='NoColor', |
|
1566 | color_scheme='NoColor', | |
1575 | tb_offset = 1, |
|
1567 | tb_offset = 1, | |
1576 | check_cache=check_linecache_ipython, |
|
1568 | check_cache=check_linecache_ipython, | |
1577 | debugger_cls=self.debugger_cls, parent=self) |
|
1569 | debugger_cls=self.debugger_cls, parent=self) | |
1578 |
|
1570 | |||
1579 | # The instance will store a pointer to the system-wide exception hook, |
|
1571 | # The instance will store a pointer to the system-wide exception hook, | |
1580 | # so that runtime code (such as magics) can access it. This is because |
|
1572 | # so that runtime code (such as magics) can access it. This is because | |
1581 | # during the read-eval loop, it may get temporarily overwritten. |
|
1573 | # during the read-eval loop, it may get temporarily overwritten. | |
1582 | self.sys_excepthook = sys.excepthook |
|
1574 | self.sys_excepthook = sys.excepthook | |
1583 |
|
1575 | |||
1584 | # and add any custom exception handlers the user may have specified |
|
1576 | # and add any custom exception handlers the user may have specified | |
1585 | self.set_custom_exc(*custom_exceptions) |
|
1577 | self.set_custom_exc(*custom_exceptions) | |
1586 |
|
1578 | |||
1587 | # Set the exception mode |
|
1579 | # Set the exception mode | |
1588 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1580 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1589 |
|
1581 | |||
1590 | def set_custom_exc(self, exc_tuple, handler): |
|
1582 | def set_custom_exc(self, exc_tuple, handler): | |
1591 | """set_custom_exc(exc_tuple, handler) |
|
1583 | """set_custom_exc(exc_tuple, handler) | |
1592 |
|
1584 | |||
1593 | Set a custom exception handler, which will be called if any of the |
|
1585 | Set a custom exception handler, which will be called if any of the | |
1594 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1586 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1595 | run_code() method). |
|
1587 | run_code() method). | |
1596 |
|
1588 | |||
1597 | Parameters |
|
1589 | Parameters | |
1598 | ---------- |
|
1590 | ---------- | |
1599 |
|
1591 | |||
1600 | exc_tuple : tuple of exception classes |
|
1592 | exc_tuple : tuple of exception classes | |
1601 | A *tuple* of exception classes, for which to call the defined |
|
1593 | A *tuple* of exception classes, for which to call the defined | |
1602 | handler. It is very important that you use a tuple, and NOT A |
|
1594 | handler. It is very important that you use a tuple, and NOT A | |
1603 | LIST here, because of the way Python's except statement works. If |
|
1595 | LIST here, because of the way Python's except statement works. If | |
1604 | you only want to trap a single exception, use a singleton tuple:: |
|
1596 | you only want to trap a single exception, use a singleton tuple:: | |
1605 |
|
1597 | |||
1606 | exc_tuple == (MyCustomException,) |
|
1598 | exc_tuple == (MyCustomException,) | |
1607 |
|
1599 | |||
1608 | handler : callable |
|
1600 | handler : callable | |
1609 | handler must have the following signature:: |
|
1601 | handler must have the following signature:: | |
1610 |
|
1602 | |||
1611 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1603 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1612 | ... |
|
1604 | ... | |
1613 | return structured_traceback |
|
1605 | return structured_traceback | |
1614 |
|
1606 | |||
1615 | Your handler must return a structured traceback (a list of strings), |
|
1607 | Your handler must return a structured traceback (a list of strings), | |
1616 | or None. |
|
1608 | or None. | |
1617 |
|
1609 | |||
1618 | This will be made into an instance method (via types.MethodType) |
|
1610 | This will be made into an instance method (via types.MethodType) | |
1619 | of IPython itself, and it will be called if any of the exceptions |
|
1611 | of IPython itself, and it will be called if any of the exceptions | |
1620 | listed in the exc_tuple are caught. If the handler is None, an |
|
1612 | listed in the exc_tuple are caught. If the handler is None, an | |
1621 | internal basic one is used, which just prints basic info. |
|
1613 | internal basic one is used, which just prints basic info. | |
1622 |
|
1614 | |||
1623 | To protect IPython from crashes, if your handler ever raises an |
|
1615 | To protect IPython from crashes, if your handler ever raises an | |
1624 | exception or returns an invalid result, it will be immediately |
|
1616 | exception or returns an invalid result, it will be immediately | |
1625 | disabled. |
|
1617 | disabled. | |
1626 |
|
1618 | |||
1627 | WARNING: by putting in your own exception handler into IPython's main |
|
1619 | WARNING: by putting in your own exception handler into IPython's main | |
1628 | execution loop, you run a very good chance of nasty crashes. This |
|
1620 | execution loop, you run a very good chance of nasty crashes. This | |
1629 | facility should only be used if you really know what you are doing.""" |
|
1621 | facility should only be used if you really know what you are doing.""" | |
1630 |
|
1622 | |||
1631 | assert type(exc_tuple)==type(()) , \ |
|
1623 | assert type(exc_tuple)==type(()) , \ | |
1632 | "The custom exceptions must be given AS A TUPLE." |
|
1624 | "The custom exceptions must be given AS A TUPLE." | |
1633 |
|
1625 | |||
1634 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1626 | def dummy_handler(self, etype, value, tb, tb_offset=None): | |
1635 | print('*** Simple custom exception handler ***') |
|
1627 | print('*** Simple custom exception handler ***') | |
1636 | print('Exception type :',etype) |
|
1628 | print('Exception type :',etype) | |
1637 | print('Exception value:',value) |
|
1629 | print('Exception value:',value) | |
1638 | print('Traceback :',tb) |
|
1630 | print('Traceback :',tb) | |
1639 | #print 'Source code :','\n'.join(self.buffer) |
|
1631 | #print 'Source code :','\n'.join(self.buffer) | |
1640 |
|
1632 | |||
1641 | def validate_stb(stb): |
|
1633 | def validate_stb(stb): | |
1642 | """validate structured traceback return type |
|
1634 | """validate structured traceback return type | |
1643 |
|
1635 | |||
1644 | return type of CustomTB *should* be a list of strings, but allow |
|
1636 | return type of CustomTB *should* be a list of strings, but allow | |
1645 | single strings or None, which are harmless. |
|
1637 | single strings or None, which are harmless. | |
1646 |
|
1638 | |||
1647 | This function will *always* return a list of strings, |
|
1639 | This function will *always* return a list of strings, | |
1648 | and will raise a TypeError if stb is inappropriate. |
|
1640 | and will raise a TypeError if stb is inappropriate. | |
1649 | """ |
|
1641 | """ | |
1650 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1642 | msg = "CustomTB must return list of strings, not %r" % stb | |
1651 | if stb is None: |
|
1643 | if stb is None: | |
1652 | return [] |
|
1644 | return [] | |
1653 | elif isinstance(stb, str): |
|
1645 | elif isinstance(stb, str): | |
1654 | return [stb] |
|
1646 | return [stb] | |
1655 | elif not isinstance(stb, list): |
|
1647 | elif not isinstance(stb, list): | |
1656 | raise TypeError(msg) |
|
1648 | raise TypeError(msg) | |
1657 | # it's a list |
|
1649 | # it's a list | |
1658 | for line in stb: |
|
1650 | for line in stb: | |
1659 | # check every element |
|
1651 | # check every element | |
1660 | if not isinstance(line, str): |
|
1652 | if not isinstance(line, str): | |
1661 | raise TypeError(msg) |
|
1653 | raise TypeError(msg) | |
1662 | return stb |
|
1654 | return stb | |
1663 |
|
1655 | |||
1664 | if handler is None: |
|
1656 | if handler is None: | |
1665 | wrapped = dummy_handler |
|
1657 | wrapped = dummy_handler | |
1666 | else: |
|
1658 | else: | |
1667 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1659 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1668 | """wrap CustomTB handler, to protect IPython from user code |
|
1660 | """wrap CustomTB handler, to protect IPython from user code | |
1669 |
|
1661 | |||
1670 | This makes it harder (but not impossible) for custom exception |
|
1662 | This makes it harder (but not impossible) for custom exception | |
1671 | handlers to crash IPython. |
|
1663 | handlers to crash IPython. | |
1672 | """ |
|
1664 | """ | |
1673 | try: |
|
1665 | try: | |
1674 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1666 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1675 | return validate_stb(stb) |
|
1667 | return validate_stb(stb) | |
1676 | except: |
|
1668 | except: | |
1677 | # clear custom handler immediately |
|
1669 | # clear custom handler immediately | |
1678 | self.set_custom_exc((), None) |
|
1670 | self.set_custom_exc((), None) | |
1679 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1671 | print("Custom TB Handler failed, unregistering", file=sys.stderr) | |
1680 | # show the exception in handler first |
|
1672 | # show the exception in handler first | |
1681 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1673 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1682 | print(self.InteractiveTB.stb2text(stb)) |
|
1674 | print(self.InteractiveTB.stb2text(stb)) | |
1683 | print("The original exception:") |
|
1675 | print("The original exception:") | |
1684 | stb = self.InteractiveTB.structured_traceback( |
|
1676 | stb = self.InteractiveTB.structured_traceback( | |
1685 | (etype,value,tb), tb_offset=tb_offset |
|
1677 | (etype,value,tb), tb_offset=tb_offset | |
1686 | ) |
|
1678 | ) | |
1687 | return stb |
|
1679 | return stb | |
1688 |
|
1680 | |||
1689 | self.CustomTB = types.MethodType(wrapped,self) |
|
1681 | self.CustomTB = types.MethodType(wrapped,self) | |
1690 | self.custom_exceptions = exc_tuple |
|
1682 | self.custom_exceptions = exc_tuple | |
1691 |
|
1683 | |||
1692 | def excepthook(self, etype, value, tb): |
|
1684 | def excepthook(self, etype, value, tb): | |
1693 | """One more defense for GUI apps that call sys.excepthook. |
|
1685 | """One more defense for GUI apps that call sys.excepthook. | |
1694 |
|
1686 | |||
1695 | GUI frameworks like wxPython trap exceptions and call |
|
1687 | GUI frameworks like wxPython trap exceptions and call | |
1696 | sys.excepthook themselves. I guess this is a feature that |
|
1688 | sys.excepthook themselves. I guess this is a feature that | |
1697 | enables them to keep running after exceptions that would |
|
1689 | enables them to keep running after exceptions that would | |
1698 | otherwise kill their mainloop. This is a bother for IPython |
|
1690 | otherwise kill their mainloop. This is a bother for IPython | |
1699 | which excepts to catch all of the program exceptions with a try: |
|
1691 | which excepts to catch all of the program exceptions with a try: | |
1700 | except: statement. |
|
1692 | except: statement. | |
1701 |
|
1693 | |||
1702 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1694 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1703 | any app directly invokes sys.excepthook, it will look to the user like |
|
1695 | any app directly invokes sys.excepthook, it will look to the user like | |
1704 | IPython crashed. In order to work around this, we can disable the |
|
1696 | IPython crashed. In order to work around this, we can disable the | |
1705 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1697 | CrashHandler and replace it with this excepthook instead, which prints a | |
1706 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1698 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1707 | call sys.excepthook will generate a regular-looking exception from |
|
1699 | call sys.excepthook will generate a regular-looking exception from | |
1708 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1700 | IPython, and the CrashHandler will only be triggered by real IPython | |
1709 | crashes. |
|
1701 | crashes. | |
1710 |
|
1702 | |||
1711 | This hook should be used sparingly, only in places which are not likely |
|
1703 | This hook should be used sparingly, only in places which are not likely | |
1712 | to be true IPython errors. |
|
1704 | to be true IPython errors. | |
1713 | """ |
|
1705 | """ | |
1714 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1706 | self.showtraceback((etype, value, tb), tb_offset=0) | |
1715 |
|
1707 | |||
1716 | def _get_exc_info(self, exc_tuple=None): |
|
1708 | def _get_exc_info(self, exc_tuple=None): | |
1717 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1709 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. | |
1718 |
|
1710 | |||
1719 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1711 | Ensures sys.last_type,value,traceback hold the exc_info we found, | |
1720 | from whichever source. |
|
1712 | from whichever source. | |
1721 |
|
1713 | |||
1722 | raises ValueError if none of these contain any information |
|
1714 | raises ValueError if none of these contain any information | |
1723 | """ |
|
1715 | """ | |
1724 | if exc_tuple is None: |
|
1716 | if exc_tuple is None: | |
1725 | etype, value, tb = sys.exc_info() |
|
1717 | etype, value, tb = sys.exc_info() | |
1726 | else: |
|
1718 | else: | |
1727 | etype, value, tb = exc_tuple |
|
1719 | etype, value, tb = exc_tuple | |
1728 |
|
1720 | |||
1729 | if etype is None: |
|
1721 | if etype is None: | |
1730 | if hasattr(sys, 'last_type'): |
|
1722 | if hasattr(sys, 'last_type'): | |
1731 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1723 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1732 | sys.last_traceback |
|
1724 | sys.last_traceback | |
1733 |
|
1725 | |||
1734 | if etype is None: |
|
1726 | if etype is None: | |
1735 | raise ValueError("No exception to find") |
|
1727 | raise ValueError("No exception to find") | |
1736 |
|
1728 | |||
1737 | # Now store the exception info in sys.last_type etc. |
|
1729 | # Now store the exception info in sys.last_type etc. | |
1738 | # WARNING: these variables are somewhat deprecated and not |
|
1730 | # WARNING: these variables are somewhat deprecated and not | |
1739 | # necessarily safe to use in a threaded environment, but tools |
|
1731 | # necessarily safe to use in a threaded environment, but tools | |
1740 | # like pdb depend on their existence, so let's set them. If we |
|
1732 | # like pdb depend on their existence, so let's set them. If we | |
1741 | # find problems in the field, we'll need to revisit their use. |
|
1733 | # find problems in the field, we'll need to revisit their use. | |
1742 | sys.last_type = etype |
|
1734 | sys.last_type = etype | |
1743 | sys.last_value = value |
|
1735 | sys.last_value = value | |
1744 | sys.last_traceback = tb |
|
1736 | sys.last_traceback = tb | |
1745 |
|
1737 | |||
1746 | return etype, value, tb |
|
1738 | return etype, value, tb | |
1747 |
|
1739 | |||
1748 | def show_usage_error(self, exc): |
|
1740 | def show_usage_error(self, exc): | |
1749 | """Show a short message for UsageErrors |
|
1741 | """Show a short message for UsageErrors | |
1750 |
|
1742 | |||
1751 | These are special exceptions that shouldn't show a traceback. |
|
1743 | These are special exceptions that shouldn't show a traceback. | |
1752 | """ |
|
1744 | """ | |
1753 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1745 | print("UsageError: %s" % exc, file=sys.stderr) | |
1754 |
|
1746 | |||
1755 | def get_exception_only(self, exc_tuple=None): |
|
1747 | def get_exception_only(self, exc_tuple=None): | |
1756 | """ |
|
1748 | """ | |
1757 | Return as a string (ending with a newline) the exception that |
|
1749 | Return as a string (ending with a newline) the exception that | |
1758 | just occurred, without any traceback. |
|
1750 | just occurred, without any traceback. | |
1759 | """ |
|
1751 | """ | |
1760 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1752 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1761 | msg = traceback.format_exception_only(etype, value) |
|
1753 | msg = traceback.format_exception_only(etype, value) | |
1762 | return ''.join(msg) |
|
1754 | return ''.join(msg) | |
1763 |
|
1755 | |||
1764 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1756 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, | |
1765 | exception_only=False): |
|
1757 | exception_only=False): | |
1766 | """Display the exception that just occurred. |
|
1758 | """Display the exception that just occurred. | |
1767 |
|
1759 | |||
1768 | If nothing is known about the exception, this is the method which |
|
1760 | If nothing is known about the exception, this is the method which | |
1769 | should be used throughout the code for presenting user tracebacks, |
|
1761 | should be used throughout the code for presenting user tracebacks, | |
1770 | rather than directly invoking the InteractiveTB object. |
|
1762 | rather than directly invoking the InteractiveTB object. | |
1771 |
|
1763 | |||
1772 | A specific showsyntaxerror() also exists, but this method can take |
|
1764 | A specific showsyntaxerror() also exists, but this method can take | |
1773 | care of calling it if needed, so unless you are explicitly catching a |
|
1765 | care of calling it if needed, so unless you are explicitly catching a | |
1774 | SyntaxError exception, don't try to analyze the stack manually and |
|
1766 | SyntaxError exception, don't try to analyze the stack manually and | |
1775 | simply call this method.""" |
|
1767 | simply call this method.""" | |
1776 |
|
1768 | |||
1777 | try: |
|
1769 | try: | |
1778 | try: |
|
1770 | try: | |
1779 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1771 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1780 | except ValueError: |
|
1772 | except ValueError: | |
1781 | print('No traceback available to show.', file=sys.stderr) |
|
1773 | print('No traceback available to show.', file=sys.stderr) | |
1782 | return |
|
1774 | return | |
1783 |
|
1775 | |||
1784 | if issubclass(etype, SyntaxError): |
|
1776 | if issubclass(etype, SyntaxError): | |
1785 | # Though this won't be called by syntax errors in the input |
|
1777 | # Though this won't be called by syntax errors in the input | |
1786 | # line, there may be SyntaxError cases with imported code. |
|
1778 | # line, there may be SyntaxError cases with imported code. | |
1787 | self.showsyntaxerror(filename) |
|
1779 | self.showsyntaxerror(filename) | |
1788 | elif etype is UsageError: |
|
1780 | elif etype is UsageError: | |
1789 | self.show_usage_error(value) |
|
1781 | self.show_usage_error(value) | |
1790 | else: |
|
1782 | else: | |
1791 | if exception_only: |
|
1783 | if exception_only: | |
1792 | stb = ['An exception has occurred, use %tb to see ' |
|
1784 | stb = ['An exception has occurred, use %tb to see ' | |
1793 | 'the full traceback.\n'] |
|
1785 | 'the full traceback.\n'] | |
1794 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1786 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1795 | value)) |
|
1787 | value)) | |
1796 | else: |
|
1788 | else: | |
1797 | try: |
|
1789 | try: | |
1798 | # Exception classes can customise their traceback - we |
|
1790 | # Exception classes can customise their traceback - we | |
1799 | # use this in IPython.parallel for exceptions occurring |
|
1791 | # use this in IPython.parallel for exceptions occurring | |
1800 | # in the engines. This should return a list of strings. |
|
1792 | # in the engines. This should return a list of strings. | |
1801 | stb = value._render_traceback_() |
|
1793 | stb = value._render_traceback_() | |
1802 | except Exception: |
|
1794 | except Exception: | |
1803 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1795 | stb = self.InteractiveTB.structured_traceback(etype, | |
1804 | value, tb, tb_offset=tb_offset) |
|
1796 | value, tb, tb_offset=tb_offset) | |
1805 |
|
1797 | |||
1806 | self._showtraceback(etype, value, stb) |
|
1798 | self._showtraceback(etype, value, stb) | |
1807 | if self.call_pdb: |
|
1799 | if self.call_pdb: | |
1808 | # drop into debugger |
|
1800 | # drop into debugger | |
1809 | self.debugger(force=True) |
|
1801 | self.debugger(force=True) | |
1810 | return |
|
1802 | return | |
1811 |
|
1803 | |||
1812 | # Actually show the traceback |
|
1804 | # Actually show the traceback | |
1813 | self._showtraceback(etype, value, stb) |
|
1805 | self._showtraceback(etype, value, stb) | |
1814 |
|
1806 | |||
1815 | except KeyboardInterrupt: |
|
1807 | except KeyboardInterrupt: | |
1816 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
1808 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
1817 |
|
1809 | |||
1818 | def _showtraceback(self, etype, evalue, stb): |
|
1810 | def _showtraceback(self, etype, evalue, stb): | |
1819 | """Actually show a traceback. |
|
1811 | """Actually show a traceback. | |
1820 |
|
1812 | |||
1821 | Subclasses may override this method to put the traceback on a different |
|
1813 | Subclasses may override this method to put the traceback on a different | |
1822 | place, like a side channel. |
|
1814 | place, like a side channel. | |
1823 | """ |
|
1815 | """ | |
1824 | print(self.InteractiveTB.stb2text(stb)) |
|
1816 | print(self.InteractiveTB.stb2text(stb)) | |
1825 |
|
1817 | |||
1826 | def showsyntaxerror(self, filename=None): |
|
1818 | def showsyntaxerror(self, filename=None): | |
1827 | """Display the syntax error that just occurred. |
|
1819 | """Display the syntax error that just occurred. | |
1828 |
|
1820 | |||
1829 | This doesn't display a stack trace because there isn't one. |
|
1821 | This doesn't display a stack trace because there isn't one. | |
1830 |
|
1822 | |||
1831 | If a filename is given, it is stuffed in the exception instead |
|
1823 | If a filename is given, it is stuffed in the exception instead | |
1832 | of what was there before (because Python's parser always uses |
|
1824 | of what was there before (because Python's parser always uses | |
1833 | "<string>" when reading from a string). |
|
1825 | "<string>" when reading from a string). | |
1834 | """ |
|
1826 | """ | |
1835 | etype, value, last_traceback = self._get_exc_info() |
|
1827 | etype, value, last_traceback = self._get_exc_info() | |
1836 |
|
1828 | |||
1837 | if filename and issubclass(etype, SyntaxError): |
|
1829 | if filename and issubclass(etype, SyntaxError): | |
1838 | try: |
|
1830 | try: | |
1839 | value.filename = filename |
|
1831 | value.filename = filename | |
1840 | except: |
|
1832 | except: | |
1841 | # Not the format we expect; leave it alone |
|
1833 | # Not the format we expect; leave it alone | |
1842 | pass |
|
1834 | pass | |
1843 |
|
1835 | |||
1844 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1836 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1845 | self._showtraceback(etype, value, stb) |
|
1837 | self._showtraceback(etype, value, stb) | |
1846 |
|
1838 | |||
1847 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1839 | # This is overridden in TerminalInteractiveShell to show a message about | |
1848 | # the %paste magic. |
|
1840 | # the %paste magic. | |
1849 | def showindentationerror(self): |
|
1841 | def showindentationerror(self): | |
1850 | """Called by run_cell when there's an IndentationError in code entered |
|
1842 | """Called by run_cell when there's an IndentationError in code entered | |
1851 | at the prompt. |
|
1843 | at the prompt. | |
1852 |
|
1844 | |||
1853 | This is overridden in TerminalInteractiveShell to show a message about |
|
1845 | This is overridden in TerminalInteractiveShell to show a message about | |
1854 | the %paste magic.""" |
|
1846 | the %paste magic.""" | |
1855 | self.showsyntaxerror() |
|
1847 | self.showsyntaxerror() | |
1856 |
|
1848 | |||
1857 | #------------------------------------------------------------------------- |
|
1849 | #------------------------------------------------------------------------- | |
1858 | # Things related to readline |
|
1850 | # Things related to readline | |
1859 | #------------------------------------------------------------------------- |
|
1851 | #------------------------------------------------------------------------- | |
1860 |
|
1852 | |||
1861 | def init_readline(self): |
|
1853 | def init_readline(self): | |
1862 | """DEPRECATED |
|
1854 | """DEPRECATED | |
1863 |
|
1855 | |||
1864 | Moved to terminal subclass, here only to simplify the init logic.""" |
|
1856 | Moved to terminal subclass, here only to simplify the init logic.""" | |
1865 | # Set a number of methods that depend on readline to be no-op |
|
1857 | # Set a number of methods that depend on readline to be no-op | |
1866 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', |
|
1858 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', | |
1867 | DeprecationWarning, stacklevel=2) |
|
1859 | DeprecationWarning, stacklevel=2) | |
1868 | self.set_custom_completer = no_op |
|
1860 | self.set_custom_completer = no_op | |
1869 |
|
1861 | |||
1870 | @skip_doctest |
|
1862 | @skip_doctest | |
1871 | def set_next_input(self, s, replace=False): |
|
1863 | def set_next_input(self, s, replace=False): | |
1872 | """ Sets the 'default' input string for the next command line. |
|
1864 | """ Sets the 'default' input string for the next command line. | |
1873 |
|
1865 | |||
1874 | Example:: |
|
1866 | Example:: | |
1875 |
|
1867 | |||
1876 | In [1]: _ip.set_next_input("Hello Word") |
|
1868 | In [1]: _ip.set_next_input("Hello Word") | |
1877 | In [2]: Hello Word_ # cursor is here |
|
1869 | In [2]: Hello Word_ # cursor is here | |
1878 | """ |
|
1870 | """ | |
1879 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1871 | self.rl_next_input = py3compat.cast_bytes_py2(s) | |
1880 |
|
1872 | |||
1881 | def _indent_current_str(self): |
|
1873 | def _indent_current_str(self): | |
1882 | """return the current level of indentation as a string""" |
|
1874 | """return the current level of indentation as a string""" | |
1883 | return self.input_splitter.indent_spaces * ' ' |
|
1875 | return self.input_splitter.indent_spaces * ' ' | |
1884 |
|
1876 | |||
1885 | #------------------------------------------------------------------------- |
|
1877 | #------------------------------------------------------------------------- | |
1886 | # Things related to text completion |
|
1878 | # Things related to text completion | |
1887 | #------------------------------------------------------------------------- |
|
1879 | #------------------------------------------------------------------------- | |
1888 |
|
1880 | |||
1889 | def init_completer(self): |
|
1881 | def init_completer(self): | |
1890 | """Initialize the completion machinery. |
|
1882 | """Initialize the completion machinery. | |
1891 |
|
1883 | |||
1892 | This creates completion machinery that can be used by client code, |
|
1884 | This creates completion machinery that can be used by client code, | |
1893 | either interactively in-process (typically triggered by the readline |
|
1885 | either interactively in-process (typically triggered by the readline | |
1894 | library), programmatically (such as in test suites) or out-of-process |
|
1886 | library), programmatically (such as in test suites) or out-of-process | |
1895 | (typically over the network by remote frontends). |
|
1887 | (typically over the network by remote frontends). | |
1896 | """ |
|
1888 | """ | |
1897 | from IPython.core.completer import IPCompleter |
|
1889 | from IPython.core.completer import IPCompleter | |
1898 | from IPython.core.completerlib import (module_completer, |
|
1890 | from IPython.core.completerlib import (module_completer, | |
1899 | magic_run_completer, cd_completer, reset_completer) |
|
1891 | magic_run_completer, cd_completer, reset_completer) | |
1900 |
|
1892 | |||
1901 | self.Completer = IPCompleter(shell=self, |
|
1893 | self.Completer = IPCompleter(shell=self, | |
1902 | namespace=self.user_ns, |
|
1894 | namespace=self.user_ns, | |
1903 | global_namespace=self.user_global_ns, |
|
1895 | global_namespace=self.user_global_ns, | |
1904 | parent=self, |
|
1896 | parent=self, | |
1905 | ) |
|
1897 | ) | |
1906 | self.configurables.append(self.Completer) |
|
1898 | self.configurables.append(self.Completer) | |
1907 |
|
1899 | |||
1908 | # Add custom completers to the basic ones built into IPCompleter |
|
1900 | # Add custom completers to the basic ones built into IPCompleter | |
1909 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1901 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1910 | self.strdispatchers['complete_command'] = sdisp |
|
1902 | self.strdispatchers['complete_command'] = sdisp | |
1911 | self.Completer.custom_completers = sdisp |
|
1903 | self.Completer.custom_completers = sdisp | |
1912 |
|
1904 | |||
1913 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1905 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1914 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1906 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1915 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
1907 | self.set_hook('complete_command', module_completer, str_key = '%aimport') | |
1916 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1908 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1917 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1909 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1918 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1910 | self.set_hook('complete_command', reset_completer, str_key = '%reset') | |
1919 |
|
1911 | |||
1920 |
|
1912 | |||
1921 | def complete(self, text, line=None, cursor_pos=None): |
|
1913 | def complete(self, text, line=None, cursor_pos=None): | |
1922 | """Return the completed text and a list of completions. |
|
1914 | """Return the completed text and a list of completions. | |
1923 |
|
1915 | |||
1924 | Parameters |
|
1916 | Parameters | |
1925 | ---------- |
|
1917 | ---------- | |
1926 |
|
1918 | |||
1927 | text : string |
|
1919 | text : string | |
1928 | A string of text to be completed on. It can be given as empty and |
|
1920 | A string of text to be completed on. It can be given as empty and | |
1929 | instead a line/position pair are given. In this case, the |
|
1921 | instead a line/position pair are given. In this case, the | |
1930 | completer itself will split the line like readline does. |
|
1922 | completer itself will split the line like readline does. | |
1931 |
|
1923 | |||
1932 | line : string, optional |
|
1924 | line : string, optional | |
1933 | The complete line that text is part of. |
|
1925 | The complete line that text is part of. | |
1934 |
|
1926 | |||
1935 | cursor_pos : int, optional |
|
1927 | cursor_pos : int, optional | |
1936 | The position of the cursor on the input line. |
|
1928 | The position of the cursor on the input line. | |
1937 |
|
1929 | |||
1938 | Returns |
|
1930 | Returns | |
1939 | ------- |
|
1931 | ------- | |
1940 | text : string |
|
1932 | text : string | |
1941 | The actual text that was completed. |
|
1933 | The actual text that was completed. | |
1942 |
|
1934 | |||
1943 | matches : list |
|
1935 | matches : list | |
1944 | A sorted list with all possible completions. |
|
1936 | A sorted list with all possible completions. | |
1945 |
|
1937 | |||
1946 | The optional arguments allow the completion to take more context into |
|
1938 | The optional arguments allow the completion to take more context into | |
1947 | account, and are part of the low-level completion API. |
|
1939 | account, and are part of the low-level completion API. | |
1948 |
|
1940 | |||
1949 | This is a wrapper around the completion mechanism, similar to what |
|
1941 | This is a wrapper around the completion mechanism, similar to what | |
1950 | readline does at the command line when the TAB key is hit. By |
|
1942 | readline does at the command line when the TAB key is hit. By | |
1951 | exposing it as a method, it can be used by other non-readline |
|
1943 | exposing it as a method, it can be used by other non-readline | |
1952 | environments (such as GUIs) for text completion. |
|
1944 | environments (such as GUIs) for text completion. | |
1953 |
|
1945 | |||
1954 | Simple usage example: |
|
1946 | Simple usage example: | |
1955 |
|
1947 | |||
1956 | In [1]: x = 'hello' |
|
1948 | In [1]: x = 'hello' | |
1957 |
|
1949 | |||
1958 | In [2]: _ip.complete('x.l') |
|
1950 | In [2]: _ip.complete('x.l') | |
1959 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1951 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1960 | """ |
|
1952 | """ | |
1961 |
|
1953 | |||
1962 | # Inject names into __builtin__ so we can complete on the added names. |
|
1954 | # Inject names into __builtin__ so we can complete on the added names. | |
1963 | with self.builtin_trap: |
|
1955 | with self.builtin_trap: | |
1964 | return self.Completer.complete(text, line, cursor_pos) |
|
1956 | return self.Completer.complete(text, line, cursor_pos) | |
1965 |
|
1957 | |||
1966 | def set_custom_completer(self, completer, pos=0): |
|
1958 | def set_custom_completer(self, completer, pos=0): | |
1967 | """Adds a new custom completer function. |
|
1959 | """Adds a new custom completer function. | |
1968 |
|
1960 | |||
1969 | The position argument (defaults to 0) is the index in the completers |
|
1961 | The position argument (defaults to 0) is the index in the completers | |
1970 | list where you want the completer to be inserted.""" |
|
1962 | list where you want the completer to be inserted.""" | |
1971 |
|
1963 | |||
1972 | newcomp = types.MethodType(completer,self.Completer) |
|
1964 | newcomp = types.MethodType(completer,self.Completer) | |
1973 | self.Completer.matchers.insert(pos,newcomp) |
|
1965 | self.Completer.matchers.insert(pos,newcomp) | |
1974 |
|
1966 | |||
1975 | def set_completer_frame(self, frame=None): |
|
1967 | def set_completer_frame(self, frame=None): | |
1976 | """Set the frame of the completer.""" |
|
1968 | """Set the frame of the completer.""" | |
1977 | if frame: |
|
1969 | if frame: | |
1978 | self.Completer.namespace = frame.f_locals |
|
1970 | self.Completer.namespace = frame.f_locals | |
1979 | self.Completer.global_namespace = frame.f_globals |
|
1971 | self.Completer.global_namespace = frame.f_globals | |
1980 | else: |
|
1972 | else: | |
1981 | self.Completer.namespace = self.user_ns |
|
1973 | self.Completer.namespace = self.user_ns | |
1982 | self.Completer.global_namespace = self.user_global_ns |
|
1974 | self.Completer.global_namespace = self.user_global_ns | |
1983 |
|
1975 | |||
1984 | #------------------------------------------------------------------------- |
|
1976 | #------------------------------------------------------------------------- | |
1985 | # Things related to magics |
|
1977 | # Things related to magics | |
1986 | #------------------------------------------------------------------------- |
|
1978 | #------------------------------------------------------------------------- | |
1987 |
|
1979 | |||
1988 | def init_magics(self): |
|
1980 | def init_magics(self): | |
1989 | from IPython.core import magics as m |
|
1981 | from IPython.core import magics as m | |
1990 | self.magics_manager = magic.MagicsManager(shell=self, |
|
1982 | self.magics_manager = magic.MagicsManager(shell=self, | |
1991 | parent=self, |
|
1983 | parent=self, | |
1992 | user_magics=m.UserMagics(self)) |
|
1984 | user_magics=m.UserMagics(self)) | |
1993 | self.configurables.append(self.magics_manager) |
|
1985 | self.configurables.append(self.magics_manager) | |
1994 |
|
1986 | |||
1995 | # Expose as public API from the magics manager |
|
1987 | # Expose as public API from the magics manager | |
1996 | self.register_magics = self.magics_manager.register |
|
1988 | self.register_magics = self.magics_manager.register | |
1997 |
|
1989 | |||
1998 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
1990 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, | |
1999 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
1991 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, | |
2000 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
1992 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, | |
2001 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
1993 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, | |
2002 | ) |
|
1994 | ) | |
2003 |
|
1995 | |||
2004 | # Register Magic Aliases |
|
1996 | # Register Magic Aliases | |
2005 | mman = self.magics_manager |
|
1997 | mman = self.magics_manager | |
2006 | # FIXME: magic aliases should be defined by the Magics classes |
|
1998 | # FIXME: magic aliases should be defined by the Magics classes | |
2007 | # or in MagicsManager, not here |
|
1999 | # or in MagicsManager, not here | |
2008 | mman.register_alias('ed', 'edit') |
|
2000 | mman.register_alias('ed', 'edit') | |
2009 | mman.register_alias('hist', 'history') |
|
2001 | mman.register_alias('hist', 'history') | |
2010 | mman.register_alias('rep', 'recall') |
|
2002 | mman.register_alias('rep', 'recall') | |
2011 | mman.register_alias('SVG', 'svg', 'cell') |
|
2003 | mman.register_alias('SVG', 'svg', 'cell') | |
2012 | mman.register_alias('HTML', 'html', 'cell') |
|
2004 | mman.register_alias('HTML', 'html', 'cell') | |
2013 | mman.register_alias('file', 'writefile', 'cell') |
|
2005 | mman.register_alias('file', 'writefile', 'cell') | |
2014 |
|
2006 | |||
2015 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2007 | # FIXME: Move the color initialization to the DisplayHook, which | |
2016 | # should be split into a prompt manager and displayhook. We probably |
|
2008 | # should be split into a prompt manager and displayhook. We probably | |
2017 | # even need a centralize colors management object. |
|
2009 | # even need a centralize colors management object. | |
2018 | self.magic('colors %s' % self.colors) |
|
2010 | self.magic('colors %s' % self.colors) | |
2019 |
|
2011 | |||
2020 | # Defined here so that it's included in the documentation |
|
2012 | # Defined here so that it's included in the documentation | |
2021 | @functools.wraps(magic.MagicsManager.register_function) |
|
2013 | @functools.wraps(magic.MagicsManager.register_function) | |
2022 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2014 | def register_magic_function(self, func, magic_kind='line', magic_name=None): | |
2023 | self.magics_manager.register_function(func, |
|
2015 | self.magics_manager.register_function(func, | |
2024 | magic_kind=magic_kind, magic_name=magic_name) |
|
2016 | magic_kind=magic_kind, magic_name=magic_name) | |
2025 |
|
2017 | |||
2026 | def run_line_magic(self, magic_name, line): |
|
2018 | def run_line_magic(self, magic_name, line): | |
2027 | """Execute the given line magic. |
|
2019 | """Execute the given line magic. | |
2028 |
|
2020 | |||
2029 | Parameters |
|
2021 | Parameters | |
2030 | ---------- |
|
2022 | ---------- | |
2031 | magic_name : str |
|
2023 | magic_name : str | |
2032 | Name of the desired magic function, without '%' prefix. |
|
2024 | Name of the desired magic function, without '%' prefix. | |
2033 |
|
2025 | |||
2034 | line : str |
|
2026 | line : str | |
2035 | The rest of the input line as a single string. |
|
2027 | The rest of the input line as a single string. | |
2036 | """ |
|
2028 | """ | |
2037 | fn = self.find_line_magic(magic_name) |
|
2029 | fn = self.find_line_magic(magic_name) | |
2038 | if fn is None: |
|
2030 | if fn is None: | |
2039 | cm = self.find_cell_magic(magic_name) |
|
2031 | cm = self.find_cell_magic(magic_name) | |
2040 | etpl = "Line magic function `%%%s` not found%s." |
|
2032 | etpl = "Line magic function `%%%s` not found%s." | |
2041 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2033 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' | |
2042 | 'did you mean that instead?)' % magic_name ) |
|
2034 | 'did you mean that instead?)' % magic_name ) | |
2043 | error(etpl % (magic_name, extra)) |
|
2035 | error(etpl % (magic_name, extra)) | |
2044 | else: |
|
2036 | else: | |
2045 | # Note: this is the distance in the stack to the user's frame. |
|
2037 | # Note: this is the distance in the stack to the user's frame. | |
2046 | # This will need to be updated if the internal calling logic gets |
|
2038 | # This will need to be updated if the internal calling logic gets | |
2047 | # refactored, or else we'll be expanding the wrong variables. |
|
2039 | # refactored, or else we'll be expanding the wrong variables. | |
2048 | stack_depth = 2 |
|
2040 | stack_depth = 2 | |
2049 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2041 | magic_arg_s = self.var_expand(line, stack_depth) | |
2050 | # Put magic args in a list so we can call with f(*a) syntax |
|
2042 | # Put magic args in a list so we can call with f(*a) syntax | |
2051 | args = [magic_arg_s] |
|
2043 | args = [magic_arg_s] | |
2052 | kwargs = {} |
|
2044 | kwargs = {} | |
2053 | # Grab local namespace if we need it: |
|
2045 | # Grab local namespace if we need it: | |
2054 | if getattr(fn, "needs_local_scope", False): |
|
2046 | if getattr(fn, "needs_local_scope", False): | |
2055 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2047 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals | |
2056 | with self.builtin_trap: |
|
2048 | with self.builtin_trap: | |
2057 | result = fn(*args,**kwargs) |
|
2049 | result = fn(*args,**kwargs) | |
2058 | return result |
|
2050 | return result | |
2059 |
|
2051 | |||
2060 | def run_cell_magic(self, magic_name, line, cell): |
|
2052 | def run_cell_magic(self, magic_name, line, cell): | |
2061 | """Execute the given cell magic. |
|
2053 | """Execute the given cell magic. | |
2062 |
|
2054 | |||
2063 | Parameters |
|
2055 | Parameters | |
2064 | ---------- |
|
2056 | ---------- | |
2065 | magic_name : str |
|
2057 | magic_name : str | |
2066 | Name of the desired magic function, without '%' prefix. |
|
2058 | Name of the desired magic function, without '%' prefix. | |
2067 |
|
2059 | |||
2068 | line : str |
|
2060 | line : str | |
2069 | The rest of the first input line as a single string. |
|
2061 | The rest of the first input line as a single string. | |
2070 |
|
2062 | |||
2071 | cell : str |
|
2063 | cell : str | |
2072 | The body of the cell as a (possibly multiline) string. |
|
2064 | The body of the cell as a (possibly multiline) string. | |
2073 | """ |
|
2065 | """ | |
2074 | fn = self.find_cell_magic(magic_name) |
|
2066 | fn = self.find_cell_magic(magic_name) | |
2075 | if fn is None: |
|
2067 | if fn is None: | |
2076 | lm = self.find_line_magic(magic_name) |
|
2068 | lm = self.find_line_magic(magic_name) | |
2077 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2069 | etpl = "Cell magic `%%{0}` not found{1}." | |
2078 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2070 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' | |
2079 | 'did you mean that instead?)'.format(magic_name)) |
|
2071 | 'did you mean that instead?)'.format(magic_name)) | |
2080 | error(etpl.format(magic_name, extra)) |
|
2072 | error(etpl.format(magic_name, extra)) | |
2081 | elif cell == '': |
|
2073 | elif cell == '': | |
2082 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2074 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) | |
2083 | if self.find_line_magic(magic_name) is not None: |
|
2075 | if self.find_line_magic(magic_name) is not None: | |
2084 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2076 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) | |
2085 | raise UsageError(message) |
|
2077 | raise UsageError(message) | |
2086 | else: |
|
2078 | else: | |
2087 | # Note: this is the distance in the stack to the user's frame. |
|
2079 | # Note: this is the distance in the stack to the user's frame. | |
2088 | # This will need to be updated if the internal calling logic gets |
|
2080 | # This will need to be updated if the internal calling logic gets | |
2089 | # refactored, or else we'll be expanding the wrong variables. |
|
2081 | # refactored, or else we'll be expanding the wrong variables. | |
2090 | stack_depth = 2 |
|
2082 | stack_depth = 2 | |
2091 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2083 | magic_arg_s = self.var_expand(line, stack_depth) | |
2092 | with self.builtin_trap: |
|
2084 | with self.builtin_trap: | |
2093 | result = fn(magic_arg_s, cell) |
|
2085 | result = fn(magic_arg_s, cell) | |
2094 | return result |
|
2086 | return result | |
2095 |
|
2087 | |||
2096 | def find_line_magic(self, magic_name): |
|
2088 | def find_line_magic(self, magic_name): | |
2097 | """Find and return a line magic by name. |
|
2089 | """Find and return a line magic by name. | |
2098 |
|
2090 | |||
2099 | Returns None if the magic isn't found.""" |
|
2091 | Returns None if the magic isn't found.""" | |
2100 | return self.magics_manager.magics['line'].get(magic_name) |
|
2092 | return self.magics_manager.magics['line'].get(magic_name) | |
2101 |
|
2093 | |||
2102 | def find_cell_magic(self, magic_name): |
|
2094 | def find_cell_magic(self, magic_name): | |
2103 | """Find and return a cell magic by name. |
|
2095 | """Find and return a cell magic by name. | |
2104 |
|
2096 | |||
2105 | Returns None if the magic isn't found.""" |
|
2097 | Returns None if the magic isn't found.""" | |
2106 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2098 | return self.magics_manager.magics['cell'].get(magic_name) | |
2107 |
|
2099 | |||
2108 | def find_magic(self, magic_name, magic_kind='line'): |
|
2100 | def find_magic(self, magic_name, magic_kind='line'): | |
2109 | """Find and return a magic of the given type by name. |
|
2101 | """Find and return a magic of the given type by name. | |
2110 |
|
2102 | |||
2111 | Returns None if the magic isn't found.""" |
|
2103 | Returns None if the magic isn't found.""" | |
2112 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2104 | return self.magics_manager.magics[magic_kind].get(magic_name) | |
2113 |
|
2105 | |||
2114 | def magic(self, arg_s): |
|
2106 | def magic(self, arg_s): | |
2115 | """DEPRECATED. Use run_line_magic() instead. |
|
2107 | """DEPRECATED. Use run_line_magic() instead. | |
2116 |
|
2108 | |||
2117 | Call a magic function by name. |
|
2109 | Call a magic function by name. | |
2118 |
|
2110 | |||
2119 | Input: a string containing the name of the magic function to call and |
|
2111 | Input: a string containing the name of the magic function to call and | |
2120 | any additional arguments to be passed to the magic. |
|
2112 | any additional arguments to be passed to the magic. | |
2121 |
|
2113 | |||
2122 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2114 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
2123 | prompt: |
|
2115 | prompt: | |
2124 |
|
2116 | |||
2125 | In[1]: %name -opt foo bar |
|
2117 | In[1]: %name -opt foo bar | |
2126 |
|
2118 | |||
2127 | To call a magic without arguments, simply use magic('name'). |
|
2119 | To call a magic without arguments, simply use magic('name'). | |
2128 |
|
2120 | |||
2129 | This provides a proper Python function to call IPython's magics in any |
|
2121 | This provides a proper Python function to call IPython's magics in any | |
2130 | valid Python code you can type at the interpreter, including loops and |
|
2122 | valid Python code you can type at the interpreter, including loops and | |
2131 | compound statements. |
|
2123 | compound statements. | |
2132 | """ |
|
2124 | """ | |
2133 | # TODO: should we issue a loud deprecation warning here? |
|
2125 | # TODO: should we issue a loud deprecation warning here? | |
2134 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2126 | magic_name, _, magic_arg_s = arg_s.partition(' ') | |
2135 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2127 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
2136 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2128 | return self.run_line_magic(magic_name, magic_arg_s) | |
2137 |
|
2129 | |||
2138 | #------------------------------------------------------------------------- |
|
2130 | #------------------------------------------------------------------------- | |
2139 | # Things related to macros |
|
2131 | # Things related to macros | |
2140 | #------------------------------------------------------------------------- |
|
2132 | #------------------------------------------------------------------------- | |
2141 |
|
2133 | |||
2142 | def define_macro(self, name, themacro): |
|
2134 | def define_macro(self, name, themacro): | |
2143 | """Define a new macro |
|
2135 | """Define a new macro | |
2144 |
|
2136 | |||
2145 | Parameters |
|
2137 | Parameters | |
2146 | ---------- |
|
2138 | ---------- | |
2147 | name : str |
|
2139 | name : str | |
2148 | The name of the macro. |
|
2140 | The name of the macro. | |
2149 | themacro : str or Macro |
|
2141 | themacro : str or Macro | |
2150 | The action to do upon invoking the macro. If a string, a new |
|
2142 | The action to do upon invoking the macro. If a string, a new | |
2151 | Macro object is created by passing the string to it. |
|
2143 | Macro object is created by passing the string to it. | |
2152 | """ |
|
2144 | """ | |
2153 |
|
2145 | |||
2154 | from IPython.core import macro |
|
2146 | from IPython.core import macro | |
2155 |
|
2147 | |||
2156 | if isinstance(themacro, str): |
|
2148 | if isinstance(themacro, str): | |
2157 | themacro = macro.Macro(themacro) |
|
2149 | themacro = macro.Macro(themacro) | |
2158 | if not isinstance(themacro, macro.Macro): |
|
2150 | if not isinstance(themacro, macro.Macro): | |
2159 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2151 | raise ValueError('A macro must be a string or a Macro instance.') | |
2160 | self.user_ns[name] = themacro |
|
2152 | self.user_ns[name] = themacro | |
2161 |
|
2153 | |||
2162 | #------------------------------------------------------------------------- |
|
2154 | #------------------------------------------------------------------------- | |
2163 | # Things related to the running of system commands |
|
2155 | # Things related to the running of system commands | |
2164 | #------------------------------------------------------------------------- |
|
2156 | #------------------------------------------------------------------------- | |
2165 |
|
2157 | |||
2166 | def system_piped(self, cmd): |
|
2158 | def system_piped(self, cmd): | |
2167 | """Call the given cmd in a subprocess, piping stdout/err |
|
2159 | """Call the given cmd in a subprocess, piping stdout/err | |
2168 |
|
2160 | |||
2169 | Parameters |
|
2161 | Parameters | |
2170 | ---------- |
|
2162 | ---------- | |
2171 | cmd : str |
|
2163 | cmd : str | |
2172 | Command to execute (can not end in '&', as background processes are |
|
2164 | Command to execute (can not end in '&', as background processes are | |
2173 | not supported. Should not be a command that expects input |
|
2165 | not supported. Should not be a command that expects input | |
2174 | other than simple text. |
|
2166 | other than simple text. | |
2175 | """ |
|
2167 | """ | |
2176 | if cmd.rstrip().endswith('&'): |
|
2168 | if cmd.rstrip().endswith('&'): | |
2177 | # this is *far* from a rigorous test |
|
2169 | # this is *far* from a rigorous test | |
2178 | # We do not support backgrounding processes because we either use |
|
2170 | # We do not support backgrounding processes because we either use | |
2179 | # pexpect or pipes to read from. Users can always just call |
|
2171 | # pexpect or pipes to read from. Users can always just call | |
2180 | # os.system() or use ip.system=ip.system_raw |
|
2172 | # os.system() or use ip.system=ip.system_raw | |
2181 | # if they really want a background process. |
|
2173 | # if they really want a background process. | |
2182 | raise OSError("Background processes not supported.") |
|
2174 | raise OSError("Background processes not supported.") | |
2183 |
|
2175 | |||
2184 | # we explicitly do NOT return the subprocess status code, because |
|
2176 | # we explicitly do NOT return the subprocess status code, because | |
2185 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2177 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2186 | # Instead, we store the exit_code in user_ns. |
|
2178 | # Instead, we store the exit_code in user_ns. | |
2187 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2179 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) | |
2188 |
|
2180 | |||
2189 | def system_raw(self, cmd): |
|
2181 | def system_raw(self, cmd): | |
2190 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2182 | """Call the given cmd in a subprocess using os.system on Windows or | |
2191 | subprocess.call using the system shell on other platforms. |
|
2183 | subprocess.call using the system shell on other platforms. | |
2192 |
|
2184 | |||
2193 | Parameters |
|
2185 | Parameters | |
2194 | ---------- |
|
2186 | ---------- | |
2195 | cmd : str |
|
2187 | cmd : str | |
2196 | Command to execute. |
|
2188 | Command to execute. | |
2197 | """ |
|
2189 | """ | |
2198 | cmd = self.var_expand(cmd, depth=1) |
|
2190 | cmd = self.var_expand(cmd, depth=1) | |
2199 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2191 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2200 | if sys.platform == 'win32': |
|
2192 | if sys.platform == 'win32': | |
2201 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2193 | from IPython.utils._process_win32 import AvoidUNCPath | |
2202 | with AvoidUNCPath() as path: |
|
2194 | with AvoidUNCPath() as path: | |
2203 | if path is not None: |
|
2195 | if path is not None: | |
2204 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2196 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2205 | try: |
|
2197 | try: | |
2206 | ec = os.system(cmd) |
|
2198 | ec = os.system(cmd) | |
2207 | except KeyboardInterrupt: |
|
2199 | except KeyboardInterrupt: | |
2208 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2200 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
2209 | ec = -2 |
|
2201 | ec = -2 | |
2210 | else: |
|
2202 | else: | |
2211 | # For posix the result of the subprocess.call() below is an exit |
|
2203 | # For posix the result of the subprocess.call() below is an exit | |
2212 | # code, which by convention is zero for success, positive for |
|
2204 | # code, which by convention is zero for success, positive for | |
2213 | # program failure. Exit codes above 128 are reserved for signals, |
|
2205 | # program failure. Exit codes above 128 are reserved for signals, | |
2214 | # and the formula for converting a signal to an exit code is usually |
|
2206 | # and the formula for converting a signal to an exit code is usually | |
2215 | # signal_number+128. To more easily differentiate between exit |
|
2207 | # signal_number+128. To more easily differentiate between exit | |
2216 | # codes and signals, ipython uses negative numbers. For instance |
|
2208 | # codes and signals, ipython uses negative numbers. For instance | |
2217 | # since control-c is signal 2 but exit code 130, ipython's |
|
2209 | # since control-c is signal 2 but exit code 130, ipython's | |
2218 | # _exit_code variable will read -2. Note that some shells like |
|
2210 | # _exit_code variable will read -2. Note that some shells like | |
2219 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2211 | # csh and fish don't follow sh/bash conventions for exit codes. | |
2220 | executable = os.environ.get('SHELL', None) |
|
2212 | executable = os.environ.get('SHELL', None) | |
2221 | try: |
|
2213 | try: | |
2222 | # Use env shell instead of default /bin/sh |
|
2214 | # Use env shell instead of default /bin/sh | |
2223 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2215 | ec = subprocess.call(cmd, shell=True, executable=executable) | |
2224 | except KeyboardInterrupt: |
|
2216 | except KeyboardInterrupt: | |
2225 | # intercept control-C; a long traceback is not useful here |
|
2217 | # intercept control-C; a long traceback is not useful here | |
2226 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2218 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
2227 | ec = 130 |
|
2219 | ec = 130 | |
2228 | if ec > 128: |
|
2220 | if ec > 128: | |
2229 | ec = -(ec - 128) |
|
2221 | ec = -(ec - 128) | |
2230 |
|
2222 | |||
2231 | # We explicitly do NOT return the subprocess status code, because |
|
2223 | # We explicitly do NOT return the subprocess status code, because | |
2232 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2224 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2233 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2225 | # Instead, we store the exit_code in user_ns. Note the semantics | |
2234 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2226 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, | |
2235 | # but raising SystemExit(_exit_code) will give status 254! |
|
2227 | # but raising SystemExit(_exit_code) will give status 254! | |
2236 | self.user_ns['_exit_code'] = ec |
|
2228 | self.user_ns['_exit_code'] = ec | |
2237 |
|
2229 | |||
2238 | # use piped system by default, because it is better behaved |
|
2230 | # use piped system by default, because it is better behaved | |
2239 | system = system_piped |
|
2231 | system = system_piped | |
2240 |
|
2232 | |||
2241 | def getoutput(self, cmd, split=True, depth=0): |
|
2233 | def getoutput(self, cmd, split=True, depth=0): | |
2242 | """Get output (possibly including stderr) from a subprocess. |
|
2234 | """Get output (possibly including stderr) from a subprocess. | |
2243 |
|
2235 | |||
2244 | Parameters |
|
2236 | Parameters | |
2245 | ---------- |
|
2237 | ---------- | |
2246 | cmd : str |
|
2238 | cmd : str | |
2247 | Command to execute (can not end in '&', as background processes are |
|
2239 | Command to execute (can not end in '&', as background processes are | |
2248 | not supported. |
|
2240 | not supported. | |
2249 | split : bool, optional |
|
2241 | split : bool, optional | |
2250 | If True, split the output into an IPython SList. Otherwise, an |
|
2242 | If True, split the output into an IPython SList. Otherwise, an | |
2251 | IPython LSString is returned. These are objects similar to normal |
|
2243 | IPython LSString is returned. These are objects similar to normal | |
2252 | lists and strings, with a few convenience attributes for easier |
|
2244 | lists and strings, with a few convenience attributes for easier | |
2253 | manipulation of line-based output. You can use '?' on them for |
|
2245 | manipulation of line-based output. You can use '?' on them for | |
2254 | details. |
|
2246 | details. | |
2255 | depth : int, optional |
|
2247 | depth : int, optional | |
2256 | How many frames above the caller are the local variables which should |
|
2248 | How many frames above the caller are the local variables which should | |
2257 | be expanded in the command string? The default (0) assumes that the |
|
2249 | be expanded in the command string? The default (0) assumes that the | |
2258 | expansion variables are in the stack frame calling this function. |
|
2250 | expansion variables are in the stack frame calling this function. | |
2259 | """ |
|
2251 | """ | |
2260 | if cmd.rstrip().endswith('&'): |
|
2252 | if cmd.rstrip().endswith('&'): | |
2261 | # this is *far* from a rigorous test |
|
2253 | # this is *far* from a rigorous test | |
2262 | raise OSError("Background processes not supported.") |
|
2254 | raise OSError("Background processes not supported.") | |
2263 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2255 | out = getoutput(self.var_expand(cmd, depth=depth+1)) | |
2264 | if split: |
|
2256 | if split: | |
2265 | out = SList(out.splitlines()) |
|
2257 | out = SList(out.splitlines()) | |
2266 | else: |
|
2258 | else: | |
2267 | out = LSString(out) |
|
2259 | out = LSString(out) | |
2268 | return out |
|
2260 | return out | |
2269 |
|
2261 | |||
2270 | #------------------------------------------------------------------------- |
|
2262 | #------------------------------------------------------------------------- | |
2271 | # Things related to aliases |
|
2263 | # Things related to aliases | |
2272 | #------------------------------------------------------------------------- |
|
2264 | #------------------------------------------------------------------------- | |
2273 |
|
2265 | |||
2274 | def init_alias(self): |
|
2266 | def init_alias(self): | |
2275 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2267 | self.alias_manager = AliasManager(shell=self, parent=self) | |
2276 | self.configurables.append(self.alias_manager) |
|
2268 | self.configurables.append(self.alias_manager) | |
2277 |
|
2269 | |||
2278 | #------------------------------------------------------------------------- |
|
2270 | #------------------------------------------------------------------------- | |
2279 | # Things related to extensions |
|
2271 | # Things related to extensions | |
2280 | #------------------------------------------------------------------------- |
|
2272 | #------------------------------------------------------------------------- | |
2281 |
|
2273 | |||
2282 | def init_extension_manager(self): |
|
2274 | def init_extension_manager(self): | |
2283 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2275 | self.extension_manager = ExtensionManager(shell=self, parent=self) | |
2284 | self.configurables.append(self.extension_manager) |
|
2276 | self.configurables.append(self.extension_manager) | |
2285 |
|
2277 | |||
2286 | #------------------------------------------------------------------------- |
|
2278 | #------------------------------------------------------------------------- | |
2287 | # Things related to payloads |
|
2279 | # Things related to payloads | |
2288 | #------------------------------------------------------------------------- |
|
2280 | #------------------------------------------------------------------------- | |
2289 |
|
2281 | |||
2290 | def init_payload(self): |
|
2282 | def init_payload(self): | |
2291 | self.payload_manager = PayloadManager(parent=self) |
|
2283 | self.payload_manager = PayloadManager(parent=self) | |
2292 | self.configurables.append(self.payload_manager) |
|
2284 | self.configurables.append(self.payload_manager) | |
2293 |
|
2285 | |||
2294 | #------------------------------------------------------------------------- |
|
2286 | #------------------------------------------------------------------------- | |
2295 | # Things related to the prefilter |
|
2287 | # Things related to the prefilter | |
2296 | #------------------------------------------------------------------------- |
|
2288 | #------------------------------------------------------------------------- | |
2297 |
|
2289 | |||
2298 | def init_prefilter(self): |
|
2290 | def init_prefilter(self): | |
2299 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2291 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) | |
2300 | self.configurables.append(self.prefilter_manager) |
|
2292 | self.configurables.append(self.prefilter_manager) | |
2301 | # Ultimately this will be refactored in the new interpreter code, but |
|
2293 | # Ultimately this will be refactored in the new interpreter code, but | |
2302 | # for now, we should expose the main prefilter method (there's legacy |
|
2294 | # for now, we should expose the main prefilter method (there's legacy | |
2303 | # code out there that may rely on this). |
|
2295 | # code out there that may rely on this). | |
2304 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2296 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2305 |
|
2297 | |||
2306 | def auto_rewrite_input(self, cmd): |
|
2298 | def auto_rewrite_input(self, cmd): | |
2307 | """Print to the screen the rewritten form of the user's command. |
|
2299 | """Print to the screen the rewritten form of the user's command. | |
2308 |
|
2300 | |||
2309 | This shows visual feedback by rewriting input lines that cause |
|
2301 | This shows visual feedback by rewriting input lines that cause | |
2310 | automatic calling to kick in, like:: |
|
2302 | automatic calling to kick in, like:: | |
2311 |
|
2303 | |||
2312 | /f x |
|
2304 | /f x | |
2313 |
|
2305 | |||
2314 | into:: |
|
2306 | into:: | |
2315 |
|
2307 | |||
2316 | ------> f(x) |
|
2308 | ------> f(x) | |
2317 |
|
2309 | |||
2318 | after the user's input prompt. This helps the user understand that the |
|
2310 | after the user's input prompt. This helps the user understand that the | |
2319 | input line was transformed automatically by IPython. |
|
2311 | input line was transformed automatically by IPython. | |
2320 | """ |
|
2312 | """ | |
2321 | if not self.show_rewritten_input: |
|
2313 | if not self.show_rewritten_input: | |
2322 | return |
|
2314 | return | |
2323 |
|
2315 | |||
2324 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2316 | # This is overridden in TerminalInteractiveShell to use fancy prompts | |
2325 | print("------> " + cmd) |
|
2317 | print("------> " + cmd) | |
2326 |
|
2318 | |||
2327 | #------------------------------------------------------------------------- |
|
2319 | #------------------------------------------------------------------------- | |
2328 | # Things related to extracting values/expressions from kernel and user_ns |
|
2320 | # Things related to extracting values/expressions from kernel and user_ns | |
2329 | #------------------------------------------------------------------------- |
|
2321 | #------------------------------------------------------------------------- | |
2330 |
|
2322 | |||
2331 | def _user_obj_error(self): |
|
2323 | def _user_obj_error(self): | |
2332 | """return simple exception dict |
|
2324 | """return simple exception dict | |
2333 |
|
2325 | |||
2334 | for use in user_expressions |
|
2326 | for use in user_expressions | |
2335 | """ |
|
2327 | """ | |
2336 |
|
2328 | |||
2337 | etype, evalue, tb = self._get_exc_info() |
|
2329 | etype, evalue, tb = self._get_exc_info() | |
2338 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2330 | stb = self.InteractiveTB.get_exception_only(etype, evalue) | |
2339 |
|
2331 | |||
2340 | exc_info = { |
|
2332 | exc_info = { | |
2341 | u'status' : 'error', |
|
2333 | u'status' : 'error', | |
2342 | u'traceback' : stb, |
|
2334 | u'traceback' : stb, | |
2343 | u'ename' : etype.__name__, |
|
2335 | u'ename' : etype.__name__, | |
2344 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2336 | u'evalue' : py3compat.safe_unicode(evalue), | |
2345 | } |
|
2337 | } | |
2346 |
|
2338 | |||
2347 | return exc_info |
|
2339 | return exc_info | |
2348 |
|
2340 | |||
2349 | def _format_user_obj(self, obj): |
|
2341 | def _format_user_obj(self, obj): | |
2350 | """format a user object to display dict |
|
2342 | """format a user object to display dict | |
2351 |
|
2343 | |||
2352 | for use in user_expressions |
|
2344 | for use in user_expressions | |
2353 | """ |
|
2345 | """ | |
2354 |
|
2346 | |||
2355 | data, md = self.display_formatter.format(obj) |
|
2347 | data, md = self.display_formatter.format(obj) | |
2356 | value = { |
|
2348 | value = { | |
2357 | 'status' : 'ok', |
|
2349 | 'status' : 'ok', | |
2358 | 'data' : data, |
|
2350 | 'data' : data, | |
2359 | 'metadata' : md, |
|
2351 | 'metadata' : md, | |
2360 | } |
|
2352 | } | |
2361 | return value |
|
2353 | return value | |
2362 |
|
2354 | |||
2363 | def user_expressions(self, expressions): |
|
2355 | def user_expressions(self, expressions): | |
2364 | """Evaluate a dict of expressions in the user's namespace. |
|
2356 | """Evaluate a dict of expressions in the user's namespace. | |
2365 |
|
2357 | |||
2366 | Parameters |
|
2358 | Parameters | |
2367 | ---------- |
|
2359 | ---------- | |
2368 | expressions : dict |
|
2360 | expressions : dict | |
2369 | A dict with string keys and string values. The expression values |
|
2361 | A dict with string keys and string values. The expression values | |
2370 | should be valid Python expressions, each of which will be evaluated |
|
2362 | should be valid Python expressions, each of which will be evaluated | |
2371 | in the user namespace. |
|
2363 | in the user namespace. | |
2372 |
|
2364 | |||
2373 | Returns |
|
2365 | Returns | |
2374 | ------- |
|
2366 | ------- | |
2375 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2367 | A dict, keyed like the input expressions dict, with the rich mime-typed | |
2376 | display_data of each value. |
|
2368 | display_data of each value. | |
2377 | """ |
|
2369 | """ | |
2378 | out = {} |
|
2370 | out = {} | |
2379 | user_ns = self.user_ns |
|
2371 | user_ns = self.user_ns | |
2380 | global_ns = self.user_global_ns |
|
2372 | global_ns = self.user_global_ns | |
2381 |
|
2373 | |||
2382 | for key, expr in expressions.items(): |
|
2374 | for key, expr in expressions.items(): | |
2383 | try: |
|
2375 | try: | |
2384 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2376 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) | |
2385 | except: |
|
2377 | except: | |
2386 | value = self._user_obj_error() |
|
2378 | value = self._user_obj_error() | |
2387 | out[key] = value |
|
2379 | out[key] = value | |
2388 | return out |
|
2380 | return out | |
2389 |
|
2381 | |||
2390 | #------------------------------------------------------------------------- |
|
2382 | #------------------------------------------------------------------------- | |
2391 | # Things related to the running of code |
|
2383 | # Things related to the running of code | |
2392 | #------------------------------------------------------------------------- |
|
2384 | #------------------------------------------------------------------------- | |
2393 |
|
2385 | |||
2394 | def ex(self, cmd): |
|
2386 | def ex(self, cmd): | |
2395 | """Execute a normal python statement in user namespace.""" |
|
2387 | """Execute a normal python statement in user namespace.""" | |
2396 | with self.builtin_trap: |
|
2388 | with self.builtin_trap: | |
2397 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2389 | exec(cmd, self.user_global_ns, self.user_ns) | |
2398 |
|
2390 | |||
2399 | def ev(self, expr): |
|
2391 | def ev(self, expr): | |
2400 | """Evaluate python expression expr in user namespace. |
|
2392 | """Evaluate python expression expr in user namespace. | |
2401 |
|
2393 | |||
2402 | Returns the result of evaluation |
|
2394 | Returns the result of evaluation | |
2403 | """ |
|
2395 | """ | |
2404 | with self.builtin_trap: |
|
2396 | with self.builtin_trap: | |
2405 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2397 | return eval(expr, self.user_global_ns, self.user_ns) | |
2406 |
|
2398 | |||
2407 | def safe_execfile(self, fname, *where, **kw): |
|
2399 | def safe_execfile(self, fname, *where, **kw): | |
2408 | """A safe version of the builtin execfile(). |
|
2400 | """A safe version of the builtin execfile(). | |
2409 |
|
2401 | |||
2410 | This version will never throw an exception, but instead print |
|
2402 | This version will never throw an exception, but instead print | |
2411 | helpful error messages to the screen. This only works on pure |
|
2403 | helpful error messages to the screen. This only works on pure | |
2412 | Python files with the .py extension. |
|
2404 | Python files with the .py extension. | |
2413 |
|
2405 | |||
2414 | Parameters |
|
2406 | Parameters | |
2415 | ---------- |
|
2407 | ---------- | |
2416 | fname : string |
|
2408 | fname : string | |
2417 | The name of the file to be executed. |
|
2409 | The name of the file to be executed. | |
2418 | where : tuple |
|
2410 | where : tuple | |
2419 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2411 | One or two namespaces, passed to execfile() as (globals,locals). | |
2420 | If only one is given, it is passed as both. |
|
2412 | If only one is given, it is passed as both. | |
2421 | exit_ignore : bool (False) |
|
2413 | exit_ignore : bool (False) | |
2422 | If True, then silence SystemExit for non-zero status (it is always |
|
2414 | If True, then silence SystemExit for non-zero status (it is always | |
2423 | silenced for zero status, as it is so common). |
|
2415 | silenced for zero status, as it is so common). | |
2424 | raise_exceptions : bool (False) |
|
2416 | raise_exceptions : bool (False) | |
2425 | If True raise exceptions everywhere. Meant for testing. |
|
2417 | If True raise exceptions everywhere. Meant for testing. | |
2426 | shell_futures : bool (False) |
|
2418 | shell_futures : bool (False) | |
2427 | If True, the code will share future statements with the interactive |
|
2419 | If True, the code will share future statements with the interactive | |
2428 | shell. It will both be affected by previous __future__ imports, and |
|
2420 | shell. It will both be affected by previous __future__ imports, and | |
2429 | any __future__ imports in the code will affect the shell. If False, |
|
2421 | any __future__ imports in the code will affect the shell. If False, | |
2430 | __future__ imports are not shared in either direction. |
|
2422 | __future__ imports are not shared in either direction. | |
2431 |
|
2423 | |||
2432 | """ |
|
2424 | """ | |
2433 | kw.setdefault('exit_ignore', False) |
|
2425 | kw.setdefault('exit_ignore', False) | |
2434 | kw.setdefault('raise_exceptions', False) |
|
2426 | kw.setdefault('raise_exceptions', False) | |
2435 | kw.setdefault('shell_futures', False) |
|
2427 | kw.setdefault('shell_futures', False) | |
2436 |
|
2428 | |||
2437 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2429 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2438 |
|
2430 | |||
2439 | # Make sure we can open the file |
|
2431 | # Make sure we can open the file | |
2440 | try: |
|
2432 | try: | |
2441 | with open(fname): |
|
2433 | with open(fname): | |
2442 | pass |
|
2434 | pass | |
2443 | except: |
|
2435 | except: | |
2444 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2436 | warn('Could not open file <%s> for safe execution.' % fname) | |
2445 | return |
|
2437 | return | |
2446 |
|
2438 | |||
2447 | # Find things also in current directory. This is needed to mimic the |
|
2439 | # Find things also in current directory. This is needed to mimic the | |
2448 | # behavior of running a script from the system command line, where |
|
2440 | # behavior of running a script from the system command line, where | |
2449 | # Python inserts the script's directory into sys.path |
|
2441 | # Python inserts the script's directory into sys.path | |
2450 | dname = os.path.dirname(fname) |
|
2442 | dname = os.path.dirname(fname) | |
2451 |
|
2443 | |||
2452 | with prepended_to_syspath(dname), self.builtin_trap: |
|
2444 | with prepended_to_syspath(dname), self.builtin_trap: | |
2453 | try: |
|
2445 | try: | |
2454 | glob, loc = (where + (None, ))[:2] |
|
2446 | glob, loc = (where + (None, ))[:2] | |
2455 | py3compat.execfile( |
|
2447 | py3compat.execfile( | |
2456 | fname, glob, loc, |
|
2448 | fname, glob, loc, | |
2457 | self.compile if kw['shell_futures'] else None) |
|
2449 | self.compile if kw['shell_futures'] else None) | |
2458 | except SystemExit as status: |
|
2450 | except SystemExit as status: | |
2459 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2451 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2460 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2452 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2461 | # these are considered normal by the OS: |
|
2453 | # these are considered normal by the OS: | |
2462 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2454 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2463 | # 0 |
|
2455 | # 0 | |
2464 | # > python -c'import sys;sys.exit()'; echo $? |
|
2456 | # > python -c'import sys;sys.exit()'; echo $? | |
2465 | # 0 |
|
2457 | # 0 | |
2466 | # For other exit status, we show the exception unless |
|
2458 | # For other exit status, we show the exception unless | |
2467 | # explicitly silenced, but only in short form. |
|
2459 | # explicitly silenced, but only in short form. | |
2468 | if status.code: |
|
2460 | if status.code: | |
2469 | if kw['raise_exceptions']: |
|
2461 | if kw['raise_exceptions']: | |
2470 | raise |
|
2462 | raise | |
2471 | if not kw['exit_ignore']: |
|
2463 | if not kw['exit_ignore']: | |
2472 | self.showtraceback(exception_only=True) |
|
2464 | self.showtraceback(exception_only=True) | |
2473 | except: |
|
2465 | except: | |
2474 | if kw['raise_exceptions']: |
|
2466 | if kw['raise_exceptions']: | |
2475 | raise |
|
2467 | raise | |
2476 | # tb offset is 2 because we wrap execfile |
|
2468 | # tb offset is 2 because we wrap execfile | |
2477 | self.showtraceback(tb_offset=2) |
|
2469 | self.showtraceback(tb_offset=2) | |
2478 |
|
2470 | |||
2479 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2471 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): | |
2480 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2472 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. | |
2481 |
|
2473 | |||
2482 | Parameters |
|
2474 | Parameters | |
2483 | ---------- |
|
2475 | ---------- | |
2484 | fname : str |
|
2476 | fname : str | |
2485 | The name of the file to execute. The filename must have a |
|
2477 | The name of the file to execute. The filename must have a | |
2486 | .ipy or .ipynb extension. |
|
2478 | .ipy or .ipynb extension. | |
2487 | shell_futures : bool (False) |
|
2479 | shell_futures : bool (False) | |
2488 | If True, the code will share future statements with the interactive |
|
2480 | If True, the code will share future statements with the interactive | |
2489 | shell. It will both be affected by previous __future__ imports, and |
|
2481 | shell. It will both be affected by previous __future__ imports, and | |
2490 | any __future__ imports in the code will affect the shell. If False, |
|
2482 | any __future__ imports in the code will affect the shell. If False, | |
2491 | __future__ imports are not shared in either direction. |
|
2483 | __future__ imports are not shared in either direction. | |
2492 | raise_exceptions : bool (False) |
|
2484 | raise_exceptions : bool (False) | |
2493 | If True raise exceptions everywhere. Meant for testing. |
|
2485 | If True raise exceptions everywhere. Meant for testing. | |
2494 | """ |
|
2486 | """ | |
2495 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2487 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2496 |
|
2488 | |||
2497 | # Make sure we can open the file |
|
2489 | # Make sure we can open the file | |
2498 | try: |
|
2490 | try: | |
2499 | with open(fname): |
|
2491 | with open(fname): | |
2500 | pass |
|
2492 | pass | |
2501 | except: |
|
2493 | except: | |
2502 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2494 | warn('Could not open file <%s> for safe execution.' % fname) | |
2503 | return |
|
2495 | return | |
2504 |
|
2496 | |||
2505 | # Find things also in current directory. This is needed to mimic the |
|
2497 | # Find things also in current directory. This is needed to mimic the | |
2506 | # behavior of running a script from the system command line, where |
|
2498 | # behavior of running a script from the system command line, where | |
2507 | # Python inserts the script's directory into sys.path |
|
2499 | # Python inserts the script's directory into sys.path | |
2508 | dname = os.path.dirname(fname) |
|
2500 | dname = os.path.dirname(fname) | |
2509 |
|
2501 | |||
2510 | def get_cells(): |
|
2502 | def get_cells(): | |
2511 | """generator for sequence of code blocks to run""" |
|
2503 | """generator for sequence of code blocks to run""" | |
2512 | if fname.endswith('.ipynb'): |
|
2504 | if fname.endswith('.ipynb'): | |
2513 | from nbformat import read |
|
2505 | from nbformat import read | |
2514 | with io_open(fname) as f: |
|
2506 | with io_open(fname) as f: | |
2515 | nb = read(f, as_version=4) |
|
2507 | nb = read(f, as_version=4) | |
2516 | if not nb.cells: |
|
2508 | if not nb.cells: | |
2517 | return |
|
2509 | return | |
2518 | for cell in nb.cells: |
|
2510 | for cell in nb.cells: | |
2519 | if cell.cell_type == 'code': |
|
2511 | if cell.cell_type == 'code': | |
2520 | yield cell.source |
|
2512 | yield cell.source | |
2521 | else: |
|
2513 | else: | |
2522 | with open(fname) as f: |
|
2514 | with open(fname) as f: | |
2523 | yield f.read() |
|
2515 | yield f.read() | |
2524 |
|
2516 | |||
2525 | with prepended_to_syspath(dname): |
|
2517 | with prepended_to_syspath(dname): | |
2526 | try: |
|
2518 | try: | |
2527 | for cell in get_cells(): |
|
2519 | for cell in get_cells(): | |
2528 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2520 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) | |
2529 | if raise_exceptions: |
|
2521 | if raise_exceptions: | |
2530 | result.raise_error() |
|
2522 | result.raise_error() | |
2531 | elif not result.success: |
|
2523 | elif not result.success: | |
2532 | break |
|
2524 | break | |
2533 | except: |
|
2525 | except: | |
2534 | if raise_exceptions: |
|
2526 | if raise_exceptions: | |
2535 | raise |
|
2527 | raise | |
2536 | self.showtraceback() |
|
2528 | self.showtraceback() | |
2537 | warn('Unknown failure executing file: <%s>' % fname) |
|
2529 | warn('Unknown failure executing file: <%s>' % fname) | |
2538 |
|
2530 | |||
2539 | def safe_run_module(self, mod_name, where): |
|
2531 | def safe_run_module(self, mod_name, where): | |
2540 | """A safe version of runpy.run_module(). |
|
2532 | """A safe version of runpy.run_module(). | |
2541 |
|
2533 | |||
2542 | This version will never throw an exception, but instead print |
|
2534 | This version will never throw an exception, but instead print | |
2543 | helpful error messages to the screen. |
|
2535 | helpful error messages to the screen. | |
2544 |
|
2536 | |||
2545 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2537 | `SystemExit` exceptions with status code 0 or None are ignored. | |
2546 |
|
2538 | |||
2547 | Parameters |
|
2539 | Parameters | |
2548 | ---------- |
|
2540 | ---------- | |
2549 | mod_name : string |
|
2541 | mod_name : string | |
2550 | The name of the module to be executed. |
|
2542 | The name of the module to be executed. | |
2551 | where : dict |
|
2543 | where : dict | |
2552 | The globals namespace. |
|
2544 | The globals namespace. | |
2553 | """ |
|
2545 | """ | |
2554 | try: |
|
2546 | try: | |
2555 | try: |
|
2547 | try: | |
2556 | where.update( |
|
2548 | where.update( | |
2557 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2549 | runpy.run_module(str(mod_name), run_name="__main__", | |
2558 | alter_sys=True) |
|
2550 | alter_sys=True) | |
2559 | ) |
|
2551 | ) | |
2560 | except SystemExit as status: |
|
2552 | except SystemExit as status: | |
2561 | if status.code: |
|
2553 | if status.code: | |
2562 | raise |
|
2554 | raise | |
2563 | except: |
|
2555 | except: | |
2564 | self.showtraceback() |
|
2556 | self.showtraceback() | |
2565 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2557 | warn('Unknown failure executing module: <%s>' % mod_name) | |
2566 |
|
2558 | |||
2567 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2559 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): | |
2568 | """Run a complete IPython cell. |
|
2560 | """Run a complete IPython cell. | |
2569 |
|
2561 | |||
2570 | Parameters |
|
2562 | Parameters | |
2571 | ---------- |
|
2563 | ---------- | |
2572 | raw_cell : str |
|
2564 | raw_cell : str | |
2573 | The code (including IPython code such as %magic functions) to run. |
|
2565 | The code (including IPython code such as %magic functions) to run. | |
2574 | store_history : bool |
|
2566 | store_history : bool | |
2575 | If True, the raw and translated cell will be stored in IPython's |
|
2567 | If True, the raw and translated cell will be stored in IPython's | |
2576 | history. For user code calling back into IPython's machinery, this |
|
2568 | history. For user code calling back into IPython's machinery, this | |
2577 | should be set to False. |
|
2569 | should be set to False. | |
2578 | silent : bool |
|
2570 | silent : bool | |
2579 | If True, avoid side-effects, such as implicit displayhooks and |
|
2571 | If True, avoid side-effects, such as implicit displayhooks and | |
2580 | and logging. silent=True forces store_history=False. |
|
2572 | and logging. silent=True forces store_history=False. | |
2581 | shell_futures : bool |
|
2573 | shell_futures : bool | |
2582 | If True, the code will share future statements with the interactive |
|
2574 | If True, the code will share future statements with the interactive | |
2583 | shell. It will both be affected by previous __future__ imports, and |
|
2575 | shell. It will both be affected by previous __future__ imports, and | |
2584 | any __future__ imports in the code will affect the shell. If False, |
|
2576 | any __future__ imports in the code will affect the shell. If False, | |
2585 | __future__ imports are not shared in either direction. |
|
2577 | __future__ imports are not shared in either direction. | |
2586 |
|
2578 | |||
2587 | Returns |
|
2579 | Returns | |
2588 | ------- |
|
2580 | ------- | |
2589 | result : :class:`ExecutionResult` |
|
2581 | result : :class:`ExecutionResult` | |
2590 | """ |
|
2582 | """ | |
2591 | result = ExecutionResult() |
|
2583 | result = ExecutionResult() | |
2592 |
|
2584 | |||
2593 | if (not raw_cell) or raw_cell.isspace(): |
|
2585 | if (not raw_cell) or raw_cell.isspace(): | |
2594 | self.last_execution_succeeded = True |
|
2586 | self.last_execution_succeeded = True | |
2595 | return result |
|
2587 | return result | |
2596 |
|
2588 | |||
2597 | if silent: |
|
2589 | if silent: | |
2598 | store_history = False |
|
2590 | store_history = False | |
2599 |
|
2591 | |||
2600 | if store_history: |
|
2592 | if store_history: | |
2601 | result.execution_count = self.execution_count |
|
2593 | result.execution_count = self.execution_count | |
2602 |
|
2594 | |||
2603 | def error_before_exec(value): |
|
2595 | def error_before_exec(value): | |
2604 | result.error_before_exec = value |
|
2596 | result.error_before_exec = value | |
2605 | self.last_execution_succeeded = False |
|
2597 | self.last_execution_succeeded = False | |
2606 | return result |
|
2598 | return result | |
2607 |
|
2599 | |||
2608 | self.events.trigger('pre_execute') |
|
2600 | self.events.trigger('pre_execute') | |
2609 | if not silent: |
|
2601 | if not silent: | |
2610 | self.events.trigger('pre_run_cell') |
|
2602 | self.events.trigger('pre_run_cell') | |
2611 |
|
2603 | |||
2612 | # If any of our input transformation (input_transformer_manager or |
|
2604 | # If any of our input transformation (input_transformer_manager or | |
2613 | # prefilter_manager) raises an exception, we store it in this variable |
|
2605 | # prefilter_manager) raises an exception, we store it in this variable | |
2614 | # so that we can display the error after logging the input and storing |
|
2606 | # so that we can display the error after logging the input and storing | |
2615 | # it in the history. |
|
2607 | # it in the history. | |
2616 | preprocessing_exc_tuple = None |
|
2608 | preprocessing_exc_tuple = None | |
2617 | try: |
|
2609 | try: | |
2618 | # Static input transformations |
|
2610 | # Static input transformations | |
2619 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2611 | cell = self.input_transformer_manager.transform_cell(raw_cell) | |
2620 | except SyntaxError: |
|
2612 | except SyntaxError: | |
2621 | preprocessing_exc_tuple = sys.exc_info() |
|
2613 | preprocessing_exc_tuple = sys.exc_info() | |
2622 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2614 | cell = raw_cell # cell has to exist so it can be stored/logged | |
2623 | else: |
|
2615 | else: | |
2624 | if len(cell.splitlines()) == 1: |
|
2616 | if len(cell.splitlines()) == 1: | |
2625 | # Dynamic transformations - only applied for single line commands |
|
2617 | # Dynamic transformations - only applied for single line commands | |
2626 | with self.builtin_trap: |
|
2618 | with self.builtin_trap: | |
2627 | try: |
|
2619 | try: | |
2628 | # use prefilter_lines to handle trailing newlines |
|
2620 | # use prefilter_lines to handle trailing newlines | |
2629 | # restore trailing newline for ast.parse |
|
2621 | # restore trailing newline for ast.parse | |
2630 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2622 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2631 | except Exception: |
|
2623 | except Exception: | |
2632 | # don't allow prefilter errors to crash IPython |
|
2624 | # don't allow prefilter errors to crash IPython | |
2633 | preprocessing_exc_tuple = sys.exc_info() |
|
2625 | preprocessing_exc_tuple = sys.exc_info() | |
2634 |
|
2626 | |||
2635 | # Store raw and processed history |
|
2627 | # Store raw and processed history | |
2636 | if store_history: |
|
2628 | if store_history: | |
2637 | self.history_manager.store_inputs(self.execution_count, |
|
2629 | self.history_manager.store_inputs(self.execution_count, | |
2638 | cell, raw_cell) |
|
2630 | cell, raw_cell) | |
2639 | if not silent: |
|
2631 | if not silent: | |
2640 | self.logger.log(cell, raw_cell) |
|
2632 | self.logger.log(cell, raw_cell) | |
2641 |
|
2633 | |||
2642 | # Display the exception if input processing failed. |
|
2634 | # Display the exception if input processing failed. | |
2643 | if preprocessing_exc_tuple is not None: |
|
2635 | if preprocessing_exc_tuple is not None: | |
2644 | self.showtraceback(preprocessing_exc_tuple) |
|
2636 | self.showtraceback(preprocessing_exc_tuple) | |
2645 | if store_history: |
|
2637 | if store_history: | |
2646 | self.execution_count += 1 |
|
2638 | self.execution_count += 1 | |
2647 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2639 | return error_before_exec(preprocessing_exc_tuple[2]) | |
2648 |
|
2640 | |||
2649 | # Our own compiler remembers the __future__ environment. If we want to |
|
2641 | # Our own compiler remembers the __future__ environment. If we want to | |
2650 | # run code with a separate __future__ environment, use the default |
|
2642 | # run code with a separate __future__ environment, use the default | |
2651 | # compiler |
|
2643 | # compiler | |
2652 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2644 | compiler = self.compile if shell_futures else CachingCompiler() | |
2653 |
|
2645 | |||
2654 | with self.builtin_trap: |
|
2646 | with self.builtin_trap: | |
2655 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2647 | cell_name = self.compile.cache(cell, self.execution_count) | |
2656 |
|
2648 | |||
2657 | with self.display_trap: |
|
2649 | with self.display_trap: | |
2658 | # Compile to bytecode |
|
2650 | # Compile to bytecode | |
2659 | try: |
|
2651 | try: | |
2660 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2652 | code_ast = compiler.ast_parse(cell, filename=cell_name) | |
2661 | except self.custom_exceptions as e: |
|
2653 | except self.custom_exceptions as e: | |
2662 | etype, value, tb = sys.exc_info() |
|
2654 | etype, value, tb = sys.exc_info() | |
2663 | self.CustomTB(etype, value, tb) |
|
2655 | self.CustomTB(etype, value, tb) | |
2664 | return error_before_exec(e) |
|
2656 | return error_before_exec(e) | |
2665 | except IndentationError as e: |
|
2657 | except IndentationError as e: | |
2666 | self.showindentationerror() |
|
2658 | self.showindentationerror() | |
2667 | if store_history: |
|
2659 | if store_history: | |
2668 | self.execution_count += 1 |
|
2660 | self.execution_count += 1 | |
2669 | return error_before_exec(e) |
|
2661 | return error_before_exec(e) | |
2670 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2662 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2671 | MemoryError) as e: |
|
2663 | MemoryError) as e: | |
2672 | self.showsyntaxerror() |
|
2664 | self.showsyntaxerror() | |
2673 | if store_history: |
|
2665 | if store_history: | |
2674 | self.execution_count += 1 |
|
2666 | self.execution_count += 1 | |
2675 | return error_before_exec(e) |
|
2667 | return error_before_exec(e) | |
2676 |
|
2668 | |||
2677 | # Apply AST transformations |
|
2669 | # Apply AST transformations | |
2678 | try: |
|
2670 | try: | |
2679 | code_ast = self.transform_ast(code_ast) |
|
2671 | code_ast = self.transform_ast(code_ast) | |
2680 | except InputRejected as e: |
|
2672 | except InputRejected as e: | |
2681 | self.showtraceback() |
|
2673 | self.showtraceback() | |
2682 | if store_history: |
|
2674 | if store_history: | |
2683 | self.execution_count += 1 |
|
2675 | self.execution_count += 1 | |
2684 | return error_before_exec(e) |
|
2676 | return error_before_exec(e) | |
2685 |
|
2677 | |||
2686 | # Give the displayhook a reference to our ExecutionResult so it |
|
2678 | # Give the displayhook a reference to our ExecutionResult so it | |
2687 | # can fill in the output value. |
|
2679 | # can fill in the output value. | |
2688 | self.displayhook.exec_result = result |
|
2680 | self.displayhook.exec_result = result | |
2689 |
|
2681 | |||
2690 | # Execute the user code |
|
2682 | # Execute the user code | |
2691 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2683 | interactivity = "none" if silent else self.ast_node_interactivity | |
2692 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, |
|
2684 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, | |
2693 | interactivity=interactivity, compiler=compiler, result=result) |
|
2685 | interactivity=interactivity, compiler=compiler, result=result) | |
2694 |
|
2686 | |||
2695 | self.last_execution_succeeded = not has_raised |
|
2687 | self.last_execution_succeeded = not has_raised | |
2696 |
|
2688 | |||
2697 | # Reset this so later displayed values do not modify the |
|
2689 | # Reset this so later displayed values do not modify the | |
2698 | # ExecutionResult |
|
2690 | # ExecutionResult | |
2699 | self.displayhook.exec_result = None |
|
2691 | self.displayhook.exec_result = None | |
2700 |
|
2692 | |||
2701 | self.events.trigger('post_execute') |
|
2693 | self.events.trigger('post_execute') | |
2702 | if not silent: |
|
2694 | if not silent: | |
2703 | self.events.trigger('post_run_cell') |
|
2695 | self.events.trigger('post_run_cell') | |
2704 |
|
2696 | |||
2705 | if store_history: |
|
2697 | if store_history: | |
2706 | # Write output to the database. Does nothing unless |
|
2698 | # Write output to the database. Does nothing unless | |
2707 | # history output logging is enabled. |
|
2699 | # history output logging is enabled. | |
2708 | self.history_manager.store_output(self.execution_count) |
|
2700 | self.history_manager.store_output(self.execution_count) | |
2709 | # Each cell is a *single* input, regardless of how many lines it has |
|
2701 | # Each cell is a *single* input, regardless of how many lines it has | |
2710 | self.execution_count += 1 |
|
2702 | self.execution_count += 1 | |
2711 |
|
2703 | |||
2712 | return result |
|
2704 | return result | |
2713 |
|
2705 | |||
2714 | def transform_ast(self, node): |
|
2706 | def transform_ast(self, node): | |
2715 | """Apply the AST transformations from self.ast_transformers |
|
2707 | """Apply the AST transformations from self.ast_transformers | |
2716 |
|
2708 | |||
2717 | Parameters |
|
2709 | Parameters | |
2718 | ---------- |
|
2710 | ---------- | |
2719 | node : ast.Node |
|
2711 | node : ast.Node | |
2720 | The root node to be transformed. Typically called with the ast.Module |
|
2712 | The root node to be transformed. Typically called with the ast.Module | |
2721 | produced by parsing user input. |
|
2713 | produced by parsing user input. | |
2722 |
|
2714 | |||
2723 | Returns |
|
2715 | Returns | |
2724 | ------- |
|
2716 | ------- | |
2725 | An ast.Node corresponding to the node it was called with. Note that it |
|
2717 | An ast.Node corresponding to the node it was called with. Note that it | |
2726 | may also modify the passed object, so don't rely on references to the |
|
2718 | may also modify the passed object, so don't rely on references to the | |
2727 | original AST. |
|
2719 | original AST. | |
2728 | """ |
|
2720 | """ | |
2729 | for transformer in self.ast_transformers: |
|
2721 | for transformer in self.ast_transformers: | |
2730 | try: |
|
2722 | try: | |
2731 | node = transformer.visit(node) |
|
2723 | node = transformer.visit(node) | |
2732 | except InputRejected: |
|
2724 | except InputRejected: | |
2733 | # User-supplied AST transformers can reject an input by raising |
|
2725 | # User-supplied AST transformers can reject an input by raising | |
2734 | # an InputRejected. Short-circuit in this case so that we |
|
2726 | # an InputRejected. Short-circuit in this case so that we | |
2735 | # don't unregister the transform. |
|
2727 | # don't unregister the transform. | |
2736 | raise |
|
2728 | raise | |
2737 | except Exception: |
|
2729 | except Exception: | |
2738 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2730 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) | |
2739 | self.ast_transformers.remove(transformer) |
|
2731 | self.ast_transformers.remove(transformer) | |
2740 |
|
2732 | |||
2741 | if self.ast_transformers: |
|
2733 | if self.ast_transformers: | |
2742 | ast.fix_missing_locations(node) |
|
2734 | ast.fix_missing_locations(node) | |
2743 | return node |
|
2735 | return node | |
2744 |
|
2736 | |||
2745 |
|
2737 | |||
2746 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2738 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', | |
2747 | compiler=compile, result=None): |
|
2739 | compiler=compile, result=None): | |
2748 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2740 | """Run a sequence of AST nodes. The execution mode depends on the | |
2749 | interactivity parameter. |
|
2741 | interactivity parameter. | |
2750 |
|
2742 | |||
2751 | Parameters |
|
2743 | Parameters | |
2752 | ---------- |
|
2744 | ---------- | |
2753 | nodelist : list |
|
2745 | nodelist : list | |
2754 | A sequence of AST nodes to run. |
|
2746 | A sequence of AST nodes to run. | |
2755 | cell_name : str |
|
2747 | cell_name : str | |
2756 | Will be passed to the compiler as the filename of the cell. Typically |
|
2748 | Will be passed to the compiler as the filename of the cell. Typically | |
2757 | the value returned by ip.compile.cache(cell). |
|
2749 | the value returned by ip.compile.cache(cell). | |
2758 | interactivity : str |
|
2750 | interactivity : str | |
2759 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2751 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2760 | run interactively (displaying output from expressions). 'last_expr' |
|
2752 | run interactively (displaying output from expressions). 'last_expr' | |
2761 | will run the last node interactively only if it is an expression (i.e. |
|
2753 | will run the last node interactively only if it is an expression (i.e. | |
2762 | expressions in loops or other blocks are not displayed. Other values |
|
2754 | expressions in loops or other blocks are not displayed. Other values | |
2763 | for this parameter will raise a ValueError. |
|
2755 | for this parameter will raise a ValueError. | |
2764 | compiler : callable |
|
2756 | compiler : callable | |
2765 | A function with the same interface as the built-in compile(), to turn |
|
2757 | A function with the same interface as the built-in compile(), to turn | |
2766 | the AST nodes into code objects. Default is the built-in compile(). |
|
2758 | the AST nodes into code objects. Default is the built-in compile(). | |
2767 | result : ExecutionResult, optional |
|
2759 | result : ExecutionResult, optional | |
2768 | An object to store exceptions that occur during execution. |
|
2760 | An object to store exceptions that occur during execution. | |
2769 |
|
2761 | |||
2770 | Returns |
|
2762 | Returns | |
2771 | ------- |
|
2763 | ------- | |
2772 | True if an exception occurred while running code, False if it finished |
|
2764 | True if an exception occurred while running code, False if it finished | |
2773 | running. |
|
2765 | running. | |
2774 | """ |
|
2766 | """ | |
2775 | if not nodelist: |
|
2767 | if not nodelist: | |
2776 | return |
|
2768 | return | |
2777 |
|
2769 | |||
2778 | if interactivity == 'last_expr': |
|
2770 | if interactivity == 'last_expr': | |
2779 | if isinstance(nodelist[-1], ast.Expr): |
|
2771 | if isinstance(nodelist[-1], ast.Expr): | |
2780 | interactivity = "last" |
|
2772 | interactivity = "last" | |
2781 | else: |
|
2773 | else: | |
2782 | interactivity = "none" |
|
2774 | interactivity = "none" | |
2783 |
|
2775 | |||
2784 | if interactivity == 'none': |
|
2776 | if interactivity == 'none': | |
2785 | to_run_exec, to_run_interactive = nodelist, [] |
|
2777 | to_run_exec, to_run_interactive = nodelist, [] | |
2786 | elif interactivity == 'last': |
|
2778 | elif interactivity == 'last': | |
2787 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2779 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2788 | elif interactivity == 'all': |
|
2780 | elif interactivity == 'all': | |
2789 | to_run_exec, to_run_interactive = [], nodelist |
|
2781 | to_run_exec, to_run_interactive = [], nodelist | |
2790 | else: |
|
2782 | else: | |
2791 | raise ValueError("Interactivity was %r" % interactivity) |
|
2783 | raise ValueError("Interactivity was %r" % interactivity) | |
2792 |
|
2784 | |||
2793 | try: |
|
2785 | try: | |
2794 | for i, node in enumerate(to_run_exec): |
|
2786 | for i, node in enumerate(to_run_exec): | |
2795 | mod = ast.Module([node]) |
|
2787 | mod = ast.Module([node]) | |
2796 | code = compiler(mod, cell_name, "exec") |
|
2788 | code = compiler(mod, cell_name, "exec") | |
2797 | if self.run_code(code, result): |
|
2789 | if self.run_code(code, result): | |
2798 | return True |
|
2790 | return True | |
2799 |
|
2791 | |||
2800 | for i, node in enumerate(to_run_interactive): |
|
2792 | for i, node in enumerate(to_run_interactive): | |
2801 | mod = ast.Interactive([node]) |
|
2793 | mod = ast.Interactive([node]) | |
2802 | code = compiler(mod, cell_name, "single") |
|
2794 | code = compiler(mod, cell_name, "single") | |
2803 | if self.run_code(code, result): |
|
2795 | if self.run_code(code, result): | |
2804 | return True |
|
2796 | return True | |
2805 |
|
2797 | |||
2806 | # Flush softspace |
|
2798 | # Flush softspace | |
2807 | if softspace(sys.stdout, 0): |
|
2799 | if softspace(sys.stdout, 0): | |
2808 | print() |
|
2800 | print() | |
2809 |
|
2801 | |||
2810 | except: |
|
2802 | except: | |
2811 | # It's possible to have exceptions raised here, typically by |
|
2803 | # It's possible to have exceptions raised here, typically by | |
2812 | # compilation of odd code (such as a naked 'return' outside a |
|
2804 | # compilation of odd code (such as a naked 'return' outside a | |
2813 | # function) that did parse but isn't valid. Typically the exception |
|
2805 | # function) that did parse but isn't valid. Typically the exception | |
2814 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2806 | # is a SyntaxError, but it's safest just to catch anything and show | |
2815 | # the user a traceback. |
|
2807 | # the user a traceback. | |
2816 |
|
2808 | |||
2817 | # We do only one try/except outside the loop to minimize the impact |
|
2809 | # We do only one try/except outside the loop to minimize the impact | |
2818 | # on runtime, and also because if any node in the node list is |
|
2810 | # on runtime, and also because if any node in the node list is | |
2819 | # broken, we should stop execution completely. |
|
2811 | # broken, we should stop execution completely. | |
2820 | if result: |
|
2812 | if result: | |
2821 | result.error_before_exec = sys.exc_info()[1] |
|
2813 | result.error_before_exec = sys.exc_info()[1] | |
2822 | self.showtraceback() |
|
2814 | self.showtraceback() | |
2823 | return True |
|
2815 | return True | |
2824 |
|
2816 | |||
2825 | return False |
|
2817 | return False | |
2826 |
|
2818 | |||
2827 | def run_code(self, code_obj, result=None): |
|
2819 | def run_code(self, code_obj, result=None): | |
2828 | """Execute a code object. |
|
2820 | """Execute a code object. | |
2829 |
|
2821 | |||
2830 | When an exception occurs, self.showtraceback() is called to display a |
|
2822 | When an exception occurs, self.showtraceback() is called to display a | |
2831 | traceback. |
|
2823 | traceback. | |
2832 |
|
2824 | |||
2833 | Parameters |
|
2825 | Parameters | |
2834 | ---------- |
|
2826 | ---------- | |
2835 | code_obj : code object |
|
2827 | code_obj : code object | |
2836 | A compiled code object, to be executed |
|
2828 | A compiled code object, to be executed | |
2837 | result : ExecutionResult, optional |
|
2829 | result : ExecutionResult, optional | |
2838 | An object to store exceptions that occur during execution. |
|
2830 | An object to store exceptions that occur during execution. | |
2839 |
|
2831 | |||
2840 | Returns |
|
2832 | Returns | |
2841 | ------- |
|
2833 | ------- | |
2842 | False : successful execution. |
|
2834 | False : successful execution. | |
2843 | True : an error occurred. |
|
2835 | True : an error occurred. | |
2844 | """ |
|
2836 | """ | |
2845 | # Set our own excepthook in case the user code tries to call it |
|
2837 | # Set our own excepthook in case the user code tries to call it | |
2846 | # directly, so that the IPython crash handler doesn't get triggered |
|
2838 | # directly, so that the IPython crash handler doesn't get triggered | |
2847 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
2839 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook | |
2848 |
|
2840 | |||
2849 | # we save the original sys.excepthook in the instance, in case config |
|
2841 | # we save the original sys.excepthook in the instance, in case config | |
2850 | # code (such as magics) needs access to it. |
|
2842 | # code (such as magics) needs access to it. | |
2851 | self.sys_excepthook = old_excepthook |
|
2843 | self.sys_excepthook = old_excepthook | |
2852 | outflag = 1 # happens in more places, so it's easier as default |
|
2844 | outflag = 1 # happens in more places, so it's easier as default | |
2853 | try: |
|
2845 | try: | |
2854 | try: |
|
2846 | try: | |
2855 | self.hooks.pre_run_code_hook() |
|
2847 | self.hooks.pre_run_code_hook() | |
2856 | #rprint('Running code', repr(code_obj)) # dbg |
|
2848 | #rprint('Running code', repr(code_obj)) # dbg | |
2857 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2849 | exec(code_obj, self.user_global_ns, self.user_ns) | |
2858 | finally: |
|
2850 | finally: | |
2859 | # Reset our crash handler in place |
|
2851 | # Reset our crash handler in place | |
2860 | sys.excepthook = old_excepthook |
|
2852 | sys.excepthook = old_excepthook | |
2861 | except SystemExit as e: |
|
2853 | except SystemExit as e: | |
2862 | if result is not None: |
|
2854 | if result is not None: | |
2863 | result.error_in_exec = e |
|
2855 | result.error_in_exec = e | |
2864 | self.showtraceback(exception_only=True) |
|
2856 | self.showtraceback(exception_only=True) | |
2865 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) |
|
2857 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) | |
2866 | except self.custom_exceptions: |
|
2858 | except self.custom_exceptions: | |
2867 | etype, value, tb = sys.exc_info() |
|
2859 | etype, value, tb = sys.exc_info() | |
2868 | if result is not None: |
|
2860 | if result is not None: | |
2869 | result.error_in_exec = value |
|
2861 | result.error_in_exec = value | |
2870 | self.CustomTB(etype, value, tb) |
|
2862 | self.CustomTB(etype, value, tb) | |
2871 | except: |
|
2863 | except: | |
2872 | if result is not None: |
|
2864 | if result is not None: | |
2873 | result.error_in_exec = sys.exc_info()[1] |
|
2865 | result.error_in_exec = sys.exc_info()[1] | |
2874 | self.showtraceback() |
|
2866 | self.showtraceback() | |
2875 | else: |
|
2867 | else: | |
2876 | outflag = 0 |
|
2868 | outflag = 0 | |
2877 | return outflag |
|
2869 | return outflag | |
2878 |
|
2870 | |||
2879 | # For backwards compatibility |
|
2871 | # For backwards compatibility | |
2880 | runcode = run_code |
|
2872 | runcode = run_code | |
2881 |
|
2873 | |||
2882 | #------------------------------------------------------------------------- |
|
2874 | #------------------------------------------------------------------------- | |
2883 | # Things related to GUI support and pylab |
|
2875 | # Things related to GUI support and pylab | |
2884 | #------------------------------------------------------------------------- |
|
2876 | #------------------------------------------------------------------------- | |
2885 |
|
2877 | |||
2886 | active_eventloop = None |
|
2878 | active_eventloop = None | |
2887 |
|
2879 | |||
2888 | def enable_gui(self, gui=None): |
|
2880 | def enable_gui(self, gui=None): | |
2889 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2881 | raise NotImplementedError('Implement enable_gui in a subclass') | |
2890 |
|
2882 | |||
2891 | def enable_matplotlib(self, gui=None): |
|
2883 | def enable_matplotlib(self, gui=None): | |
2892 | """Enable interactive matplotlib and inline figure support. |
|
2884 | """Enable interactive matplotlib and inline figure support. | |
2893 |
|
2885 | |||
2894 | This takes the following steps: |
|
2886 | This takes the following steps: | |
2895 |
|
2887 | |||
2896 | 1. select the appropriate eventloop and matplotlib backend |
|
2888 | 1. select the appropriate eventloop and matplotlib backend | |
2897 | 2. set up matplotlib for interactive use with that backend |
|
2889 | 2. set up matplotlib for interactive use with that backend | |
2898 | 3. configure formatters for inline figure display |
|
2890 | 3. configure formatters for inline figure display | |
2899 | 4. enable the selected gui eventloop |
|
2891 | 4. enable the selected gui eventloop | |
2900 |
|
2892 | |||
2901 | Parameters |
|
2893 | Parameters | |
2902 | ---------- |
|
2894 | ---------- | |
2903 | gui : optional, string |
|
2895 | gui : optional, string | |
2904 | If given, dictates the choice of matplotlib GUI backend to use |
|
2896 | If given, dictates the choice of matplotlib GUI backend to use | |
2905 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2897 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2906 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2898 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2907 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2899 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2908 | user's matplotlibrc configuration file). Note that not all backends |
|
2900 | user's matplotlibrc configuration file). Note that not all backends | |
2909 | make sense in all contexts, for example a terminal ipython can't |
|
2901 | make sense in all contexts, for example a terminal ipython can't | |
2910 | display figures inline. |
|
2902 | display figures inline. | |
2911 | """ |
|
2903 | """ | |
2912 | from IPython.core import pylabtools as pt |
|
2904 | from IPython.core import pylabtools as pt | |
2913 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2905 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) | |
2914 |
|
2906 | |||
2915 | if gui != 'inline': |
|
2907 | if gui != 'inline': | |
2916 | # If we have our first gui selection, store it |
|
2908 | # If we have our first gui selection, store it | |
2917 | if self.pylab_gui_select is None: |
|
2909 | if self.pylab_gui_select is None: | |
2918 | self.pylab_gui_select = gui |
|
2910 | self.pylab_gui_select = gui | |
2919 | # Otherwise if they are different |
|
2911 | # Otherwise if they are different | |
2920 | elif gui != self.pylab_gui_select: |
|
2912 | elif gui != self.pylab_gui_select: | |
2921 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2913 | print ('Warning: Cannot change to a different GUI toolkit: %s.' | |
2922 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2914 | ' Using %s instead.' % (gui, self.pylab_gui_select)) | |
2923 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2915 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) | |
2924 |
|
2916 | |||
2925 | pt.activate_matplotlib(backend) |
|
2917 | pt.activate_matplotlib(backend) | |
2926 | pt.configure_inline_support(self, backend) |
|
2918 | pt.configure_inline_support(self, backend) | |
2927 |
|
2919 | |||
2928 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2920 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
2929 | # plot updates into account |
|
2921 | # plot updates into account | |
2930 | self.enable_gui(gui) |
|
2922 | self.enable_gui(gui) | |
2931 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2923 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ | |
2932 | pt.mpl_runner(self.safe_execfile) |
|
2924 | pt.mpl_runner(self.safe_execfile) | |
2933 |
|
2925 | |||
2934 | return gui, backend |
|
2926 | return gui, backend | |
2935 |
|
2927 | |||
2936 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2928 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): | |
2937 | """Activate pylab support at runtime. |
|
2929 | """Activate pylab support at runtime. | |
2938 |
|
2930 | |||
2939 | This turns on support for matplotlib, preloads into the interactive |
|
2931 | This turns on support for matplotlib, preloads into the interactive | |
2940 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2932 | namespace all of numpy and pylab, and configures IPython to correctly | |
2941 | interact with the GUI event loop. The GUI backend to be used can be |
|
2933 | interact with the GUI event loop. The GUI backend to be used can be | |
2942 | optionally selected with the optional ``gui`` argument. |
|
2934 | optionally selected with the optional ``gui`` argument. | |
2943 |
|
2935 | |||
2944 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
2936 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. | |
2945 |
|
2937 | |||
2946 | Parameters |
|
2938 | Parameters | |
2947 | ---------- |
|
2939 | ---------- | |
2948 | gui : optional, string |
|
2940 | gui : optional, string | |
2949 | If given, dictates the choice of matplotlib GUI backend to use |
|
2941 | If given, dictates the choice of matplotlib GUI backend to use | |
2950 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2942 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2951 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2943 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2952 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2944 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2953 | user's matplotlibrc configuration file). Note that not all backends |
|
2945 | user's matplotlibrc configuration file). Note that not all backends | |
2954 | make sense in all contexts, for example a terminal ipython can't |
|
2946 | make sense in all contexts, for example a terminal ipython can't | |
2955 | display figures inline. |
|
2947 | display figures inline. | |
2956 | import_all : optional, bool, default: True |
|
2948 | import_all : optional, bool, default: True | |
2957 | Whether to do `from numpy import *` and `from pylab import *` |
|
2949 | Whether to do `from numpy import *` and `from pylab import *` | |
2958 | in addition to module imports. |
|
2950 | in addition to module imports. | |
2959 | welcome_message : deprecated |
|
2951 | welcome_message : deprecated | |
2960 | This argument is ignored, no welcome message will be displayed. |
|
2952 | This argument is ignored, no welcome message will be displayed. | |
2961 | """ |
|
2953 | """ | |
2962 | from IPython.core.pylabtools import import_pylab |
|
2954 | from IPython.core.pylabtools import import_pylab | |
2963 |
|
2955 | |||
2964 | gui, backend = self.enable_matplotlib(gui) |
|
2956 | gui, backend = self.enable_matplotlib(gui) | |
2965 |
|
2957 | |||
2966 | # We want to prevent the loading of pylab to pollute the user's |
|
2958 | # We want to prevent the loading of pylab to pollute the user's | |
2967 | # namespace as shown by the %who* magics, so we execute the activation |
|
2959 | # namespace as shown by the %who* magics, so we execute the activation | |
2968 | # code in an empty namespace, and we update *both* user_ns and |
|
2960 | # code in an empty namespace, and we update *both* user_ns and | |
2969 | # user_ns_hidden with this information. |
|
2961 | # user_ns_hidden with this information. | |
2970 | ns = {} |
|
2962 | ns = {} | |
2971 | import_pylab(ns, import_all) |
|
2963 | import_pylab(ns, import_all) | |
2972 | # warn about clobbered names |
|
2964 | # warn about clobbered names | |
2973 | ignored = {"__builtins__"} |
|
2965 | ignored = {"__builtins__"} | |
2974 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
2966 | both = set(ns).intersection(self.user_ns).difference(ignored) | |
2975 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
2967 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] | |
2976 | self.user_ns.update(ns) |
|
2968 | self.user_ns.update(ns) | |
2977 | self.user_ns_hidden.update(ns) |
|
2969 | self.user_ns_hidden.update(ns) | |
2978 | return gui, backend, clobbered |
|
2970 | return gui, backend, clobbered | |
2979 |
|
2971 | |||
2980 | #------------------------------------------------------------------------- |
|
2972 | #------------------------------------------------------------------------- | |
2981 | # Utilities |
|
2973 | # Utilities | |
2982 | #------------------------------------------------------------------------- |
|
2974 | #------------------------------------------------------------------------- | |
2983 |
|
2975 | |||
2984 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2976 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
2985 | """Expand python variables in a string. |
|
2977 | """Expand python variables in a string. | |
2986 |
|
2978 | |||
2987 | The depth argument indicates how many frames above the caller should |
|
2979 | The depth argument indicates how many frames above the caller should | |
2988 | be walked to look for the local namespace where to expand variables. |
|
2980 | be walked to look for the local namespace where to expand variables. | |
2989 |
|
2981 | |||
2990 | The global namespace for expansion is always the user's interactive |
|
2982 | The global namespace for expansion is always the user's interactive | |
2991 | namespace. |
|
2983 | namespace. | |
2992 | """ |
|
2984 | """ | |
2993 | ns = self.user_ns.copy() |
|
2985 | ns = self.user_ns.copy() | |
2994 | try: |
|
2986 | try: | |
2995 | frame = sys._getframe(depth+1) |
|
2987 | frame = sys._getframe(depth+1) | |
2996 | except ValueError: |
|
2988 | except ValueError: | |
2997 | # This is thrown if there aren't that many frames on the stack, |
|
2989 | # This is thrown if there aren't that many frames on the stack, | |
2998 | # e.g. if a script called run_line_magic() directly. |
|
2990 | # e.g. if a script called run_line_magic() directly. | |
2999 | pass |
|
2991 | pass | |
3000 | else: |
|
2992 | else: | |
3001 | ns.update(frame.f_locals) |
|
2993 | ns.update(frame.f_locals) | |
3002 |
|
2994 | |||
3003 | try: |
|
2995 | try: | |
3004 | # We have to use .vformat() here, because 'self' is a valid and common |
|
2996 | # We have to use .vformat() here, because 'self' is a valid and common | |
3005 | # name, and expanding **ns for .format() would make it collide with |
|
2997 | # name, and expanding **ns for .format() would make it collide with | |
3006 | # the 'self' argument of the method. |
|
2998 | # the 'self' argument of the method. | |
3007 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
2999 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) | |
3008 | except Exception: |
|
3000 | except Exception: | |
3009 | # if formatter couldn't format, just let it go untransformed |
|
3001 | # if formatter couldn't format, just let it go untransformed | |
3010 | pass |
|
3002 | pass | |
3011 | return cmd |
|
3003 | return cmd | |
3012 |
|
3004 | |||
3013 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3005 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
3014 | """Make a new tempfile and return its filename. |
|
3006 | """Make a new tempfile and return its filename. | |
3015 |
|
3007 | |||
3016 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3008 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), | |
3017 | but it registers the created filename internally so ipython cleans it up |
|
3009 | but it registers the created filename internally so ipython cleans it up | |
3018 | at exit time. |
|
3010 | at exit time. | |
3019 |
|
3011 | |||
3020 | Optional inputs: |
|
3012 | Optional inputs: | |
3021 |
|
3013 | |||
3022 | - data(None): if data is given, it gets written out to the temp file |
|
3014 | - data(None): if data is given, it gets written out to the temp file | |
3023 | immediately, and the file is closed again.""" |
|
3015 | immediately, and the file is closed again.""" | |
3024 |
|
3016 | |||
3025 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3017 | dirname = tempfile.mkdtemp(prefix=prefix) | |
3026 | self.tempdirs.append(dirname) |
|
3018 | self.tempdirs.append(dirname) | |
3027 |
|
3019 | |||
3028 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3020 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) | |
3029 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3021 | os.close(handle) # On Windows, there can only be one open handle on a file | |
3030 | self.tempfiles.append(filename) |
|
3022 | self.tempfiles.append(filename) | |
3031 |
|
3023 | |||
3032 | if data: |
|
3024 | if data: | |
3033 | tmp_file = open(filename,'w') |
|
3025 | tmp_file = open(filename,'w') | |
3034 | tmp_file.write(data) |
|
3026 | tmp_file.write(data) | |
3035 | tmp_file.close() |
|
3027 | tmp_file.close() | |
3036 | return filename |
|
3028 | return filename | |
3037 |
|
3029 | |||
3038 | @undoc |
|
3030 | @undoc | |
3039 | def write(self,data): |
|
3031 | def write(self,data): | |
3040 | """DEPRECATED: Write a string to the default output""" |
|
3032 | """DEPRECATED: Write a string to the default output""" | |
3041 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3033 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', | |
3042 | DeprecationWarning, stacklevel=2) |
|
3034 | DeprecationWarning, stacklevel=2) | |
3043 | sys.stdout.write(data) |
|
3035 | sys.stdout.write(data) | |
3044 |
|
3036 | |||
3045 | @undoc |
|
3037 | @undoc | |
3046 | def write_err(self,data): |
|
3038 | def write_err(self,data): | |
3047 | """DEPRECATED: Write a string to the default error output""" |
|
3039 | """DEPRECATED: Write a string to the default error output""" | |
3048 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3040 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', | |
3049 | DeprecationWarning, stacklevel=2) |
|
3041 | DeprecationWarning, stacklevel=2) | |
3050 | sys.stderr.write(data) |
|
3042 | sys.stderr.write(data) | |
3051 |
|
3043 | |||
3052 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3044 | def ask_yes_no(self, prompt, default=None, interrupt=None): | |
3053 | if self.quiet: |
|
3045 | if self.quiet: | |
3054 | return True |
|
3046 | return True | |
3055 | return ask_yes_no(prompt,default,interrupt) |
|
3047 | return ask_yes_no(prompt,default,interrupt) | |
3056 |
|
3048 | |||
3057 | def show_usage(self): |
|
3049 | def show_usage(self): | |
3058 | """Show a usage message""" |
|
3050 | """Show a usage message""" | |
3059 | page.page(IPython.core.usage.interactive_usage) |
|
3051 | page.page(IPython.core.usage.interactive_usage) | |
3060 |
|
3052 | |||
3061 | def extract_input_lines(self, range_str, raw=False): |
|
3053 | def extract_input_lines(self, range_str, raw=False): | |
3062 | """Return as a string a set of input history slices. |
|
3054 | """Return as a string a set of input history slices. | |
3063 |
|
3055 | |||
3064 | Parameters |
|
3056 | Parameters | |
3065 | ---------- |
|
3057 | ---------- | |
3066 | range_str : string |
|
3058 | range_str : string | |
3067 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3059 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
3068 | since this function is for use by magic functions which get their |
|
3060 | since this function is for use by magic functions which get their | |
3069 | arguments as strings. The number before the / is the session |
|
3061 | arguments as strings. The number before the / is the session | |
3070 | number: ~n goes n back from the current session. |
|
3062 | number: ~n goes n back from the current session. | |
3071 |
|
3063 | |||
3072 | raw : bool, optional |
|
3064 | raw : bool, optional | |
3073 | By default, the processed input is used. If this is true, the raw |
|
3065 | By default, the processed input is used. If this is true, the raw | |
3074 | input history is used instead. |
|
3066 | input history is used instead. | |
3075 |
|
3067 | |||
3076 | Notes |
|
3068 | Notes | |
3077 | ----- |
|
3069 | ----- | |
3078 |
|
3070 | |||
3079 | Slices can be described with two notations: |
|
3071 | Slices can be described with two notations: | |
3080 |
|
3072 | |||
3081 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3073 | * ``N:M`` -> standard python form, means including items N...(M-1). | |
3082 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3074 | * ``N-M`` -> include items N..M (closed endpoint). | |
3083 | """ |
|
3075 | """ | |
3084 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3076 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) | |
3085 | return "\n".join(x for _, _, x in lines) |
|
3077 | return "\n".join(x for _, _, x in lines) | |
3086 |
|
3078 | |||
3087 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3079 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): | |
3088 | """Get a code string from history, file, url, or a string or macro. |
|
3080 | """Get a code string from history, file, url, or a string or macro. | |
3089 |
|
3081 | |||
3090 | This is mainly used by magic functions. |
|
3082 | This is mainly used by magic functions. | |
3091 |
|
3083 | |||
3092 | Parameters |
|
3084 | Parameters | |
3093 | ---------- |
|
3085 | ---------- | |
3094 |
|
3086 | |||
3095 | target : str |
|
3087 | target : str | |
3096 |
|
3088 | |||
3097 | A string specifying code to retrieve. This will be tried respectively |
|
3089 | A string specifying code to retrieve. This will be tried respectively | |
3098 | as: ranges of input history (see %history for syntax), url, |
|
3090 | as: ranges of input history (see %history for syntax), url, | |
3099 | corresponding .py file, filename, or an expression evaluating to a |
|
3091 | corresponding .py file, filename, or an expression evaluating to a | |
3100 | string or Macro in the user namespace. |
|
3092 | string or Macro in the user namespace. | |
3101 |
|
3093 | |||
3102 | raw : bool |
|
3094 | raw : bool | |
3103 | If true (default), retrieve raw history. Has no effect on the other |
|
3095 | If true (default), retrieve raw history. Has no effect on the other | |
3104 | retrieval mechanisms. |
|
3096 | retrieval mechanisms. | |
3105 |
|
3097 | |||
3106 | py_only : bool (default False) |
|
3098 | py_only : bool (default False) | |
3107 | Only try to fetch python code, do not try alternative methods to decode file |
|
3099 | Only try to fetch python code, do not try alternative methods to decode file | |
3108 | if unicode fails. |
|
3100 | if unicode fails. | |
3109 |
|
3101 | |||
3110 | Returns |
|
3102 | Returns | |
3111 | ------- |
|
3103 | ------- | |
3112 | A string of code. |
|
3104 | A string of code. | |
3113 |
|
3105 | |||
3114 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3106 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
3115 | to an object of another type. In each case, .args[0] is a printable |
|
3107 | to an object of another type. In each case, .args[0] is a printable | |
3116 | message. |
|
3108 | message. | |
3117 | """ |
|
3109 | """ | |
3118 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3110 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
3119 | if code: |
|
3111 | if code: | |
3120 | return code |
|
3112 | return code | |
3121 | try: |
|
3113 | try: | |
3122 | if target.startswith(('http://', 'https://')): |
|
3114 | if target.startswith(('http://', 'https://')): | |
3123 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3115 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) | |
3124 | except UnicodeDecodeError: |
|
3116 | except UnicodeDecodeError: | |
3125 | if not py_only : |
|
3117 | if not py_only : | |
3126 | # Deferred import |
|
3118 | # Deferred import | |
3127 | from urllib.request import urlopen |
|
3119 | from urllib.request import urlopen | |
3128 | response = urlopen(target) |
|
3120 | response = urlopen(target) | |
3129 | return response.read().decode('latin1') |
|
3121 | return response.read().decode('latin1') | |
3130 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3122 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3131 |
|
3123 | |||
3132 | potential_target = [target] |
|
3124 | potential_target = [target] | |
3133 | try : |
|
3125 | try : | |
3134 | potential_target.insert(0,get_py_filename(target)) |
|
3126 | potential_target.insert(0,get_py_filename(target)) | |
3135 | except IOError: |
|
3127 | except IOError: | |
3136 | pass |
|
3128 | pass | |
3137 |
|
3129 | |||
3138 | for tgt in potential_target : |
|
3130 | for tgt in potential_target : | |
3139 | if os.path.isfile(tgt): # Read file |
|
3131 | if os.path.isfile(tgt): # Read file | |
3140 | try : |
|
3132 | try : | |
3141 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3133 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) | |
3142 | except UnicodeDecodeError : |
|
3134 | except UnicodeDecodeError : | |
3143 | if not py_only : |
|
3135 | if not py_only : | |
3144 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3136 | with io_open(tgt,'r', encoding='latin1') as f : | |
3145 | return f.read() |
|
3137 | return f.read() | |
3146 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3138 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3147 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3139 | elif os.path.isdir(os.path.expanduser(tgt)): | |
3148 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3140 | raise ValueError("'%s' is a directory, not a regular file." % target) | |
3149 |
|
3141 | |||
3150 | if search_ns: |
|
3142 | if search_ns: | |
3151 | # Inspect namespace to load object source |
|
3143 | # Inspect namespace to load object source | |
3152 | object_info = self.object_inspect(target, detail_level=1) |
|
3144 | object_info = self.object_inspect(target, detail_level=1) | |
3153 | if object_info['found'] and object_info['source']: |
|
3145 | if object_info['found'] and object_info['source']: | |
3154 | return object_info['source'] |
|
3146 | return object_info['source'] | |
3155 |
|
3147 | |||
3156 | try: # User namespace |
|
3148 | try: # User namespace | |
3157 | codeobj = eval(target, self.user_ns) |
|
3149 | codeobj = eval(target, self.user_ns) | |
3158 | except Exception: |
|
3150 | except Exception: | |
3159 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3151 | raise ValueError(("'%s' was not found in history, as a file, url, " | |
3160 | "nor in the user namespace.") % target) |
|
3152 | "nor in the user namespace.") % target) | |
3161 |
|
3153 | |||
3162 | if isinstance(codeobj, str): |
|
3154 | if isinstance(codeobj, str): | |
3163 | return codeobj |
|
3155 | return codeobj | |
3164 | elif isinstance(codeobj, Macro): |
|
3156 | elif isinstance(codeobj, Macro): | |
3165 | return codeobj.value |
|
3157 | return codeobj.value | |
3166 |
|
3158 | |||
3167 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3159 | raise TypeError("%s is neither a string nor a macro." % target, | |
3168 | codeobj) |
|
3160 | codeobj) | |
3169 |
|
3161 | |||
3170 | #------------------------------------------------------------------------- |
|
3162 | #------------------------------------------------------------------------- | |
3171 | # Things related to IPython exiting |
|
3163 | # Things related to IPython exiting | |
3172 | #------------------------------------------------------------------------- |
|
3164 | #------------------------------------------------------------------------- | |
3173 | def atexit_operations(self): |
|
3165 | def atexit_operations(self): | |
3174 | """This will be executed at the time of exit. |
|
3166 | """This will be executed at the time of exit. | |
3175 |
|
3167 | |||
3176 | Cleanup operations and saving of persistent data that is done |
|
3168 | Cleanup operations and saving of persistent data that is done | |
3177 | unconditionally by IPython should be performed here. |
|
3169 | unconditionally by IPython should be performed here. | |
3178 |
|
3170 | |||
3179 | For things that may depend on startup flags or platform specifics (such |
|
3171 | For things that may depend on startup flags or platform specifics (such | |
3180 | as having readline or not), register a separate atexit function in the |
|
3172 | as having readline or not), register a separate atexit function in the | |
3181 | code that has the appropriate information, rather than trying to |
|
3173 | code that has the appropriate information, rather than trying to | |
3182 | clutter |
|
3174 | clutter | |
3183 | """ |
|
3175 | """ | |
3184 | # Close the history session (this stores the end time and line count) |
|
3176 | # Close the history session (this stores the end time and line count) | |
3185 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3177 | # this must be *before* the tempfile cleanup, in case of temporary | |
3186 | # history db |
|
3178 | # history db | |
3187 | self.history_manager.end_session() |
|
3179 | self.history_manager.end_session() | |
3188 |
|
3180 | |||
3189 | # Cleanup all tempfiles and folders left around |
|
3181 | # Cleanup all tempfiles and folders left around | |
3190 | for tfile in self.tempfiles: |
|
3182 | for tfile in self.tempfiles: | |
3191 | try: |
|
3183 | try: | |
3192 | os.unlink(tfile) |
|
3184 | os.unlink(tfile) | |
3193 | except OSError: |
|
3185 | except OSError: | |
3194 | pass |
|
3186 | pass | |
3195 |
|
3187 | |||
3196 | for tdir in self.tempdirs: |
|
3188 | for tdir in self.tempdirs: | |
3197 | try: |
|
3189 | try: | |
3198 | os.rmdir(tdir) |
|
3190 | os.rmdir(tdir) | |
3199 | except OSError: |
|
3191 | except OSError: | |
3200 | pass |
|
3192 | pass | |
3201 |
|
3193 | |||
3202 | # Clear all user namespaces to release all references cleanly. |
|
3194 | # Clear all user namespaces to release all references cleanly. | |
3203 | self.reset(new_session=False) |
|
3195 | self.reset(new_session=False) | |
3204 |
|
3196 | |||
3205 | # Run user hooks |
|
3197 | # Run user hooks | |
3206 | self.hooks.shutdown_hook() |
|
3198 | self.hooks.shutdown_hook() | |
3207 |
|
3199 | |||
3208 | def cleanup(self): |
|
3200 | def cleanup(self): | |
3209 | self.restore_sys_module_state() |
|
3201 | self.restore_sys_module_state() | |
3210 |
|
3202 | |||
3211 |
|
3203 | |||
3212 | # Overridden in terminal subclass to change prompts |
|
3204 | # Overridden in terminal subclass to change prompts | |
3213 | def switch_doctest_mode(self, mode): |
|
3205 | def switch_doctest_mode(self, mode): | |
3214 | pass |
|
3206 | pass | |
3215 |
|
3207 | |||
3216 |
|
3208 | |||
3217 | class InteractiveShellABC(metaclass=abc.ABCMeta): |
|
3209 | class InteractiveShellABC(metaclass=abc.ABCMeta): | |
3218 | """An abstract base class for InteractiveShell.""" |
|
3210 | """An abstract base class for InteractiveShell.""" | |
3219 |
|
3211 | |||
3220 | InteractiveShellABC.register(InteractiveShell) |
|
3212 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,1488 +1,1469 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Verbose and colourful traceback formatting. |
|
3 | Verbose and colourful traceback formatting. | |
4 |
|
4 | |||
5 | **ColorTB** |
|
5 | **ColorTB** | |
6 |
|
6 | |||
7 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
7 | I've always found it a bit hard to visually parse tracebacks in Python. The | |
8 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
8 | ColorTB class is a solution to that problem. It colors the different parts of a | |
9 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
9 | traceback in a manner similar to what you would expect from a syntax-highlighting | |
10 | text editor. |
|
10 | text editor. | |
11 |
|
11 | |||
12 | Installation instructions for ColorTB:: |
|
12 | Installation instructions for ColorTB:: | |
13 |
|
13 | |||
14 | import sys,ultratb |
|
14 | import sys,ultratb | |
15 | sys.excepthook = ultratb.ColorTB() |
|
15 | sys.excepthook = ultratb.ColorTB() | |
16 |
|
16 | |||
17 | **VerboseTB** |
|
17 | **VerboseTB** | |
18 |
|
18 | |||
19 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
19 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | |
20 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
20 | of useful info when a traceback occurs. Ping originally had it spit out HTML | |
21 | and intended it for CGI programmers, but why should they have all the fun? I |
|
21 | and intended it for CGI programmers, but why should they have all the fun? I | |
22 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
22 | altered it to spit out colored text to the terminal. It's a bit overwhelming, | |
23 | but kind of neat, and maybe useful for long-running programs that you believe |
|
23 | but kind of neat, and maybe useful for long-running programs that you believe | |
24 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
24 | are bug-free. If a crash *does* occur in that type of program you want details. | |
25 | Give it a shot--you'll love it or you'll hate it. |
|
25 | Give it a shot--you'll love it or you'll hate it. | |
26 |
|
26 | |||
27 | .. note:: |
|
27 | .. note:: | |
28 |
|
28 | |||
29 | The Verbose mode prints the variables currently visible where the exception |
|
29 | The Verbose mode prints the variables currently visible where the exception | |
30 | happened (shortening their strings if too long). This can potentially be |
|
30 | happened (shortening their strings if too long). This can potentially be | |
31 | very slow, if you happen to have a huge data structure whose string |
|
31 | very slow, if you happen to have a huge data structure whose string | |
32 | representation is complex to compute. Your computer may appear to freeze for |
|
32 | representation is complex to compute. Your computer may appear to freeze for | |
33 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
33 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback | |
34 | with Ctrl-C (maybe hitting it more than once). |
|
34 | with Ctrl-C (maybe hitting it more than once). | |
35 |
|
35 | |||
36 | If you encounter this kind of situation often, you may want to use the |
|
36 | If you encounter this kind of situation often, you may want to use the | |
37 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
37 | Verbose_novars mode instead of the regular Verbose, which avoids formatting | |
38 | variables (but otherwise includes the information and context given by |
|
38 | variables (but otherwise includes the information and context given by | |
39 | Verbose). |
|
39 | Verbose). | |
40 |
|
40 | |||
41 | .. note:: |
|
41 | .. note:: | |
42 |
|
42 | |||
43 | The verbose mode print all variables in the stack, which means it can |
|
43 | The verbose mode print all variables in the stack, which means it can | |
44 | potentially leak sensitive information like access keys, or unencryted |
|
44 | potentially leak sensitive information like access keys, or unencryted | |
45 | password. |
|
45 | password. | |
46 |
|
46 | |||
47 | Installation instructions for VerboseTB:: |
|
47 | Installation instructions for VerboseTB:: | |
48 |
|
48 | |||
49 | import sys,ultratb |
|
49 | import sys,ultratb | |
50 | sys.excepthook = ultratb.VerboseTB() |
|
50 | sys.excepthook = ultratb.VerboseTB() | |
51 |
|
51 | |||
52 | Note: Much of the code in this module was lifted verbatim from the standard |
|
52 | Note: Much of the code in this module was lifted verbatim from the standard | |
53 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
53 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | |
54 |
|
54 | |||
55 | Color schemes |
|
55 | Color schemes | |
56 | ------------- |
|
56 | ------------- | |
57 |
|
57 | |||
58 | The colors are defined in the class TBTools through the use of the |
|
58 | The colors are defined in the class TBTools through the use of the | |
59 | ColorSchemeTable class. Currently the following exist: |
|
59 | ColorSchemeTable class. Currently the following exist: | |
60 |
|
60 | |||
61 | - NoColor: allows all of this module to be used in any terminal (the color |
|
61 | - NoColor: allows all of this module to be used in any terminal (the color | |
62 | escapes are just dummy blank strings). |
|
62 | escapes are just dummy blank strings). | |
63 |
|
63 | |||
64 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
64 | - Linux: is meant to look good in a terminal like the Linux console (black | |
65 | or very dark background). |
|
65 | or very dark background). | |
66 |
|
66 | |||
67 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
67 | - LightBG: similar to Linux but swaps dark/light colors to be more readable | |
68 | in light background terminals. |
|
68 | in light background terminals. | |
69 |
|
69 | |||
70 | - Neutral: a neutral color scheme that should be readable on both light and |
|
70 | - Neutral: a neutral color scheme that should be readable on both light and | |
71 | dark background |
|
71 | dark background | |
72 |
|
72 | |||
73 | You can implement other color schemes easily, the syntax is fairly |
|
73 | You can implement other color schemes easily, the syntax is fairly | |
74 | self-explanatory. Please send back new schemes you develop to the author for |
|
74 | self-explanatory. Please send back new schemes you develop to the author for | |
75 | possible inclusion in future releases. |
|
75 | possible inclusion in future releases. | |
76 |
|
76 | |||
77 | Inheritance diagram: |
|
77 | Inheritance diagram: | |
78 |
|
78 | |||
79 | .. inheritance-diagram:: IPython.core.ultratb |
|
79 | .. inheritance-diagram:: IPython.core.ultratb | |
80 | :parts: 3 |
|
80 | :parts: 3 | |
81 | """ |
|
81 | """ | |
82 |
|
82 | |||
83 | #***************************************************************************** |
|
83 | #***************************************************************************** | |
84 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
84 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> | |
85 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
85 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
86 | # |
|
86 | # | |
87 | # Distributed under the terms of the BSD License. The full license is in |
|
87 | # Distributed under the terms of the BSD License. The full license is in | |
88 | # the file COPYING, distributed as part of this software. |
|
88 | # the file COPYING, distributed as part of this software. | |
89 | #***************************************************************************** |
|
89 | #***************************************************************************** | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | import dis |
|
92 | import dis | |
93 | import inspect |
|
93 | import inspect | |
94 | import keyword |
|
94 | import keyword | |
95 | import linecache |
|
95 | import linecache | |
96 | import os |
|
96 | import os | |
97 | import pydoc |
|
97 | import pydoc | |
98 | import re |
|
98 | import re | |
99 | import sys |
|
99 | import sys | |
100 | import time |
|
100 | import time | |
101 | import tokenize |
|
101 | import tokenize | |
102 | import traceback |
|
102 | import traceback | |
103 | import types |
|
103 | import types | |
104 |
|
104 | |||
105 | try: # Python 2 |
|
105 | try: # Python 2 | |
106 | generate_tokens = tokenize.generate_tokens |
|
106 | generate_tokens = tokenize.generate_tokens | |
107 | except AttributeError: # Python 3 |
|
107 | except AttributeError: # Python 3 | |
108 | generate_tokens = tokenize.tokenize |
|
108 | generate_tokens = tokenize.tokenize | |
109 |
|
109 | |||
110 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
110 | # For purposes of monkeypatching inspect to fix a bug in it. | |
111 | from inspect import getsourcefile, getfile, getmodule, \ |
|
111 | from inspect import getsourcefile, getfile, getmodule, \ | |
112 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
112 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode | |
113 |
|
113 | |||
114 | # IPython's own modules |
|
114 | # IPython's own modules | |
115 | from IPython import get_ipython |
|
115 | from IPython import get_ipython | |
116 | from IPython.core import debugger |
|
116 | from IPython.core import debugger | |
117 | from IPython.core.display_trap import DisplayTrap |
|
117 | from IPython.core.display_trap import DisplayTrap | |
118 | from IPython.core.excolors import exception_colors |
|
118 | from IPython.core.excolors import exception_colors | |
119 | from IPython.utils import PyColorize |
|
119 | from IPython.utils import PyColorize | |
120 | from IPython.utils import openpy |
|
120 | from IPython.utils import openpy | |
121 | from IPython.utils import path as util_path |
|
121 | from IPython.utils import path as util_path | |
122 | from IPython.utils import py3compat |
|
122 | from IPython.utils import py3compat | |
123 | from IPython.utils import ulinecache |
|
123 | from IPython.utils import ulinecache | |
124 | from IPython.utils.data import uniq_stable |
|
124 | from IPython.utils.data import uniq_stable | |
125 | from IPython.utils.terminal import get_terminal_size |
|
125 | from IPython.utils.terminal import get_terminal_size | |
126 | from logging import info, error |
|
126 | from logging import info, error | |
127 |
|
127 | |||
128 | import IPython.utils.colorable as colorable |
|
128 | import IPython.utils.colorable as colorable | |
129 |
|
129 | |||
130 | # Globals |
|
130 | # Globals | |
131 | # amount of space to put line numbers before verbose tracebacks |
|
131 | # amount of space to put line numbers before verbose tracebacks | |
132 | INDENT_SIZE = 8 |
|
132 | INDENT_SIZE = 8 | |
133 |
|
133 | |||
134 | # Default color scheme. This is used, for example, by the traceback |
|
134 | # Default color scheme. This is used, for example, by the traceback | |
135 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
135 | # formatter. When running in an actual IPython instance, the user's rc.colors | |
136 | # value is used, but having a module global makes this functionality available |
|
136 | # value is used, but having a module global makes this functionality available | |
137 | # to users of ultratb who are NOT running inside ipython. |
|
137 | # to users of ultratb who are NOT running inside ipython. | |
138 | DEFAULT_SCHEME = 'NoColor' |
|
138 | DEFAULT_SCHEME = 'NoColor' | |
139 |
|
139 | |||
140 | # --------------------------------------------------------------------------- |
|
140 | # --------------------------------------------------------------------------- | |
141 | # Code begins |
|
141 | # Code begins | |
142 |
|
142 | |||
143 | # Utility functions |
|
143 | # Utility functions | |
144 | def inspect_error(): |
|
144 | def inspect_error(): | |
145 | """Print a message about internal inspect errors. |
|
145 | """Print a message about internal inspect errors. | |
146 |
|
146 | |||
147 | These are unfortunately quite common.""" |
|
147 | These are unfortunately quite common.""" | |
148 |
|
148 | |||
149 | error('Internal Python error in the inspect module.\n' |
|
149 | error('Internal Python error in the inspect module.\n' | |
150 | 'Below is the traceback from this internal error.\n') |
|
150 | 'Below is the traceback from this internal error.\n') | |
151 |
|
151 | |||
152 |
|
152 | |||
153 | # This function is a monkeypatch we apply to the Python inspect module. We have |
|
153 | # This function is a monkeypatch we apply to the Python inspect module. We have | |
154 | # now found when it's needed (see discussion on issue gh-1456), and we have a |
|
154 | # now found when it's needed (see discussion on issue gh-1456), and we have a | |
155 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if |
|
155 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if | |
156 | # the monkeypatch is not applied. TK, Aug 2012. |
|
156 | # the monkeypatch is not applied. TK, Aug 2012. | |
157 | def findsource(object): |
|
157 | def findsource(object): | |
158 | """Return the entire source file and starting line number for an object. |
|
158 | """Return the entire source file and starting line number for an object. | |
159 |
|
159 | |||
160 | The argument may be a module, class, method, function, traceback, frame, |
|
160 | The argument may be a module, class, method, function, traceback, frame, | |
161 | or code object. The source code is returned as a list of all the lines |
|
161 | or code object. The source code is returned as a list of all the lines | |
162 | in the file and the line number indexes a line in that list. An IOError |
|
162 | in the file and the line number indexes a line in that list. An IOError | |
163 | is raised if the source code cannot be retrieved. |
|
163 | is raised if the source code cannot be retrieved. | |
164 |
|
164 | |||
165 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
165 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" | |
166 |
|
166 | |||
167 | file = getsourcefile(object) or getfile(object) |
|
167 | file = getsourcefile(object) or getfile(object) | |
168 | # If the object is a frame, then trying to get the globals dict from its |
|
168 | # If the object is a frame, then trying to get the globals dict from its | |
169 | # module won't work. Instead, the frame object itself has the globals |
|
169 | # module won't work. Instead, the frame object itself has the globals | |
170 | # dictionary. |
|
170 | # dictionary. | |
171 | globals_dict = None |
|
171 | globals_dict = None | |
172 | if inspect.isframe(object): |
|
172 | if inspect.isframe(object): | |
173 | # XXX: can this ever be false? |
|
173 | # XXX: can this ever be false? | |
174 | globals_dict = object.f_globals |
|
174 | globals_dict = object.f_globals | |
175 | else: |
|
175 | else: | |
176 | module = getmodule(object, file) |
|
176 | module = getmodule(object, file) | |
177 | if module: |
|
177 | if module: | |
178 | globals_dict = module.__dict__ |
|
178 | globals_dict = module.__dict__ | |
179 | lines = linecache.getlines(file, globals_dict) |
|
179 | lines = linecache.getlines(file, globals_dict) | |
180 | if not lines: |
|
180 | if not lines: | |
181 | raise IOError('could not get source code') |
|
181 | raise IOError('could not get source code') | |
182 |
|
182 | |||
183 | if ismodule(object): |
|
183 | if ismodule(object): | |
184 | return lines, 0 |
|
184 | return lines, 0 | |
185 |
|
185 | |||
186 | if isclass(object): |
|
186 | if isclass(object): | |
187 | name = object.__name__ |
|
187 | name = object.__name__ | |
188 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
188 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') | |
189 | # make some effort to find the best matching class definition: |
|
189 | # make some effort to find the best matching class definition: | |
190 | # use the one with the least indentation, which is the one |
|
190 | # use the one with the least indentation, which is the one | |
191 | # that's most probably not inside a function definition. |
|
191 | # that's most probably not inside a function definition. | |
192 | candidates = [] |
|
192 | candidates = [] | |
193 | for i in range(len(lines)): |
|
193 | for i in range(len(lines)): | |
194 | match = pat.match(lines[i]) |
|
194 | match = pat.match(lines[i]) | |
195 | if match: |
|
195 | if match: | |
196 | # if it's at toplevel, it's already the best one |
|
196 | # if it's at toplevel, it's already the best one | |
197 | if lines[i][0] == 'c': |
|
197 | if lines[i][0] == 'c': | |
198 | return lines, i |
|
198 | return lines, i | |
199 | # else add whitespace to candidate list |
|
199 | # else add whitespace to candidate list | |
200 | candidates.append((match.group(1), i)) |
|
200 | candidates.append((match.group(1), i)) | |
201 | if candidates: |
|
201 | if candidates: | |
202 | # this will sort by whitespace, and by line number, |
|
202 | # this will sort by whitespace, and by line number, | |
203 | # less whitespace first |
|
203 | # less whitespace first | |
204 | candidates.sort() |
|
204 | candidates.sort() | |
205 | return lines, candidates[0][1] |
|
205 | return lines, candidates[0][1] | |
206 | else: |
|
206 | else: | |
207 | raise IOError('could not find class definition') |
|
207 | raise IOError('could not find class definition') | |
208 |
|
208 | |||
209 | if ismethod(object): |
|
209 | if ismethod(object): | |
210 | object = object.__func__ |
|
210 | object = object.__func__ | |
211 | if isfunction(object): |
|
211 | if isfunction(object): | |
212 | object = object.__code__ |
|
212 | object = object.__code__ | |
213 | if istraceback(object): |
|
213 | if istraceback(object): | |
214 | object = object.tb_frame |
|
214 | object = object.tb_frame | |
215 | if isframe(object): |
|
215 | if isframe(object): | |
216 | object = object.f_code |
|
216 | object = object.f_code | |
217 | if iscode(object): |
|
217 | if iscode(object): | |
218 | if not hasattr(object, 'co_firstlineno'): |
|
218 | if not hasattr(object, 'co_firstlineno'): | |
219 | raise IOError('could not find function definition') |
|
219 | raise IOError('could not find function definition') | |
220 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
220 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') | |
221 | pmatch = pat.match |
|
221 | pmatch = pat.match | |
222 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
222 | # fperez - fix: sometimes, co_firstlineno can give a number larger than | |
223 | # the length of lines, which causes an error. Safeguard against that. |
|
223 | # the length of lines, which causes an error. Safeguard against that. | |
224 | lnum = min(object.co_firstlineno, len(lines)) - 1 |
|
224 | lnum = min(object.co_firstlineno, len(lines)) - 1 | |
225 | while lnum > 0: |
|
225 | while lnum > 0: | |
226 | if pmatch(lines[lnum]): |
|
226 | if pmatch(lines[lnum]): | |
227 | break |
|
227 | break | |
228 | lnum -= 1 |
|
228 | lnum -= 1 | |
229 |
|
229 | |||
230 | return lines, lnum |
|
230 | return lines, lnum | |
231 | raise IOError('could not find code object') |
|
231 | raise IOError('could not find code object') | |
232 |
|
232 | |||
233 |
|
233 | |||
234 | # This is a patched version of inspect.getargs that applies the (unmerged) |
|
234 | # This is a patched version of inspect.getargs that applies the (unmerged) | |
235 | # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes |
|
235 | # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes | |
236 | # https://github.com/ipython/ipython/issues/8205 and |
|
236 | # https://github.com/ipython/ipython/issues/8205 and | |
237 | # https://github.com/ipython/ipython/issues/8293 |
|
237 | # https://github.com/ipython/ipython/issues/8293 | |
238 | def getargs(co): |
|
238 | def getargs(co): | |
239 | """Get information about the arguments accepted by a code object. |
|
239 | """Get information about the arguments accepted by a code object. | |
240 |
|
240 | |||
241 | Three things are returned: (args, varargs, varkw), where 'args' is |
|
241 | Three things are returned: (args, varargs, varkw), where 'args' is | |
242 | a list of argument names (possibly containing nested lists), and |
|
242 | a list of argument names (possibly containing nested lists), and | |
243 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
|
243 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" | |
244 | if not iscode(co): |
|
244 | if not iscode(co): | |
245 | raise TypeError('{!r} is not a code object'.format(co)) |
|
245 | raise TypeError('{!r} is not a code object'.format(co)) | |
246 |
|
246 | |||
247 | nargs = co.co_argcount |
|
247 | nargs = co.co_argcount | |
248 | names = co.co_varnames |
|
248 | names = co.co_varnames | |
249 | args = list(names[:nargs]) |
|
249 | args = list(names[:nargs]) | |
250 | step = 0 |
|
250 | step = 0 | |
251 |
|
251 | |||
252 | # The following acrobatics are for anonymous (tuple) arguments. |
|
252 | # The following acrobatics are for anonymous (tuple) arguments. | |
253 | for i in range(nargs): |
|
253 | for i in range(nargs): | |
254 | if args[i][:1] in ('', '.'): |
|
254 | if args[i][:1] in ('', '.'): | |
255 | stack, remain, count = [], [], [] |
|
255 | stack, remain, count = [], [], [] | |
256 | while step < len(co.co_code): |
|
256 | while step < len(co.co_code): | |
257 | op = ord(co.co_code[step]) |
|
257 | op = ord(co.co_code[step]) | |
258 | step = step + 1 |
|
258 | step = step + 1 | |
259 | if op >= dis.HAVE_ARGUMENT: |
|
259 | if op >= dis.HAVE_ARGUMENT: | |
260 | opname = dis.opname[op] |
|
260 | opname = dis.opname[op] | |
261 | value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256 |
|
261 | value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256 | |
262 | step = step + 2 |
|
262 | step = step + 2 | |
263 | if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'): |
|
263 | if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'): | |
264 | remain.append(value) |
|
264 | remain.append(value) | |
265 | count.append(value) |
|
265 | count.append(value) | |
266 | elif opname in ('STORE_FAST', 'STORE_DEREF'): |
|
266 | elif opname in ('STORE_FAST', 'STORE_DEREF'): | |
267 | if op in dis.haslocal: |
|
267 | if op in dis.haslocal: | |
268 | stack.append(co.co_varnames[value]) |
|
268 | stack.append(co.co_varnames[value]) | |
269 | elif op in dis.hasfree: |
|
269 | elif op in dis.hasfree: | |
270 | stack.append((co.co_cellvars + co.co_freevars)[value]) |
|
270 | stack.append((co.co_cellvars + co.co_freevars)[value]) | |
271 | # Special case for sublists of length 1: def foo((bar)) |
|
271 | # Special case for sublists of length 1: def foo((bar)) | |
272 | # doesn't generate the UNPACK_TUPLE bytecode, so if |
|
272 | # doesn't generate the UNPACK_TUPLE bytecode, so if | |
273 | # `remain` is empty here, we have such a sublist. |
|
273 | # `remain` is empty here, we have such a sublist. | |
274 | if not remain: |
|
274 | if not remain: | |
275 | stack[0] = [stack[0]] |
|
275 | stack[0] = [stack[0]] | |
276 | break |
|
276 | break | |
277 | else: |
|
277 | else: | |
278 | remain[-1] = remain[-1] - 1 |
|
278 | remain[-1] = remain[-1] - 1 | |
279 | while remain[-1] == 0: |
|
279 | while remain[-1] == 0: | |
280 | remain.pop() |
|
280 | remain.pop() | |
281 | size = count.pop() |
|
281 | size = count.pop() | |
282 | stack[-size:] = [stack[-size:]] |
|
282 | stack[-size:] = [stack[-size:]] | |
283 | if not remain: |
|
283 | if not remain: | |
284 | break |
|
284 | break | |
285 | remain[-1] = remain[-1] - 1 |
|
285 | remain[-1] = remain[-1] - 1 | |
286 | if not remain: |
|
286 | if not remain: | |
287 | break |
|
287 | break | |
288 | args[i] = stack[0] |
|
288 | args[i] = stack[0] | |
289 |
|
289 | |||
290 | varargs = None |
|
290 | varargs = None | |
291 | if co.co_flags & inspect.CO_VARARGS: |
|
291 | if co.co_flags & inspect.CO_VARARGS: | |
292 | varargs = co.co_varnames[nargs] |
|
292 | varargs = co.co_varnames[nargs] | |
293 | nargs = nargs + 1 |
|
293 | nargs = nargs + 1 | |
294 | varkw = None |
|
294 | varkw = None | |
295 | if co.co_flags & inspect.CO_VARKEYWORDS: |
|
295 | if co.co_flags & inspect.CO_VARKEYWORDS: | |
296 | varkw = co.co_varnames[nargs] |
|
296 | varkw = co.co_varnames[nargs] | |
297 | return inspect.Arguments(args, varargs, varkw) |
|
297 | return inspect.Arguments(args, varargs, varkw) | |
298 |
|
298 | |||
299 |
|
299 | |||
300 | # Monkeypatch inspect to apply our bugfix. |
|
300 | # Monkeypatch inspect to apply our bugfix. | |
301 | def with_patch_inspect(f): |
|
301 | def with_patch_inspect(f): | |
302 | """decorator for monkeypatching inspect.findsource""" |
|
302 | """decorator for monkeypatching inspect.findsource""" | |
303 |
|
303 | |||
304 | def wrapped(*args, **kwargs): |
|
304 | def wrapped(*args, **kwargs): | |
305 | save_findsource = inspect.findsource |
|
305 | save_findsource = inspect.findsource | |
306 | save_getargs = inspect.getargs |
|
306 | save_getargs = inspect.getargs | |
307 | inspect.findsource = findsource |
|
307 | inspect.findsource = findsource | |
308 | inspect.getargs = getargs |
|
308 | inspect.getargs = getargs | |
309 | try: |
|
309 | try: | |
310 | return f(*args, **kwargs) |
|
310 | return f(*args, **kwargs) | |
311 | finally: |
|
311 | finally: | |
312 | inspect.findsource = save_findsource |
|
312 | inspect.findsource = save_findsource | |
313 | inspect.getargs = save_getargs |
|
313 | inspect.getargs = save_getargs | |
314 |
|
314 | |||
315 | return wrapped |
|
315 | return wrapped | |
316 |
|
316 | |||
317 |
|
317 | |||
318 | if py3compat.PY3: |
|
318 | if py3compat.PY3: | |
319 | fixed_getargvalues = inspect.getargvalues |
|
319 | fixed_getargvalues = inspect.getargvalues | |
320 | else: |
|
320 | else: | |
321 | # Fixes for https://github.com/ipython/ipython/issues/8293 |
|
321 | # Fixes for https://github.com/ipython/ipython/issues/8293 | |
322 | # and https://github.com/ipython/ipython/issues/8205. |
|
322 | # and https://github.com/ipython/ipython/issues/8205. | |
323 | # The relevant bug is caused by failure to correctly handle anonymous tuple |
|
323 | # The relevant bug is caused by failure to correctly handle anonymous tuple | |
324 | # unpacking, which only exists in Python 2. |
|
324 | # unpacking, which only exists in Python 2. | |
325 | fixed_getargvalues = with_patch_inspect(inspect.getargvalues) |
|
325 | fixed_getargvalues = with_patch_inspect(inspect.getargvalues) | |
326 |
|
326 | |||
327 |
|
327 | |||
328 | def fix_frame_records_filenames(records): |
|
328 | def fix_frame_records_filenames(records): | |
329 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
329 | """Try to fix the filenames in each record from inspect.getinnerframes(). | |
330 |
|
330 | |||
331 | Particularly, modules loaded from within zip files have useless filenames |
|
331 | Particularly, modules loaded from within zip files have useless filenames | |
332 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
332 | attached to their code object, and inspect.getinnerframes() just uses it. | |
333 | """ |
|
333 | """ | |
334 | fixed_records = [] |
|
334 | fixed_records = [] | |
335 | for frame, filename, line_no, func_name, lines, index in records: |
|
335 | for frame, filename, line_no, func_name, lines, index in records: | |
336 | # Look inside the frame's globals dictionary for __file__, |
|
336 | # Look inside the frame's globals dictionary for __file__, | |
337 | # which should be better. However, keep Cython filenames since |
|
337 | # which should be better. However, keep Cython filenames since | |
338 | # we prefer the source filenames over the compiled .so file. |
|
338 | # we prefer the source filenames over the compiled .so file. | |
339 | filename = py3compat.cast_unicode_py2(filename, "utf-8") |
|
339 | filename = py3compat.cast_unicode_py2(filename, "utf-8") | |
340 | if not filename.endswith(('.pyx', '.pxd', '.pxi')): |
|
340 | if not filename.endswith(('.pyx', '.pxd', '.pxi')): | |
341 | better_fn = frame.f_globals.get('__file__', None) |
|
341 | better_fn = frame.f_globals.get('__file__', None) | |
342 | if isinstance(better_fn, str): |
|
342 | if isinstance(better_fn, str): | |
343 | # Check the type just in case someone did something weird with |
|
343 | # Check the type just in case someone did something weird with | |
344 | # __file__. It might also be None if the error occurred during |
|
344 | # __file__. It might also be None if the error occurred during | |
345 | # import. |
|
345 | # import. | |
346 | filename = better_fn |
|
346 | filename = better_fn | |
347 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
347 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) | |
348 | return fixed_records |
|
348 | return fixed_records | |
349 |
|
349 | |||
350 |
|
350 | |||
351 | @with_patch_inspect |
|
351 | @with_patch_inspect | |
352 | def _fixed_getinnerframes(etb, context=1, tb_offset=0): |
|
352 | def _fixed_getinnerframes(etb, context=1, tb_offset=0): | |
353 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
353 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 | |
354 |
|
354 | |||
355 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
355 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) | |
356 | # If the error is at the console, don't build any context, since it would |
|
356 | # If the error is at the console, don't build any context, since it would | |
357 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
357 | # otherwise produce 5 blank lines printed out (there is no file at the | |
358 | # console) |
|
358 | # console) | |
359 | rec_check = records[tb_offset:] |
|
359 | rec_check = records[tb_offset:] | |
360 | try: |
|
360 | try: | |
361 | rname = rec_check[0][1] |
|
361 | rname = rec_check[0][1] | |
362 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
362 | if rname == '<ipython console>' or rname.endswith('<string>'): | |
363 | return rec_check |
|
363 | return rec_check | |
364 | except IndexError: |
|
364 | except IndexError: | |
365 | pass |
|
365 | pass | |
366 |
|
366 | |||
367 | aux = traceback.extract_tb(etb) |
|
367 | aux = traceback.extract_tb(etb) | |
368 | assert len(records) == len(aux) |
|
368 | assert len(records) == len(aux) | |
369 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
369 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): | |
370 | maybeStart = lnum - 1 - context // 2 |
|
370 | maybeStart = lnum - 1 - context // 2 | |
371 | start = max(maybeStart, 0) |
|
371 | start = max(maybeStart, 0) | |
372 | end = start + context |
|
372 | end = start + context | |
373 | lines = ulinecache.getlines(file)[start:end] |
|
373 | lines = ulinecache.getlines(file)[start:end] | |
374 | buf = list(records[i]) |
|
374 | buf = list(records[i]) | |
375 | buf[LNUM_POS] = lnum |
|
375 | buf[LNUM_POS] = lnum | |
376 | buf[INDEX_POS] = lnum - 1 - start |
|
376 | buf[INDEX_POS] = lnum - 1 - start | |
377 | buf[LINES_POS] = lines |
|
377 | buf[LINES_POS] = lines | |
378 | records[i] = tuple(buf) |
|
378 | records[i] = tuple(buf) | |
379 | return records[tb_offset:] |
|
379 | return records[tb_offset:] | |
380 |
|
380 | |||
381 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
381 | # Helper function -- largely belongs to VerboseTB, but we need the same | |
382 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
382 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they | |
383 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
383 | # can be recognized properly by ipython.el's py-traceback-line-re | |
384 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
384 | # (SyntaxErrors have to be treated specially because they have no traceback) | |
385 |
|
385 | |||
386 |
|
386 | |||
387 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, _line_format=(lambda x,_:x,None)): |
|
387 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, _line_format=(lambda x,_:x,None)): | |
388 | numbers_width = INDENT_SIZE - 1 |
|
388 | numbers_width = INDENT_SIZE - 1 | |
389 | res = [] |
|
389 | res = [] | |
390 | i = lnum - index |
|
390 | i = lnum - index | |
391 |
|
391 | |||
392 | for line in lines: |
|
392 | for line in lines: | |
393 | line = py3compat.cast_unicode(line) |
|
393 | line = py3compat.cast_unicode(line) | |
394 |
|
394 | |||
395 | new_line, err = _line_format(line, 'str') |
|
395 | new_line, err = _line_format(line, 'str') | |
396 | if not err: line = new_line |
|
396 | if not err: line = new_line | |
397 |
|
397 | |||
398 | if i == lnum: |
|
398 | if i == lnum: | |
399 | # This is the line with the error |
|
399 | # This is the line with the error | |
400 | pad = numbers_width - len(str(i)) |
|
400 | pad = numbers_width - len(str(i)) | |
401 | num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) |
|
401 | num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) | |
402 | line = '%s%s%s %s%s' % (Colors.linenoEm, num, |
|
402 | line = '%s%s%s %s%s' % (Colors.linenoEm, num, | |
403 | Colors.line, line, Colors.Normal) |
|
403 | Colors.line, line, Colors.Normal) | |
404 | else: |
|
404 | else: | |
405 | num = '%*s' % (numbers_width, i) |
|
405 | num = '%*s' % (numbers_width, i) | |
406 | line = '%s%s%s %s' % (Colors.lineno, num, |
|
406 | line = '%s%s%s %s' % (Colors.lineno, num, | |
407 | Colors.Normal, line) |
|
407 | Colors.Normal, line) | |
408 |
|
408 | |||
409 | res.append(line) |
|
409 | res.append(line) | |
410 | if lvals and i == lnum: |
|
410 | if lvals and i == lnum: | |
411 | res.append(lvals + '\n') |
|
411 | res.append(lvals + '\n') | |
412 | i = i + 1 |
|
412 | i = i + 1 | |
413 | return res |
|
413 | return res | |
414 |
|
414 | |||
415 | def is_recursion_error(etype, value, records): |
|
415 | def is_recursion_error(etype, value, records): | |
416 | try: |
|
416 | try: | |
417 | # RecursionError is new in Python 3.5 |
|
417 | # RecursionError is new in Python 3.5 | |
418 | recursion_error_type = RecursionError |
|
418 | recursion_error_type = RecursionError | |
419 | except NameError: |
|
419 | except NameError: | |
420 | recursion_error_type = RuntimeError |
|
420 | recursion_error_type = RuntimeError | |
421 |
|
421 | |||
422 | # The default recursion limit is 1000, but some of that will be taken up |
|
422 | # The default recursion limit is 1000, but some of that will be taken up | |
423 | # by stack frames in IPython itself. >500 frames probably indicates |
|
423 | # by stack frames in IPython itself. >500 frames probably indicates | |
424 | # a recursion error. |
|
424 | # a recursion error. | |
425 | return (etype is recursion_error_type) \ |
|
425 | return (etype is recursion_error_type) \ | |
426 | and "recursion" in str(value).lower() \ |
|
426 | and "recursion" in str(value).lower() \ | |
427 | and len(records) > 500 |
|
427 | and len(records) > 500 | |
428 |
|
428 | |||
429 | def find_recursion(etype, value, records): |
|
429 | def find_recursion(etype, value, records): | |
430 | """Identify the repeating stack frames from a RecursionError traceback |
|
430 | """Identify the repeating stack frames from a RecursionError traceback | |
431 |
|
431 | |||
432 | 'records' is a list as returned by VerboseTB.get_records() |
|
432 | 'records' is a list as returned by VerboseTB.get_records() | |
433 |
|
433 | |||
434 | Returns (last_unique, repeat_length) |
|
434 | Returns (last_unique, repeat_length) | |
435 | """ |
|
435 | """ | |
436 | # This involves a bit of guesswork - we want to show enough of the traceback |
|
436 | # This involves a bit of guesswork - we want to show enough of the traceback | |
437 | # to indicate where the recursion is occurring. We guess that the innermost |
|
437 | # to indicate where the recursion is occurring. We guess that the innermost | |
438 | # quarter of the traceback (250 frames by default) is repeats, and find the |
|
438 | # quarter of the traceback (250 frames by default) is repeats, and find the | |
439 | # first frame (from in to out) that looks different. |
|
439 | # first frame (from in to out) that looks different. | |
440 | if not is_recursion_error(etype, value, records): |
|
440 | if not is_recursion_error(etype, value, records): | |
441 | return len(records), 0 |
|
441 | return len(records), 0 | |
442 |
|
442 | |||
443 | # Select filename, lineno, func_name to track frames with |
|
443 | # Select filename, lineno, func_name to track frames with | |
444 | records = [r[1:4] for r in records] |
|
444 | records = [r[1:4] for r in records] | |
445 | inner_frames = records[-(len(records)//4):] |
|
445 | inner_frames = records[-(len(records)//4):] | |
446 | frames_repeated = set(inner_frames) |
|
446 | frames_repeated = set(inner_frames) | |
447 |
|
447 | |||
448 | last_seen_at = {} |
|
448 | last_seen_at = {} | |
449 | longest_repeat = 0 |
|
449 | longest_repeat = 0 | |
450 | i = len(records) |
|
450 | i = len(records) | |
451 | for frame in reversed(records): |
|
451 | for frame in reversed(records): | |
452 | i -= 1 |
|
452 | i -= 1 | |
453 | if frame not in frames_repeated: |
|
453 | if frame not in frames_repeated: | |
454 | last_unique = i |
|
454 | last_unique = i | |
455 | break |
|
455 | break | |
456 |
|
456 | |||
457 | if frame in last_seen_at: |
|
457 | if frame in last_seen_at: | |
458 | distance = last_seen_at[frame] - i |
|
458 | distance = last_seen_at[frame] - i | |
459 | longest_repeat = max(longest_repeat, distance) |
|
459 | longest_repeat = max(longest_repeat, distance) | |
460 |
|
460 | |||
461 | last_seen_at[frame] = i |
|
461 | last_seen_at[frame] = i | |
462 | else: |
|
462 | else: | |
463 | last_unique = 0 # The whole traceback was recursion |
|
463 | last_unique = 0 # The whole traceback was recursion | |
464 |
|
464 | |||
465 | return last_unique, longest_repeat |
|
465 | return last_unique, longest_repeat | |
466 |
|
466 | |||
467 | #--------------------------------------------------------------------------- |
|
467 | #--------------------------------------------------------------------------- | |
468 | # Module classes |
|
468 | # Module classes | |
469 | class TBTools(colorable.Colorable): |
|
469 | class TBTools(colorable.Colorable): | |
470 | """Basic tools used by all traceback printer classes.""" |
|
470 | """Basic tools used by all traceback printer classes.""" | |
471 |
|
471 | |||
472 | # Number of frames to skip when reporting tracebacks |
|
472 | # Number of frames to skip when reporting tracebacks | |
473 | tb_offset = 0 |
|
473 | tb_offset = 0 | |
474 |
|
474 | |||
475 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
475 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): | |
476 | # Whether to call the interactive pdb debugger after printing |
|
476 | # Whether to call the interactive pdb debugger after printing | |
477 | # tracebacks or not |
|
477 | # tracebacks or not | |
478 | super(TBTools, self).__init__(parent=parent, config=config) |
|
478 | super(TBTools, self).__init__(parent=parent, config=config) | |
479 | self.call_pdb = call_pdb |
|
479 | self.call_pdb = call_pdb | |
480 |
|
480 | |||
481 | # Output stream to write to. Note that we store the original value in |
|
481 | # Output stream to write to. Note that we store the original value in | |
482 | # a private attribute and then make the public ostream a property, so |
|
482 | # a private attribute and then make the public ostream a property, so | |
483 | # that we can delay accessing sys.stdout until runtime. The way |
|
483 | # that we can delay accessing sys.stdout until runtime. The way | |
484 | # things are written now, the sys.stdout object is dynamically managed |
|
484 | # things are written now, the sys.stdout object is dynamically managed | |
485 | # so a reference to it should NEVER be stored statically. This |
|
485 | # so a reference to it should NEVER be stored statically. This | |
486 | # property approach confines this detail to a single location, and all |
|
486 | # property approach confines this detail to a single location, and all | |
487 | # subclasses can simply access self.ostream for writing. |
|
487 | # subclasses can simply access self.ostream for writing. | |
488 | self._ostream = ostream |
|
488 | self._ostream = ostream | |
489 |
|
489 | |||
490 | # Create color table |
|
490 | # Create color table | |
491 | self.color_scheme_table = exception_colors() |
|
491 | self.color_scheme_table = exception_colors() | |
492 |
|
492 | |||
493 | self.set_colors(color_scheme) |
|
493 | self.set_colors(color_scheme) | |
494 | self.old_scheme = color_scheme # save initial value for toggles |
|
494 | self.old_scheme = color_scheme # save initial value for toggles | |
495 |
|
495 | |||
496 | if call_pdb: |
|
496 | if call_pdb: | |
497 | self.pdb = debugger.Pdb() |
|
497 | self.pdb = debugger.Pdb() | |
498 | else: |
|
498 | else: | |
499 | self.pdb = None |
|
499 | self.pdb = None | |
500 |
|
500 | |||
501 | def _get_ostream(self): |
|
501 | def _get_ostream(self): | |
502 | """Output stream that exceptions are written to. |
|
502 | """Output stream that exceptions are written to. | |
503 |
|
503 | |||
504 | Valid values are: |
|
504 | Valid values are: | |
505 |
|
505 | |||
506 | - None: the default, which means that IPython will dynamically resolve |
|
506 | - None: the default, which means that IPython will dynamically resolve | |
507 | to sys.stdout. This ensures compatibility with most tools, including |
|
507 | to sys.stdout. This ensures compatibility with most tools, including | |
508 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
508 | Windows (where plain stdout doesn't recognize ANSI escapes). | |
509 |
|
509 | |||
510 | - Any object with 'write' and 'flush' attributes. |
|
510 | - Any object with 'write' and 'flush' attributes. | |
511 | """ |
|
511 | """ | |
512 | return sys.stdout if self._ostream is None else self._ostream |
|
512 | return sys.stdout if self._ostream is None else self._ostream | |
513 |
|
513 | |||
514 | def _set_ostream(self, val): |
|
514 | def _set_ostream(self, val): | |
515 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
515 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) | |
516 | self._ostream = val |
|
516 | self._ostream = val | |
517 |
|
517 | |||
518 | ostream = property(_get_ostream, _set_ostream) |
|
518 | ostream = property(_get_ostream, _set_ostream) | |
519 |
|
519 | |||
520 | def set_colors(self, *args, **kw): |
|
520 | def set_colors(self, *args, **kw): | |
521 | """Shorthand access to the color table scheme selector method.""" |
|
521 | """Shorthand access to the color table scheme selector method.""" | |
522 |
|
522 | |||
523 | # Set own color table |
|
523 | # Set own color table | |
524 | self.color_scheme_table.set_active_scheme(*args, **kw) |
|
524 | self.color_scheme_table.set_active_scheme(*args, **kw) | |
525 | # for convenience, set Colors to the active scheme |
|
525 | # for convenience, set Colors to the active scheme | |
526 | self.Colors = self.color_scheme_table.active_colors |
|
526 | self.Colors = self.color_scheme_table.active_colors | |
527 | # Also set colors of debugger |
|
527 | # Also set colors of debugger | |
528 | if hasattr(self, 'pdb') and self.pdb is not None: |
|
528 | if hasattr(self, 'pdb') and self.pdb is not None: | |
529 | self.pdb.set_colors(*args, **kw) |
|
529 | self.pdb.set_colors(*args, **kw) | |
530 |
|
530 | |||
531 | def color_toggle(self): |
|
531 | def color_toggle(self): | |
532 | """Toggle between the currently active color scheme and NoColor.""" |
|
532 | """Toggle between the currently active color scheme and NoColor.""" | |
533 |
|
533 | |||
534 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
534 | if self.color_scheme_table.active_scheme_name == 'NoColor': | |
535 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
535 | self.color_scheme_table.set_active_scheme(self.old_scheme) | |
536 | self.Colors = self.color_scheme_table.active_colors |
|
536 | self.Colors = self.color_scheme_table.active_colors | |
537 | else: |
|
537 | else: | |
538 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
538 | self.old_scheme = self.color_scheme_table.active_scheme_name | |
539 | self.color_scheme_table.set_active_scheme('NoColor') |
|
539 | self.color_scheme_table.set_active_scheme('NoColor') | |
540 | self.Colors = self.color_scheme_table.active_colors |
|
540 | self.Colors = self.color_scheme_table.active_colors | |
541 |
|
541 | |||
542 | def stb2text(self, stb): |
|
542 | def stb2text(self, stb): | |
543 | """Convert a structured traceback (a list) to a string.""" |
|
543 | """Convert a structured traceback (a list) to a string.""" | |
544 | return '\n'.join(stb) |
|
544 | return '\n'.join(stb) | |
545 |
|
545 | |||
546 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
546 | def text(self, etype, value, tb, tb_offset=None, context=5): | |
547 | """Return formatted traceback. |
|
547 | """Return formatted traceback. | |
548 |
|
548 | |||
549 | Subclasses may override this if they add extra arguments. |
|
549 | Subclasses may override this if they add extra arguments. | |
550 | """ |
|
550 | """ | |
551 | tb_list = self.structured_traceback(etype, value, tb, |
|
551 | tb_list = self.structured_traceback(etype, value, tb, | |
552 | tb_offset, context) |
|
552 | tb_offset, context) | |
553 | return self.stb2text(tb_list) |
|
553 | return self.stb2text(tb_list) | |
554 |
|
554 | |||
555 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
555 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, | |
556 | context=5, mode=None): |
|
556 | context=5, mode=None): | |
557 | """Return a list of traceback frames. |
|
557 | """Return a list of traceback frames. | |
558 |
|
558 | |||
559 | Must be implemented by each class. |
|
559 | Must be implemented by each class. | |
560 | """ |
|
560 | """ | |
561 | raise NotImplementedError() |
|
561 | raise NotImplementedError() | |
562 |
|
562 | |||
563 |
|
563 | |||
564 | #--------------------------------------------------------------------------- |
|
564 | #--------------------------------------------------------------------------- | |
565 | class ListTB(TBTools): |
|
565 | class ListTB(TBTools): | |
566 | """Print traceback information from a traceback list, with optional color. |
|
566 | """Print traceback information from a traceback list, with optional color. | |
567 |
|
567 | |||
568 | Calling requires 3 arguments: (etype, evalue, elist) |
|
568 | Calling requires 3 arguments: (etype, evalue, elist) | |
569 | as would be obtained by:: |
|
569 | as would be obtained by:: | |
570 |
|
570 | |||
571 | etype, evalue, tb = sys.exc_info() |
|
571 | etype, evalue, tb = sys.exc_info() | |
572 | if tb: |
|
572 | if tb: | |
573 | elist = traceback.extract_tb(tb) |
|
573 | elist = traceback.extract_tb(tb) | |
574 | else: |
|
574 | else: | |
575 | elist = None |
|
575 | elist = None | |
576 |
|
576 | |||
577 | It can thus be used by programs which need to process the traceback before |
|
577 | It can thus be used by programs which need to process the traceback before | |
578 | printing (such as console replacements based on the code module from the |
|
578 | printing (such as console replacements based on the code module from the | |
579 | standard library). |
|
579 | standard library). | |
580 |
|
580 | |||
581 | Because they are meant to be called without a full traceback (only a |
|
581 | Because they are meant to be called without a full traceback (only a | |
582 | list), instances of this class can't call the interactive pdb debugger.""" |
|
582 | list), instances of this class can't call the interactive pdb debugger.""" | |
583 |
|
583 | |||
584 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
584 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): | |
585 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
585 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
586 | ostream=ostream, parent=parent,config=config) |
|
586 | ostream=ostream, parent=parent,config=config) | |
587 |
|
587 | |||
588 | def __call__(self, etype, value, elist): |
|
588 | def __call__(self, etype, value, elist): | |
589 | self.ostream.flush() |
|
589 | self.ostream.flush() | |
590 | self.ostream.write(self.text(etype, value, elist)) |
|
590 | self.ostream.write(self.text(etype, value, elist)) | |
591 | self.ostream.write('\n') |
|
591 | self.ostream.write('\n') | |
592 |
|
592 | |||
593 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
593 | def structured_traceback(self, etype, value, elist, tb_offset=None, | |
594 | context=5): |
|
594 | context=5): | |
595 | """Return a color formatted string with the traceback info. |
|
595 | """Return a color formatted string with the traceback info. | |
596 |
|
596 | |||
597 | Parameters |
|
597 | Parameters | |
598 | ---------- |
|
598 | ---------- | |
599 | etype : exception type |
|
599 | etype : exception type | |
600 | Type of the exception raised. |
|
600 | Type of the exception raised. | |
601 |
|
601 | |||
602 | value : object |
|
602 | value : object | |
603 | Data stored in the exception |
|
603 | Data stored in the exception | |
604 |
|
604 | |||
605 | elist : list |
|
605 | elist : list | |
606 | List of frames, see class docstring for details. |
|
606 | List of frames, see class docstring for details. | |
607 |
|
607 | |||
608 | tb_offset : int, optional |
|
608 | tb_offset : int, optional | |
609 | Number of frames in the traceback to skip. If not given, the |
|
609 | Number of frames in the traceback to skip. If not given, the | |
610 | instance value is used (set in constructor). |
|
610 | instance value is used (set in constructor). | |
611 |
|
611 | |||
612 | context : int, optional |
|
612 | context : int, optional | |
613 | Number of lines of context information to print. |
|
613 | Number of lines of context information to print. | |
614 |
|
614 | |||
615 | Returns |
|
615 | Returns | |
616 | ------- |
|
616 | ------- | |
617 | String with formatted exception. |
|
617 | String with formatted exception. | |
618 | """ |
|
618 | """ | |
619 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
619 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
620 | Colors = self.Colors |
|
620 | Colors = self.Colors | |
621 | out_list = [] |
|
621 | out_list = [] | |
622 | if elist: |
|
622 | if elist: | |
623 |
|
623 | |||
624 | if tb_offset and len(elist) > tb_offset: |
|
624 | if tb_offset and len(elist) > tb_offset: | |
625 | elist = elist[tb_offset:] |
|
625 | elist = elist[tb_offset:] | |
626 |
|
626 | |||
627 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
627 | out_list.append('Traceback %s(most recent call last)%s:' % | |
628 | (Colors.normalEm, Colors.Normal) + '\n') |
|
628 | (Colors.normalEm, Colors.Normal) + '\n') | |
629 | out_list.extend(self._format_list(elist)) |
|
629 | out_list.extend(self._format_list(elist)) | |
630 | # The exception info should be a single entry in the list. |
|
630 | # The exception info should be a single entry in the list. | |
631 | lines = ''.join(self._format_exception_only(etype, value)) |
|
631 | lines = ''.join(self._format_exception_only(etype, value)) | |
632 | out_list.append(lines) |
|
632 | out_list.append(lines) | |
633 |
|
633 | |||
634 | # Note: this code originally read: |
|
634 | # Note: this code originally read: | |
635 |
|
635 | |||
636 | ## for line in lines[:-1]: |
|
636 | ## for line in lines[:-1]: | |
637 | ## out_list.append(" "+line) |
|
637 | ## out_list.append(" "+line) | |
638 | ## out_list.append(lines[-1]) |
|
638 | ## out_list.append(lines[-1]) | |
639 |
|
639 | |||
640 | # This means it was indenting everything but the last line by a little |
|
640 | # This means it was indenting everything but the last line by a little | |
641 | # bit. I've disabled this for now, but if we see ugliness somewhere we |
|
641 | # bit. I've disabled this for now, but if we see ugliness somewhere we | |
642 | # can restore it. |
|
642 | # can restore it. | |
643 |
|
643 | |||
644 | return out_list |
|
644 | return out_list | |
645 |
|
645 | |||
646 | def _format_list(self, extracted_list): |
|
646 | def _format_list(self, extracted_list): | |
647 | """Format a list of traceback entry tuples for printing. |
|
647 | """Format a list of traceback entry tuples for printing. | |
648 |
|
648 | |||
649 | Given a list of tuples as returned by extract_tb() or |
|
649 | Given a list of tuples as returned by extract_tb() or | |
650 | extract_stack(), return a list of strings ready for printing. |
|
650 | extract_stack(), return a list of strings ready for printing. | |
651 | Each string in the resulting list corresponds to the item with the |
|
651 | Each string in the resulting list corresponds to the item with the | |
652 | same index in the argument list. Each string ends in a newline; |
|
652 | same index in the argument list. Each string ends in a newline; | |
653 | the strings may contain internal newlines as well, for those items |
|
653 | the strings may contain internal newlines as well, for those items | |
654 | whose source text line is not None. |
|
654 | whose source text line is not None. | |
655 |
|
655 | |||
656 | Lifted almost verbatim from traceback.py |
|
656 | Lifted almost verbatim from traceback.py | |
657 | """ |
|
657 | """ | |
658 |
|
658 | |||
659 | Colors = self.Colors |
|
659 | Colors = self.Colors | |
660 | list = [] |
|
660 | list = [] | |
661 | for filename, lineno, name, line in extracted_list[:-1]: |
|
661 | for filename, lineno, name, line in extracted_list[:-1]: | |
662 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
662 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ | |
663 | (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal, |
|
663 | (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal, | |
664 | Colors.lineno, lineno, Colors.Normal, |
|
664 | Colors.lineno, lineno, Colors.Normal, | |
665 | Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal) |
|
665 | Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal) | |
666 | if line: |
|
666 | if line: | |
667 | item += ' %s\n' % line.strip() |
|
667 | item += ' %s\n' % line.strip() | |
668 | list.append(item) |
|
668 | list.append(item) | |
669 | # Emphasize the last entry |
|
669 | # Emphasize the last entry | |
670 | filename, lineno, name, line = extracted_list[-1] |
|
670 | filename, lineno, name, line = extracted_list[-1] | |
671 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
671 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ | |
672 | (Colors.normalEm, |
|
672 | (Colors.normalEm, | |
673 | Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm, |
|
673 | Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm, | |
674 | Colors.linenoEm, lineno, Colors.normalEm, |
|
674 | Colors.linenoEm, lineno, Colors.normalEm, | |
675 | Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm, |
|
675 | Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm, | |
676 | Colors.Normal) |
|
676 | Colors.Normal) | |
677 | if line: |
|
677 | if line: | |
678 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
678 | item += '%s %s%s\n' % (Colors.line, line.strip(), | |
679 | Colors.Normal) |
|
679 | Colors.Normal) | |
680 | list.append(item) |
|
680 | list.append(item) | |
681 | return list |
|
681 | return list | |
682 |
|
682 | |||
683 | def _format_exception_only(self, etype, value): |
|
683 | def _format_exception_only(self, etype, value): | |
684 | """Format the exception part of a traceback. |
|
684 | """Format the exception part of a traceback. | |
685 |
|
685 | |||
686 | The arguments are the exception type and value such as given by |
|
686 | The arguments are the exception type and value such as given by | |
687 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
687 | sys.exc_info()[:2]. The return value is a list of strings, each ending | |
688 | in a newline. Normally, the list contains a single string; however, |
|
688 | in a newline. Normally, the list contains a single string; however, | |
689 | for SyntaxError exceptions, it contains several lines that (when |
|
689 | for SyntaxError exceptions, it contains several lines that (when | |
690 | printed) display detailed information about where the syntax error |
|
690 | printed) display detailed information about where the syntax error | |
691 | occurred. The message indicating which exception occurred is the |
|
691 | occurred. The message indicating which exception occurred is the | |
692 | always last string in the list. |
|
692 | always last string in the list. | |
693 |
|
693 | |||
694 | Also lifted nearly verbatim from traceback.py |
|
694 | Also lifted nearly verbatim from traceback.py | |
695 | """ |
|
695 | """ | |
696 | have_filedata = False |
|
696 | have_filedata = False | |
697 | Colors = self.Colors |
|
697 | Colors = self.Colors | |
698 | list = [] |
|
698 | list = [] | |
699 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) |
|
699 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) | |
700 | if value is None: |
|
700 | if value is None: | |
701 | # Not sure if this can still happen in Python 2.6 and above |
|
701 | # Not sure if this can still happen in Python 2.6 and above | |
702 | list.append(stype + '\n') |
|
702 | list.append(stype + '\n') | |
703 | else: |
|
703 | else: | |
704 | if issubclass(etype, SyntaxError): |
|
704 | if issubclass(etype, SyntaxError): | |
705 | have_filedata = True |
|
705 | have_filedata = True | |
706 | if not value.filename: value.filename = "<string>" |
|
706 | if not value.filename: value.filename = "<string>" | |
707 | if value.lineno: |
|
707 | if value.lineno: | |
708 | lineno = value.lineno |
|
708 | lineno = value.lineno | |
709 | textline = ulinecache.getline(value.filename, value.lineno) |
|
709 | textline = ulinecache.getline(value.filename, value.lineno) | |
710 | else: |
|
710 | else: | |
711 | lineno = 'unknown' |
|
711 | lineno = 'unknown' | |
712 | textline = '' |
|
712 | textline = '' | |
713 | list.append('%s File %s"%s"%s, line %s%s%s\n' % \ |
|
713 | list.append('%s File %s"%s"%s, line %s%s%s\n' % \ | |
714 | (Colors.normalEm, |
|
714 | (Colors.normalEm, | |
715 | Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm, |
|
715 | Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm, | |
716 | Colors.linenoEm, lineno, Colors.Normal )) |
|
716 | Colors.linenoEm, lineno, Colors.Normal )) | |
717 | if textline == '': |
|
717 | if textline == '': | |
718 | textline = py3compat.cast_unicode(value.text, "utf-8") |
|
718 | textline = py3compat.cast_unicode(value.text, "utf-8") | |
719 |
|
719 | |||
720 | if textline is not None: |
|
720 | if textline is not None: | |
721 | i = 0 |
|
721 | i = 0 | |
722 | while i < len(textline) and textline[i].isspace(): |
|
722 | while i < len(textline) and textline[i].isspace(): | |
723 | i += 1 |
|
723 | i += 1 | |
724 | list.append('%s %s%s\n' % (Colors.line, |
|
724 | list.append('%s %s%s\n' % (Colors.line, | |
725 | textline.strip(), |
|
725 | textline.strip(), | |
726 | Colors.Normal)) |
|
726 | Colors.Normal)) | |
727 | if value.offset is not None: |
|
727 | if value.offset is not None: | |
728 | s = ' ' |
|
728 | s = ' ' | |
729 | for c in textline[i:value.offset - 1]: |
|
729 | for c in textline[i:value.offset - 1]: | |
730 | if c.isspace(): |
|
730 | if c.isspace(): | |
731 | s += c |
|
731 | s += c | |
732 | else: |
|
732 | else: | |
733 | s += ' ' |
|
733 | s += ' ' | |
734 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
734 | list.append('%s%s^%s\n' % (Colors.caret, s, | |
735 | Colors.Normal)) |
|
735 | Colors.Normal)) | |
736 |
|
736 | |||
737 | try: |
|
737 | try: | |
738 | s = value.msg |
|
738 | s = value.msg | |
739 | except Exception: |
|
739 | except Exception: | |
740 | s = self._some_str(value) |
|
740 | s = self._some_str(value) | |
741 | if s: |
|
741 | if s: | |
742 | list.append('%s%s:%s %s\n' % (stype, Colors.excName, |
|
742 | list.append('%s%s:%s %s\n' % (stype, Colors.excName, | |
743 | Colors.Normal, s)) |
|
743 | Colors.Normal, s)) | |
744 | else: |
|
744 | else: | |
745 | list.append('%s\n' % stype) |
|
745 | list.append('%s\n' % stype) | |
746 |
|
746 | |||
747 | # sync with user hooks |
|
747 | # sync with user hooks | |
748 | if have_filedata: |
|
748 | if have_filedata: | |
749 | ipinst = get_ipython() |
|
749 | ipinst = get_ipython() | |
750 | if ipinst is not None: |
|
750 | if ipinst is not None: | |
751 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
751 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) | |
752 |
|
752 | |||
753 | return list |
|
753 | return list | |
754 |
|
754 | |||
755 | def get_exception_only(self, etype, value): |
|
755 | def get_exception_only(self, etype, value): | |
756 | """Only print the exception type and message, without a traceback. |
|
756 | """Only print the exception type and message, without a traceback. | |
757 |
|
757 | |||
758 | Parameters |
|
758 | Parameters | |
759 | ---------- |
|
759 | ---------- | |
760 | etype : exception type |
|
760 | etype : exception type | |
761 | value : exception value |
|
761 | value : exception value | |
762 | """ |
|
762 | """ | |
763 | return ListTB.structured_traceback(self, etype, value, []) |
|
763 | return ListTB.structured_traceback(self, etype, value, []) | |
764 |
|
764 | |||
765 | def show_exception_only(self, etype, evalue): |
|
765 | def show_exception_only(self, etype, evalue): | |
766 | """Only print the exception type and message, without a traceback. |
|
766 | """Only print the exception type and message, without a traceback. | |
767 |
|
767 | |||
768 | Parameters |
|
768 | Parameters | |
769 | ---------- |
|
769 | ---------- | |
770 | etype : exception type |
|
770 | etype : exception type | |
771 | value : exception value |
|
771 | value : exception value | |
772 | """ |
|
772 | """ | |
773 | # This method needs to use __call__ from *this* class, not the one from |
|
773 | # This method needs to use __call__ from *this* class, not the one from | |
774 | # a subclass whose signature or behavior may be different |
|
774 | # a subclass whose signature or behavior may be different | |
775 | ostream = self.ostream |
|
775 | ostream = self.ostream | |
776 | ostream.flush() |
|
776 | ostream.flush() | |
777 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
777 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) | |
778 | ostream.flush() |
|
778 | ostream.flush() | |
779 |
|
779 | |||
780 | def _some_str(self, value): |
|
780 | def _some_str(self, value): | |
781 | # Lifted from traceback.py |
|
781 | # Lifted from traceback.py | |
782 | try: |
|
782 | try: | |
783 | return py3compat.cast_unicode(str(value)) |
|
783 | return py3compat.cast_unicode(str(value)) | |
784 | except: |
|
784 | except: | |
785 | return u'<unprintable %s object>' % type(value).__name__ |
|
785 | return u'<unprintable %s object>' % type(value).__name__ | |
786 |
|
786 | |||
787 |
|
787 | |||
788 | #---------------------------------------------------------------------------- |
|
788 | #---------------------------------------------------------------------------- | |
789 | class VerboseTB(TBTools): |
|
789 | class VerboseTB(TBTools): | |
790 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
790 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead | |
791 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
791 | of HTML. Requires inspect and pydoc. Crazy, man. | |
792 |
|
792 | |||
793 | Modified version which optionally strips the topmost entries from the |
|
793 | Modified version which optionally strips the topmost entries from the | |
794 | traceback, to be used with alternate interpreters (because their own code |
|
794 | traceback, to be used with alternate interpreters (because their own code | |
795 | would appear in the traceback).""" |
|
795 | would appear in the traceback).""" | |
796 |
|
796 | |||
797 | def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, |
|
797 | def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, | |
798 | tb_offset=0, long_header=False, include_vars=True, |
|
798 | tb_offset=0, long_header=False, include_vars=True, | |
799 | check_cache=None, debugger_cls = None, |
|
799 | check_cache=None, debugger_cls = None, | |
800 | parent=None, config=None): |
|
800 | parent=None, config=None): | |
801 | """Specify traceback offset, headers and color scheme. |
|
801 | """Specify traceback offset, headers and color scheme. | |
802 |
|
802 | |||
803 | Define how many frames to drop from the tracebacks. Calling it with |
|
803 | Define how many frames to drop from the tracebacks. Calling it with | |
804 | tb_offset=1 allows use of this handler in interpreters which will have |
|
804 | tb_offset=1 allows use of this handler in interpreters which will have | |
805 | their own code at the top of the traceback (VerboseTB will first |
|
805 | their own code at the top of the traceback (VerboseTB will first | |
806 | remove that frame before printing the traceback info).""" |
|
806 | remove that frame before printing the traceback info).""" | |
807 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
807 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
808 | ostream=ostream, parent=parent, config=config) |
|
808 | ostream=ostream, parent=parent, config=config) | |
809 | self.tb_offset = tb_offset |
|
809 | self.tb_offset = tb_offset | |
810 | self.long_header = long_header |
|
810 | self.long_header = long_header | |
811 | self.include_vars = include_vars |
|
811 | self.include_vars = include_vars | |
812 | # By default we use linecache.checkcache, but the user can provide a |
|
812 | # By default we use linecache.checkcache, but the user can provide a | |
813 | # different check_cache implementation. This is used by the IPython |
|
813 | # different check_cache implementation. This is used by the IPython | |
814 | # kernel to provide tracebacks for interactive code that is cached, |
|
814 | # kernel to provide tracebacks for interactive code that is cached, | |
815 | # by a compiler instance that flushes the linecache but preserves its |
|
815 | # by a compiler instance that flushes the linecache but preserves its | |
816 | # own code cache. |
|
816 | # own code cache. | |
817 | if check_cache is None: |
|
817 | if check_cache is None: | |
818 | check_cache = linecache.checkcache |
|
818 | check_cache = linecache.checkcache | |
819 | self.check_cache = check_cache |
|
819 | self.check_cache = check_cache | |
820 |
|
820 | |||
821 | self.debugger_cls = debugger_cls or debugger.Pdb |
|
821 | self.debugger_cls = debugger_cls or debugger.Pdb | |
822 |
|
822 | |||
823 | def format_records(self, records, last_unique, recursion_repeat): |
|
823 | def format_records(self, records, last_unique, recursion_repeat): | |
824 | """Format the stack frames of the traceback""" |
|
824 | """Format the stack frames of the traceback""" | |
825 | frames = [] |
|
825 | frames = [] | |
826 | for r in records[:last_unique+recursion_repeat+1]: |
|
826 | for r in records[:last_unique+recursion_repeat+1]: | |
827 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
827 | #print '*** record:',file,lnum,func,lines,index # dbg | |
828 | frames.append(self.format_record(*r)) |
|
828 | frames.append(self.format_record(*r)) | |
829 |
|
829 | |||
830 | if recursion_repeat: |
|
830 | if recursion_repeat: | |
831 | frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) |
|
831 | frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) | |
832 | frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) |
|
832 | frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) | |
833 |
|
833 | |||
834 | return frames |
|
834 | return frames | |
835 |
|
835 | |||
836 | def format_record(self, frame, file, lnum, func, lines, index): |
|
836 | def format_record(self, frame, file, lnum, func, lines, index): | |
837 | """Format a single stack frame""" |
|
837 | """Format a single stack frame""" | |
838 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
838 | Colors = self.Colors # just a shorthand + quicker name lookup | |
839 | ColorsNormal = Colors.Normal # used a lot |
|
839 | ColorsNormal = Colors.Normal # used a lot | |
840 | col_scheme = self.color_scheme_table.active_scheme_name |
|
840 | col_scheme = self.color_scheme_table.active_scheme_name | |
841 | indent = ' ' * INDENT_SIZE |
|
841 | indent = ' ' * INDENT_SIZE | |
842 | em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) |
|
842 | em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) | |
843 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
843 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) | |
844 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
844 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) | |
845 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
845 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, | |
846 | ColorsNormal) |
|
846 | ColorsNormal) | |
847 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
847 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ | |
848 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
848 | (Colors.vName, Colors.valEm, ColorsNormal) | |
849 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
849 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) | |
850 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
850 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, | |
851 | Colors.vName, ColorsNormal) |
|
851 | Colors.vName, ColorsNormal) | |
852 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
852 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) | |
853 |
|
853 | |||
854 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
854 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) | |
855 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, |
|
855 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, | |
856 | ColorsNormal) |
|
856 | ColorsNormal) | |
857 |
|
857 | |||
858 | abspath = os.path.abspath |
|
858 | abspath = os.path.abspath | |
859 |
|
859 | |||
860 |
|
860 | |||
861 | if not file: |
|
861 | if not file: | |
862 | file = '?' |
|
862 | file = '?' | |
863 | elif file.startswith(str("<")) and file.endswith(str(">")): |
|
863 | elif file.startswith(str("<")) and file.endswith(str(">")): | |
864 | # Not a real filename, no problem... |
|
864 | # Not a real filename, no problem... | |
865 | pass |
|
865 | pass | |
866 | elif not os.path.isabs(file): |
|
866 | elif not os.path.isabs(file): | |
867 | # Try to make the filename absolute by trying all |
|
867 | # Try to make the filename absolute by trying all | |
868 | # sys.path entries (which is also what linecache does) |
|
868 | # sys.path entries (which is also what linecache does) | |
869 | for dirname in sys.path: |
|
869 | for dirname in sys.path: | |
870 | try: |
|
870 | try: | |
871 | fullname = os.path.join(dirname, file) |
|
871 | fullname = os.path.join(dirname, file) | |
872 | if os.path.isfile(fullname): |
|
872 | if os.path.isfile(fullname): | |
873 | file = os.path.abspath(fullname) |
|
873 | file = os.path.abspath(fullname) | |
874 | break |
|
874 | break | |
875 | except Exception: |
|
875 | except Exception: | |
876 | # Just in case that sys.path contains very |
|
876 | # Just in case that sys.path contains very | |
877 | # strange entries... |
|
877 | # strange entries... | |
878 | pass |
|
878 | pass | |
879 |
|
879 | |||
880 | file = py3compat.cast_unicode(file, util_path.fs_encoding) |
|
880 | file = py3compat.cast_unicode(file, util_path.fs_encoding) | |
881 | link = tpl_link % file |
|
881 | link = tpl_link % file | |
882 | args, varargs, varkw, locals = fixed_getargvalues(frame) |
|
882 | args, varargs, varkw, locals = fixed_getargvalues(frame) | |
883 |
|
883 | |||
884 | if func == '?': |
|
884 | if func == '?': | |
885 | call = '' |
|
885 | call = '' | |
886 | else: |
|
886 | else: | |
887 | # Decide whether to include variable details or not |
|
887 | # Decide whether to include variable details or not | |
888 | var_repr = self.include_vars and eqrepr or nullrepr |
|
888 | var_repr = self.include_vars and eqrepr or nullrepr | |
889 | try: |
|
889 | try: | |
890 | call = tpl_call % (func, inspect.formatargvalues(args, |
|
890 | call = tpl_call % (func, inspect.formatargvalues(args, | |
891 | varargs, varkw, |
|
891 | varargs, varkw, | |
892 | locals, formatvalue=var_repr)) |
|
892 | locals, formatvalue=var_repr)) | |
893 | except KeyError: |
|
893 | except KeyError: | |
894 | # This happens in situations like errors inside generator |
|
894 | # This happens in situations like errors inside generator | |
895 | # expressions, where local variables are listed in the |
|
895 | # expressions, where local variables are listed in the | |
896 | # line, but can't be extracted from the frame. I'm not |
|
896 | # line, but can't be extracted from the frame. I'm not | |
897 | # 100% sure this isn't actually a bug in inspect itself, |
|
897 | # 100% sure this isn't actually a bug in inspect itself, | |
898 | # but since there's no info for us to compute with, the |
|
898 | # but since there's no info for us to compute with, the | |
899 | # best we can do is report the failure and move on. Here |
|
899 | # best we can do is report the failure and move on. Here | |
900 | # we must *not* call any traceback construction again, |
|
900 | # we must *not* call any traceback construction again, | |
901 | # because that would mess up use of %debug later on. So we |
|
901 | # because that would mess up use of %debug later on. So we | |
902 | # simply report the failure and move on. The only |
|
902 | # simply report the failure and move on. The only | |
903 | # limitation will be that this frame won't have locals |
|
903 | # limitation will be that this frame won't have locals | |
904 | # listed in the call signature. Quite subtle problem... |
|
904 | # listed in the call signature. Quite subtle problem... | |
905 | # I can't think of a good way to validate this in a unit |
|
905 | # I can't think of a good way to validate this in a unit | |
906 | # test, but running a script consisting of: |
|
906 | # test, but running a script consisting of: | |
907 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
907 | # dict( (k,v.strip()) for (k,v) in range(10) ) | |
908 | # will illustrate the error, if this exception catch is |
|
908 | # will illustrate the error, if this exception catch is | |
909 | # disabled. |
|
909 | # disabled. | |
910 | call = tpl_call_fail % func |
|
910 | call = tpl_call_fail % func | |
911 |
|
911 | |||
912 | # Don't attempt to tokenize binary files. |
|
912 | # Don't attempt to tokenize binary files. | |
913 | if file.endswith(('.so', '.pyd', '.dll')): |
|
913 | if file.endswith(('.so', '.pyd', '.dll')): | |
914 | return '%s %s\n' % (link, call) |
|
914 | return '%s %s\n' % (link, call) | |
915 |
|
915 | |||
916 | elif file.endswith(('.pyc', '.pyo')): |
|
916 | elif file.endswith(('.pyc', '.pyo')): | |
917 | # Look up the corresponding source file. |
|
917 | # Look up the corresponding source file. | |
918 | try: |
|
918 | try: | |
919 | file = openpy.source_from_cache(file) |
|
919 | file = openpy.source_from_cache(file) | |
920 | except ValueError: |
|
920 | except ValueError: | |
921 | # Failed to get the source file for some reason |
|
921 | # Failed to get the source file for some reason | |
922 | # E.g. https://github.com/ipython/ipython/issues/9486 |
|
922 | # E.g. https://github.com/ipython/ipython/issues/9486 | |
923 | return '%s %s\n' % (link, call) |
|
923 | return '%s %s\n' % (link, call) | |
924 |
|
924 | |||
925 | def linereader(file=file, lnum=[lnum], getline=ulinecache.getline): |
|
925 | def linereader(file=file, lnum=[lnum], getline=ulinecache.getline): | |
926 | line = getline(file, lnum[0]) |
|
926 | line = getline(file, lnum[0]) | |
927 | lnum[0] += 1 |
|
927 | lnum[0] += 1 | |
928 | return line |
|
928 | return line | |
929 |
|
929 | |||
930 | # Build the list of names on this line of code where the exception |
|
930 | # Build the list of names on this line of code where the exception | |
931 | # occurred. |
|
931 | # occurred. | |
932 | try: |
|
932 | try: | |
933 | names = [] |
|
933 | names = [] | |
934 | name_cont = False |
|
934 | name_cont = False | |
935 |
|
935 | |||
936 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
936 | for token_type, token, start, end, line in generate_tokens(linereader): | |
937 | # build composite names |
|
937 | # build composite names | |
938 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
938 | if token_type == tokenize.NAME and token not in keyword.kwlist: | |
939 | if name_cont: |
|
939 | if name_cont: | |
940 | # Continuation of a dotted name |
|
940 | # Continuation of a dotted name | |
941 | try: |
|
941 | try: | |
942 | names[-1].append(token) |
|
942 | names[-1].append(token) | |
943 | except IndexError: |
|
943 | except IndexError: | |
944 | names.append([token]) |
|
944 | names.append([token]) | |
945 | name_cont = False |
|
945 | name_cont = False | |
946 | else: |
|
946 | else: | |
947 | # Regular new names. We append everything, the caller |
|
947 | # Regular new names. We append everything, the caller | |
948 | # will be responsible for pruning the list later. It's |
|
948 | # will be responsible for pruning the list later. It's | |
949 | # very tricky to try to prune as we go, b/c composite |
|
949 | # very tricky to try to prune as we go, b/c composite | |
950 | # names can fool us. The pruning at the end is easy |
|
950 | # names can fool us. The pruning at the end is easy | |
951 | # to do (or the caller can print a list with repeated |
|
951 | # to do (or the caller can print a list with repeated | |
952 | # names if so desired. |
|
952 | # names if so desired. | |
953 | names.append([token]) |
|
953 | names.append([token]) | |
954 | elif token == '.': |
|
954 | elif token == '.': | |
955 | name_cont = True |
|
955 | name_cont = True | |
956 | elif token_type == tokenize.NEWLINE: |
|
956 | elif token_type == tokenize.NEWLINE: | |
957 | break |
|
957 | break | |
958 |
|
958 | |||
959 | except (IndexError, UnicodeDecodeError, SyntaxError): |
|
959 | except (IndexError, UnicodeDecodeError, SyntaxError): | |
960 | # signals exit of tokenizer |
|
960 | # signals exit of tokenizer | |
961 | # SyntaxError can occur if the file is not actually Python |
|
961 | # SyntaxError can occur if the file is not actually Python | |
962 | # - see gh-6300 |
|
962 | # - see gh-6300 | |
963 | pass |
|
963 | pass | |
964 | except tokenize.TokenError as msg: |
|
964 | except tokenize.TokenError as msg: | |
965 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
965 | _m = ("An unexpected error occurred while tokenizing input\n" | |
966 | "The following traceback may be corrupted or invalid\n" |
|
966 | "The following traceback may be corrupted or invalid\n" | |
967 | "The error message is: %s\n" % msg) |
|
967 | "The error message is: %s\n" % msg) | |
968 | error(_m) |
|
968 | error(_m) | |
969 |
|
969 | |||
970 | # Join composite names (e.g. "dict.fromkeys") |
|
970 | # Join composite names (e.g. "dict.fromkeys") | |
971 | names = ['.'.join(n) for n in names] |
|
971 | names = ['.'.join(n) for n in names] | |
972 | # prune names list of duplicates, but keep the right order |
|
972 | # prune names list of duplicates, but keep the right order | |
973 | unique_names = uniq_stable(names) |
|
973 | unique_names = uniq_stable(names) | |
974 |
|
974 | |||
975 | # Start loop over vars |
|
975 | # Start loop over vars | |
976 | lvals = [] |
|
976 | lvals = [] | |
977 | if self.include_vars: |
|
977 | if self.include_vars: | |
978 | for name_full in unique_names: |
|
978 | for name_full in unique_names: | |
979 | name_base = name_full.split('.', 1)[0] |
|
979 | name_base = name_full.split('.', 1)[0] | |
980 | if name_base in frame.f_code.co_varnames: |
|
980 | if name_base in frame.f_code.co_varnames: | |
981 | if name_base in locals: |
|
981 | if name_base in locals: | |
982 | try: |
|
982 | try: | |
983 | value = repr(eval(name_full, locals)) |
|
983 | value = repr(eval(name_full, locals)) | |
984 | except: |
|
984 | except: | |
985 | value = undefined |
|
985 | value = undefined | |
986 | else: |
|
986 | else: | |
987 | value = undefined |
|
987 | value = undefined | |
988 | name = tpl_local_var % name_full |
|
988 | name = tpl_local_var % name_full | |
989 | else: |
|
989 | else: | |
990 | if name_base in frame.f_globals: |
|
990 | if name_base in frame.f_globals: | |
991 | try: |
|
991 | try: | |
992 | value = repr(eval(name_full, frame.f_globals)) |
|
992 | value = repr(eval(name_full, frame.f_globals)) | |
993 | except: |
|
993 | except: | |
994 | value = undefined |
|
994 | value = undefined | |
995 | else: |
|
995 | else: | |
996 | value = undefined |
|
996 | value = undefined | |
997 | name = tpl_global_var % name_full |
|
997 | name = tpl_global_var % name_full | |
998 | lvals.append(tpl_name_val % (name, value)) |
|
998 | lvals.append(tpl_name_val % (name, value)) | |
999 | if lvals: |
|
999 | if lvals: | |
1000 | lvals = '%s%s' % (indent, em_normal.join(lvals)) |
|
1000 | lvals = '%s%s' % (indent, em_normal.join(lvals)) | |
1001 | else: |
|
1001 | else: | |
1002 | lvals = '' |
|
1002 | lvals = '' | |
1003 |
|
1003 | |||
1004 | level = '%s %s\n' % (link, call) |
|
1004 | level = '%s %s\n' % (link, call) | |
1005 |
|
1005 | |||
1006 | if index is None: |
|
1006 | if index is None: | |
1007 | return level |
|
1007 | return level | |
1008 | else: |
|
1008 | else: | |
1009 | _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2 |
|
1009 | _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2 | |
1010 | return '%s%s' % (level, ''.join( |
|
1010 | return '%s%s' % (level, ''.join( | |
1011 | _format_traceback_lines(lnum, index, lines, Colors, lvals, |
|
1011 | _format_traceback_lines(lnum, index, lines, Colors, lvals, | |
1012 | _line_format))) |
|
1012 | _line_format))) | |
1013 |
|
1013 | |||
1014 | def prepare_chained_exception_message(self, cause): |
|
1014 | def prepare_chained_exception_message(self, cause): | |
1015 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" |
|
1015 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" | |
1016 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" |
|
1016 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" | |
1017 |
|
1017 | |||
1018 | if cause: |
|
1018 | if cause: | |
1019 | message = [[direct_cause]] |
|
1019 | message = [[direct_cause]] | |
1020 | else: |
|
1020 | else: | |
1021 | message = [[exception_during_handling]] |
|
1021 | message = [[exception_during_handling]] | |
1022 | return message |
|
1022 | return message | |
1023 |
|
1023 | |||
1024 | def prepare_header(self, etype, long_version=False): |
|
1024 | def prepare_header(self, etype, long_version=False): | |
1025 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1025 | colors = self.Colors # just a shorthand + quicker name lookup | |
1026 | colorsnormal = colors.Normal # used a lot |
|
1026 | colorsnormal = colors.Normal # used a lot | |
1027 | exc = '%s%s%s' % (colors.excName, etype, colorsnormal) |
|
1027 | exc = '%s%s%s' % (colors.excName, etype, colorsnormal) | |
1028 | width = min(75, get_terminal_size()[0]) |
|
1028 | width = min(75, get_terminal_size()[0]) | |
1029 | if long_version: |
|
1029 | if long_version: | |
1030 | # Header with the exception type, python version, and date |
|
1030 | # Header with the exception type, python version, and date | |
1031 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
1031 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable | |
1032 | date = time.ctime(time.time()) |
|
1032 | date = time.ctime(time.time()) | |
1033 |
|
1033 | |||
1034 | head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, |
|
1034 | head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, | |
1035 | exc, ' ' * (width - len(str(etype)) - len(pyver)), |
|
1035 | exc, ' ' * (width - len(str(etype)) - len(pyver)), | |
1036 | pyver, date.rjust(width) ) |
|
1036 | pyver, date.rjust(width) ) | |
1037 | head += "\nA problem occurred executing Python code. Here is the sequence of function" \ |
|
1037 | head += "\nA problem occurred executing Python code. Here is the sequence of function" \ | |
1038 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
1038 | "\ncalls leading up to the error, with the most recent (innermost) call last." | |
1039 | else: |
|
1039 | else: | |
1040 | # Simplified header |
|
1040 | # Simplified header | |
1041 | head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ |
|
1041 | head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ | |
1042 | rjust(width - len(str(etype))) ) |
|
1042 | rjust(width - len(str(etype))) ) | |
1043 |
|
1043 | |||
1044 | return head |
|
1044 | return head | |
1045 |
|
1045 | |||
1046 | def format_exception(self, etype, evalue): |
|
1046 | def format_exception(self, etype, evalue): | |
1047 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1047 | colors = self.Colors # just a shorthand + quicker name lookup | |
1048 | colorsnormal = colors.Normal # used a lot |
|
1048 | colorsnormal = colors.Normal # used a lot | |
1049 | indent = ' ' * INDENT_SIZE |
|
1049 | indent = ' ' * INDENT_SIZE | |
1050 | # Get (safely) a string form of the exception info |
|
1050 | # Get (safely) a string form of the exception info | |
1051 | try: |
|
1051 | try: | |
1052 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1052 | etype_str, evalue_str = map(str, (etype, evalue)) | |
1053 | except: |
|
1053 | except: | |
1054 | # User exception is improperly defined. |
|
1054 | # User exception is improperly defined. | |
1055 | etype, evalue = str, sys.exc_info()[:2] |
|
1055 | etype, evalue = str, sys.exc_info()[:2] | |
1056 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1056 | etype_str, evalue_str = map(str, (etype, evalue)) | |
1057 | # ... and format it |
|
1057 | # ... and format it | |
1058 |
|
|
1058 | return ['%s%s%s: %s' % (colors.excName, etype_str, | |
1059 |
|
|
1059 | colorsnormal, py3compat.cast_unicode(evalue_str))] | |
1060 |
|
1060 | |||
1061 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: |
|
|||
1062 | try: |
|
|||
1063 | names = [w for w in dir(evalue) if isinstance(w, str)] |
|
|||
1064 | except: |
|
|||
1065 | # Every now and then, an object with funny internals blows up |
|
|||
1066 | # when dir() is called on it. We do the best we can to report |
|
|||
1067 | # the problem and continue |
|
|||
1068 | _m = '%sException reporting error (object with broken dir())%s:' |
|
|||
1069 | exception.append(_m % (colors.excName, colorsnormal)) |
|
|||
1070 | etype_str, evalue_str = map(str, sys.exc_info()[:2]) |
|
|||
1071 | exception.append('%s%s%s: %s' % (colors.excName, etype_str, |
|
|||
1072 | colorsnormal, py3compat.cast_unicode(evalue_str))) |
|
|||
1073 | names = [] |
|
|||
1074 | for name in names: |
|
|||
1075 | value = text_repr(getattr(evalue, name)) |
|
|||
1076 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
|||
1077 |
|
||||
1078 | return exception |
|
|||
1079 |
|
||||
1080 | def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset): |
|
1061 | def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset): | |
1081 | """Formats the header, traceback and exception message for a single exception. |
|
1062 | """Formats the header, traceback and exception message for a single exception. | |
1082 |
|
1063 | |||
1083 | This may be called multiple times by Python 3 exception chaining |
|
1064 | This may be called multiple times by Python 3 exception chaining | |
1084 | (PEP 3134). |
|
1065 | (PEP 3134). | |
1085 | """ |
|
1066 | """ | |
1086 | # some locals |
|
1067 | # some locals | |
1087 | orig_etype = etype |
|
1068 | orig_etype = etype | |
1088 | try: |
|
1069 | try: | |
1089 | etype = etype.__name__ |
|
1070 | etype = etype.__name__ | |
1090 | except AttributeError: |
|
1071 | except AttributeError: | |
1091 | pass |
|
1072 | pass | |
1092 |
|
1073 | |||
1093 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1074 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
1094 | head = self.prepare_header(etype, self.long_header) |
|
1075 | head = self.prepare_header(etype, self.long_header) | |
1095 | records = self.get_records(etb, number_of_lines_of_context, tb_offset) |
|
1076 | records = self.get_records(etb, number_of_lines_of_context, tb_offset) | |
1096 |
|
1077 | |||
1097 | if records is None: |
|
1078 | if records is None: | |
1098 | return "" |
|
1079 | return "" | |
1099 |
|
1080 | |||
1100 | last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) |
|
1081 | last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) | |
1101 |
|
1082 | |||
1102 | frames = self.format_records(records, last_unique, recursion_repeat) |
|
1083 | frames = self.format_records(records, last_unique, recursion_repeat) | |
1103 |
|
1084 | |||
1104 | formatted_exception = self.format_exception(etype, evalue) |
|
1085 | formatted_exception = self.format_exception(etype, evalue) | |
1105 | if records: |
|
1086 | if records: | |
1106 | filepath, lnum = records[-1][1:3] |
|
1087 | filepath, lnum = records[-1][1:3] | |
1107 | filepath = os.path.abspath(filepath) |
|
1088 | filepath = os.path.abspath(filepath) | |
1108 | ipinst = get_ipython() |
|
1089 | ipinst = get_ipython() | |
1109 | if ipinst is not None: |
|
1090 | if ipinst is not None: | |
1110 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
1091 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) | |
1111 |
|
1092 | |||
1112 | return [[head] + frames + [''.join(formatted_exception[0])]] |
|
1093 | return [[head] + frames + [''.join(formatted_exception[0])]] | |
1113 |
|
1094 | |||
1114 | def get_records(self, etb, number_of_lines_of_context, tb_offset): |
|
1095 | def get_records(self, etb, number_of_lines_of_context, tb_offset): | |
1115 | try: |
|
1096 | try: | |
1116 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
1097 | # Try the default getinnerframes and Alex's: Alex's fixes some | |
1117 | # problems, but it generates empty tracebacks for console errors |
|
1098 | # problems, but it generates empty tracebacks for console errors | |
1118 | # (5 blanks lines) where none should be returned. |
|
1099 | # (5 blanks lines) where none should be returned. | |
1119 | return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) |
|
1100 | return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) | |
1120 | except UnicodeDecodeError: |
|
1101 | except UnicodeDecodeError: | |
1121 | # This can occur if a file's encoding magic comment is wrong. |
|
1102 | # This can occur if a file's encoding magic comment is wrong. | |
1122 | # I can't see a way to recover without duplicating a bunch of code |
|
1103 | # I can't see a way to recover without duplicating a bunch of code | |
1123 | # from the stdlib traceback module. --TK |
|
1104 | # from the stdlib traceback module. --TK | |
1124 | error('\nUnicodeDecodeError while processing traceback.\n') |
|
1105 | error('\nUnicodeDecodeError while processing traceback.\n') | |
1125 | return None |
|
1106 | return None | |
1126 | except: |
|
1107 | except: | |
1127 | # FIXME: I've been getting many crash reports from python 2.3 |
|
1108 | # FIXME: I've been getting many crash reports from python 2.3 | |
1128 | # users, traceable to inspect.py. If I can find a small test-case |
|
1109 | # users, traceable to inspect.py. If I can find a small test-case | |
1129 | # to reproduce this, I should either write a better workaround or |
|
1110 | # to reproduce this, I should either write a better workaround or | |
1130 | # file a bug report against inspect (if that's the real problem). |
|
1111 | # file a bug report against inspect (if that's the real problem). | |
1131 | # So far, I haven't been able to find an isolated example to |
|
1112 | # So far, I haven't been able to find an isolated example to | |
1132 | # reproduce the problem. |
|
1113 | # reproduce the problem. | |
1133 | inspect_error() |
|
1114 | inspect_error() | |
1134 | traceback.print_exc(file=self.ostream) |
|
1115 | traceback.print_exc(file=self.ostream) | |
1135 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
1116 | info('\nUnfortunately, your original traceback can not be constructed.\n') | |
1136 | return None |
|
1117 | return None | |
1137 |
|
1118 | |||
1138 | def get_parts_of_chained_exception(self, evalue): |
|
1119 | def get_parts_of_chained_exception(self, evalue): | |
1139 | def get_chained_exception(exception_value): |
|
1120 | def get_chained_exception(exception_value): | |
1140 | cause = getattr(exception_value, '__cause__', None) |
|
1121 | cause = getattr(exception_value, '__cause__', None) | |
1141 | if cause: |
|
1122 | if cause: | |
1142 | return cause |
|
1123 | return cause | |
1143 | if getattr(exception_value, '__suppress_context__', False): |
|
1124 | if getattr(exception_value, '__suppress_context__', False): | |
1144 | return None |
|
1125 | return None | |
1145 | return getattr(exception_value, '__context__', None) |
|
1126 | return getattr(exception_value, '__context__', None) | |
1146 |
|
1127 | |||
1147 | chained_evalue = get_chained_exception(evalue) |
|
1128 | chained_evalue = get_chained_exception(evalue) | |
1148 |
|
1129 | |||
1149 | if chained_evalue: |
|
1130 | if chained_evalue: | |
1150 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ |
|
1131 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ | |
1151 |
|
1132 | |||
1152 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
1133 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, | |
1153 | number_of_lines_of_context=5): |
|
1134 | number_of_lines_of_context=5): | |
1154 | """Return a nice text document describing the traceback.""" |
|
1135 | """Return a nice text document describing the traceback.""" | |
1155 |
|
1136 | |||
1156 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, |
|
1137 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, | |
1157 | tb_offset) |
|
1138 | tb_offset) | |
1158 |
|
1139 | |||
1159 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1140 | colors = self.Colors # just a shorthand + quicker name lookup | |
1160 | colorsnormal = colors.Normal # used a lot |
|
1141 | colorsnormal = colors.Normal # used a lot | |
1161 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) |
|
1142 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) | |
1162 | structured_traceback_parts = [head] |
|
1143 | structured_traceback_parts = [head] | |
1163 | if py3compat.PY3: |
|
1144 | if py3compat.PY3: | |
1164 | chained_exceptions_tb_offset = 0 |
|
1145 | chained_exceptions_tb_offset = 0 | |
1165 | lines_of_context = 3 |
|
1146 | lines_of_context = 3 | |
1166 | formatted_exceptions = formatted_exception |
|
1147 | formatted_exceptions = formatted_exception | |
1167 | exception = self.get_parts_of_chained_exception(evalue) |
|
1148 | exception = self.get_parts_of_chained_exception(evalue) | |
1168 | if exception: |
|
1149 | if exception: | |
1169 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1150 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) | |
1170 | etype, evalue, etb = exception |
|
1151 | etype, evalue, etb = exception | |
1171 | else: |
|
1152 | else: | |
1172 | evalue = None |
|
1153 | evalue = None | |
1173 | chained_exc_ids = set() |
|
1154 | chained_exc_ids = set() | |
1174 | while evalue: |
|
1155 | while evalue: | |
1175 | formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, |
|
1156 | formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, | |
1176 | chained_exceptions_tb_offset) |
|
1157 | chained_exceptions_tb_offset) | |
1177 | exception = self.get_parts_of_chained_exception(evalue) |
|
1158 | exception = self.get_parts_of_chained_exception(evalue) | |
1178 |
|
1159 | |||
1179 | if exception and not id(exception[1]) in chained_exc_ids: |
|
1160 | if exception and not id(exception[1]) in chained_exc_ids: | |
1180 | chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop |
|
1161 | chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop | |
1181 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1162 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) | |
1182 | etype, evalue, etb = exception |
|
1163 | etype, evalue, etb = exception | |
1183 | else: |
|
1164 | else: | |
1184 | evalue = None |
|
1165 | evalue = None | |
1185 |
|
1166 | |||
1186 | # we want to see exceptions in a reversed order: |
|
1167 | # we want to see exceptions in a reversed order: | |
1187 | # the first exception should be on top |
|
1168 | # the first exception should be on top | |
1188 | for formatted_exception in reversed(formatted_exceptions): |
|
1169 | for formatted_exception in reversed(formatted_exceptions): | |
1189 | structured_traceback_parts += formatted_exception |
|
1170 | structured_traceback_parts += formatted_exception | |
1190 | else: |
|
1171 | else: | |
1191 | structured_traceback_parts += formatted_exception[0] |
|
1172 | structured_traceback_parts += formatted_exception[0] | |
1192 |
|
1173 | |||
1193 | return structured_traceback_parts |
|
1174 | return structured_traceback_parts | |
1194 |
|
1175 | |||
1195 | def debugger(self, force=False): |
|
1176 | def debugger(self, force=False): | |
1196 | """Call up the pdb debugger if desired, always clean up the tb |
|
1177 | """Call up the pdb debugger if desired, always clean up the tb | |
1197 | reference. |
|
1178 | reference. | |
1198 |
|
1179 | |||
1199 | Keywords: |
|
1180 | Keywords: | |
1200 |
|
1181 | |||
1201 | - force(False): by default, this routine checks the instance call_pdb |
|
1182 | - force(False): by default, this routine checks the instance call_pdb | |
1202 | flag and does not actually invoke the debugger if the flag is false. |
|
1183 | flag and does not actually invoke the debugger if the flag is false. | |
1203 | The 'force' option forces the debugger to activate even if the flag |
|
1184 | The 'force' option forces the debugger to activate even if the flag | |
1204 | is false. |
|
1185 | is false. | |
1205 |
|
1186 | |||
1206 | If the call_pdb flag is set, the pdb interactive debugger is |
|
1187 | If the call_pdb flag is set, the pdb interactive debugger is | |
1207 | invoked. In all cases, the self.tb reference to the current traceback |
|
1188 | invoked. In all cases, the self.tb reference to the current traceback | |
1208 | is deleted to prevent lingering references which hamper memory |
|
1189 | is deleted to prevent lingering references which hamper memory | |
1209 | management. |
|
1190 | management. | |
1210 |
|
1191 | |||
1211 | Note that each call to pdb() does an 'import readline', so if your app |
|
1192 | Note that each call to pdb() does an 'import readline', so if your app | |
1212 | requires a special setup for the readline completers, you'll have to |
|
1193 | requires a special setup for the readline completers, you'll have to | |
1213 | fix that by hand after invoking the exception handler.""" |
|
1194 | fix that by hand after invoking the exception handler.""" | |
1214 |
|
1195 | |||
1215 | if force or self.call_pdb: |
|
1196 | if force or self.call_pdb: | |
1216 | if self.pdb is None: |
|
1197 | if self.pdb is None: | |
1217 | self.pdb = self.debugger_cls() |
|
1198 | self.pdb = self.debugger_cls() | |
1218 | # the system displayhook may have changed, restore the original |
|
1199 | # the system displayhook may have changed, restore the original | |
1219 | # for pdb |
|
1200 | # for pdb | |
1220 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
1201 | display_trap = DisplayTrap(hook=sys.__displayhook__) | |
1221 | with display_trap: |
|
1202 | with display_trap: | |
1222 | self.pdb.reset() |
|
1203 | self.pdb.reset() | |
1223 | # Find the right frame so we don't pop up inside ipython itself |
|
1204 | # Find the right frame so we don't pop up inside ipython itself | |
1224 | if hasattr(self, 'tb') and self.tb is not None: |
|
1205 | if hasattr(self, 'tb') and self.tb is not None: | |
1225 | etb = self.tb |
|
1206 | etb = self.tb | |
1226 | else: |
|
1207 | else: | |
1227 | etb = self.tb = sys.last_traceback |
|
1208 | etb = self.tb = sys.last_traceback | |
1228 | while self.tb is not None and self.tb.tb_next is not None: |
|
1209 | while self.tb is not None and self.tb.tb_next is not None: | |
1229 | self.tb = self.tb.tb_next |
|
1210 | self.tb = self.tb.tb_next | |
1230 | if etb and etb.tb_next: |
|
1211 | if etb and etb.tb_next: | |
1231 | etb = etb.tb_next |
|
1212 | etb = etb.tb_next | |
1232 | self.pdb.botframe = etb.tb_frame |
|
1213 | self.pdb.botframe = etb.tb_frame | |
1233 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1214 | self.pdb.interaction(self.tb.tb_frame, self.tb) | |
1234 |
|
1215 | |||
1235 | if hasattr(self, 'tb'): |
|
1216 | if hasattr(self, 'tb'): | |
1236 | del self.tb |
|
1217 | del self.tb | |
1237 |
|
1218 | |||
1238 | def handler(self, info=None): |
|
1219 | def handler(self, info=None): | |
1239 | (etype, evalue, etb) = info or sys.exc_info() |
|
1220 | (etype, evalue, etb) = info or sys.exc_info() | |
1240 | self.tb = etb |
|
1221 | self.tb = etb | |
1241 | ostream = self.ostream |
|
1222 | ostream = self.ostream | |
1242 | ostream.flush() |
|
1223 | ostream.flush() | |
1243 | ostream.write(self.text(etype, evalue, etb)) |
|
1224 | ostream.write(self.text(etype, evalue, etb)) | |
1244 | ostream.write('\n') |
|
1225 | ostream.write('\n') | |
1245 | ostream.flush() |
|
1226 | ostream.flush() | |
1246 |
|
1227 | |||
1247 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1228 | # Changed so an instance can just be called as VerboseTB_inst() and print | |
1248 | # out the right info on its own. |
|
1229 | # out the right info on its own. | |
1249 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1230 | def __call__(self, etype=None, evalue=None, etb=None): | |
1250 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1231 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" | |
1251 | if etb is None: |
|
1232 | if etb is None: | |
1252 | self.handler() |
|
1233 | self.handler() | |
1253 | else: |
|
1234 | else: | |
1254 | self.handler((etype, evalue, etb)) |
|
1235 | self.handler((etype, evalue, etb)) | |
1255 | try: |
|
1236 | try: | |
1256 | self.debugger() |
|
1237 | self.debugger() | |
1257 | except KeyboardInterrupt: |
|
1238 | except KeyboardInterrupt: | |
1258 | print("\nKeyboardInterrupt") |
|
1239 | print("\nKeyboardInterrupt") | |
1259 |
|
1240 | |||
1260 |
|
1241 | |||
1261 | #---------------------------------------------------------------------------- |
|
1242 | #---------------------------------------------------------------------------- | |
1262 | class FormattedTB(VerboseTB, ListTB): |
|
1243 | class FormattedTB(VerboseTB, ListTB): | |
1263 | """Subclass ListTB but allow calling with a traceback. |
|
1244 | """Subclass ListTB but allow calling with a traceback. | |
1264 |
|
1245 | |||
1265 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1246 | It can thus be used as a sys.excepthook for Python > 2.1. | |
1266 |
|
1247 | |||
1267 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1248 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. | |
1268 |
|
1249 | |||
1269 | Allows a tb_offset to be specified. This is useful for situations where |
|
1250 | Allows a tb_offset to be specified. This is useful for situations where | |
1270 | one needs to remove a number of topmost frames from the traceback (such as |
|
1251 | one needs to remove a number of topmost frames from the traceback (such as | |
1271 | occurs with python programs that themselves execute other python code, |
|
1252 | occurs with python programs that themselves execute other python code, | |
1272 | like Python shells). """ |
|
1253 | like Python shells). """ | |
1273 |
|
1254 | |||
1274 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1255 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, | |
1275 | ostream=None, |
|
1256 | ostream=None, | |
1276 | tb_offset=0, long_header=False, include_vars=False, |
|
1257 | tb_offset=0, long_header=False, include_vars=False, | |
1277 | check_cache=None, debugger_cls=None, |
|
1258 | check_cache=None, debugger_cls=None, | |
1278 | parent=None, config=None): |
|
1259 | parent=None, config=None): | |
1279 |
|
1260 | |||
1280 | # NEVER change the order of this list. Put new modes at the end: |
|
1261 | # NEVER change the order of this list. Put new modes at the end: | |
1281 | self.valid_modes = ['Plain', 'Context', 'Verbose'] |
|
1262 | self.valid_modes = ['Plain', 'Context', 'Verbose'] | |
1282 | self.verbose_modes = self.valid_modes[1:3] |
|
1263 | self.verbose_modes = self.valid_modes[1:3] | |
1283 |
|
1264 | |||
1284 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1265 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
1285 | ostream=ostream, tb_offset=tb_offset, |
|
1266 | ostream=ostream, tb_offset=tb_offset, | |
1286 | long_header=long_header, include_vars=include_vars, |
|
1267 | long_header=long_header, include_vars=include_vars, | |
1287 | check_cache=check_cache, debugger_cls=debugger_cls, |
|
1268 | check_cache=check_cache, debugger_cls=debugger_cls, | |
1288 | parent=parent, config=config) |
|
1269 | parent=parent, config=config) | |
1289 |
|
1270 | |||
1290 | # Different types of tracebacks are joined with different separators to |
|
1271 | # Different types of tracebacks are joined with different separators to | |
1291 | # form a single string. They are taken from this dict |
|
1272 | # form a single string. They are taken from this dict | |
1292 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1273 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') | |
1293 | # set_mode also sets the tb_join_char attribute |
|
1274 | # set_mode also sets the tb_join_char attribute | |
1294 | self.set_mode(mode) |
|
1275 | self.set_mode(mode) | |
1295 |
|
1276 | |||
1296 | def _extract_tb(self, tb): |
|
1277 | def _extract_tb(self, tb): | |
1297 | if tb: |
|
1278 | if tb: | |
1298 | return traceback.extract_tb(tb) |
|
1279 | return traceback.extract_tb(tb) | |
1299 | else: |
|
1280 | else: | |
1300 | return None |
|
1281 | return None | |
1301 |
|
1282 | |||
1302 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): |
|
1283 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): | |
1303 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1284 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
1304 | mode = self.mode |
|
1285 | mode = self.mode | |
1305 | if mode in self.verbose_modes: |
|
1286 | if mode in self.verbose_modes: | |
1306 | # Verbose modes need a full traceback |
|
1287 | # Verbose modes need a full traceback | |
1307 | return VerboseTB.structured_traceback( |
|
1288 | return VerboseTB.structured_traceback( | |
1308 | self, etype, value, tb, tb_offset, number_of_lines_of_context |
|
1289 | self, etype, value, tb, tb_offset, number_of_lines_of_context | |
1309 | ) |
|
1290 | ) | |
1310 | else: |
|
1291 | else: | |
1311 | # We must check the source cache because otherwise we can print |
|
1292 | # We must check the source cache because otherwise we can print | |
1312 | # out-of-date source code. |
|
1293 | # out-of-date source code. | |
1313 | self.check_cache() |
|
1294 | self.check_cache() | |
1314 | # Now we can extract and format the exception |
|
1295 | # Now we can extract and format the exception | |
1315 | elist = self._extract_tb(tb) |
|
1296 | elist = self._extract_tb(tb) | |
1316 | return ListTB.structured_traceback( |
|
1297 | return ListTB.structured_traceback( | |
1317 | self, etype, value, elist, tb_offset, number_of_lines_of_context |
|
1298 | self, etype, value, elist, tb_offset, number_of_lines_of_context | |
1318 | ) |
|
1299 | ) | |
1319 |
|
1300 | |||
1320 | def stb2text(self, stb): |
|
1301 | def stb2text(self, stb): | |
1321 | """Convert a structured traceback (a list) to a string.""" |
|
1302 | """Convert a structured traceback (a list) to a string.""" | |
1322 | return self.tb_join_char.join(stb) |
|
1303 | return self.tb_join_char.join(stb) | |
1323 |
|
1304 | |||
1324 |
|
1305 | |||
1325 | def set_mode(self, mode=None): |
|
1306 | def set_mode(self, mode=None): | |
1326 | """Switch to the desired mode. |
|
1307 | """Switch to the desired mode. | |
1327 |
|
1308 | |||
1328 | If mode is not specified, cycles through the available modes.""" |
|
1309 | If mode is not specified, cycles through the available modes.""" | |
1329 |
|
1310 | |||
1330 | if not mode: |
|
1311 | if not mode: | |
1331 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ |
|
1312 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ | |
1332 | len(self.valid_modes) |
|
1313 | len(self.valid_modes) | |
1333 | self.mode = self.valid_modes[new_idx] |
|
1314 | self.mode = self.valid_modes[new_idx] | |
1334 | elif mode not in self.valid_modes: |
|
1315 | elif mode not in self.valid_modes: | |
1335 | raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n' |
|
1316 | raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n' | |
1336 | 'Valid modes: ' + str(self.valid_modes)) |
|
1317 | 'Valid modes: ' + str(self.valid_modes)) | |
1337 | else: |
|
1318 | else: | |
1338 | self.mode = mode |
|
1319 | self.mode = mode | |
1339 | # include variable details only in 'Verbose' mode |
|
1320 | # include variable details only in 'Verbose' mode | |
1340 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1321 | self.include_vars = (self.mode == self.valid_modes[2]) | |
1341 | # Set the join character for generating text tracebacks |
|
1322 | # Set the join character for generating text tracebacks | |
1342 | self.tb_join_char = self._join_chars[self.mode] |
|
1323 | self.tb_join_char = self._join_chars[self.mode] | |
1343 |
|
1324 | |||
1344 | # some convenient shortcuts |
|
1325 | # some convenient shortcuts | |
1345 | def plain(self): |
|
1326 | def plain(self): | |
1346 | self.set_mode(self.valid_modes[0]) |
|
1327 | self.set_mode(self.valid_modes[0]) | |
1347 |
|
1328 | |||
1348 | def context(self): |
|
1329 | def context(self): | |
1349 | self.set_mode(self.valid_modes[1]) |
|
1330 | self.set_mode(self.valid_modes[1]) | |
1350 |
|
1331 | |||
1351 | def verbose(self): |
|
1332 | def verbose(self): | |
1352 | self.set_mode(self.valid_modes[2]) |
|
1333 | self.set_mode(self.valid_modes[2]) | |
1353 |
|
1334 | |||
1354 |
|
1335 | |||
1355 | #---------------------------------------------------------------------------- |
|
1336 | #---------------------------------------------------------------------------- | |
1356 | class AutoFormattedTB(FormattedTB): |
|
1337 | class AutoFormattedTB(FormattedTB): | |
1357 | """A traceback printer which can be called on the fly. |
|
1338 | """A traceback printer which can be called on the fly. | |
1358 |
|
1339 | |||
1359 | It will find out about exceptions by itself. |
|
1340 | It will find out about exceptions by itself. | |
1360 |
|
1341 | |||
1361 | A brief example:: |
|
1342 | A brief example:: | |
1362 |
|
1343 | |||
1363 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1344 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') | |
1364 | try: |
|
1345 | try: | |
1365 | ... |
|
1346 | ... | |
1366 | except: |
|
1347 | except: | |
1367 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1348 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object | |
1368 | """ |
|
1349 | """ | |
1369 |
|
1350 | |||
1370 | def __call__(self, etype=None, evalue=None, etb=None, |
|
1351 | def __call__(self, etype=None, evalue=None, etb=None, | |
1371 | out=None, tb_offset=None): |
|
1352 | out=None, tb_offset=None): | |
1372 | """Print out a formatted exception traceback. |
|
1353 | """Print out a formatted exception traceback. | |
1373 |
|
1354 | |||
1374 | Optional arguments: |
|
1355 | Optional arguments: | |
1375 | - out: an open file-like object to direct output to. |
|
1356 | - out: an open file-like object to direct output to. | |
1376 |
|
1357 | |||
1377 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1358 | - tb_offset: the number of frames to skip over in the stack, on a | |
1378 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1359 | per-call basis (this overrides temporarily the instance's tb_offset | |
1379 | given at initialization time. """ |
|
1360 | given at initialization time. """ | |
1380 |
|
1361 | |||
1381 | if out is None: |
|
1362 | if out is None: | |
1382 | out = self.ostream |
|
1363 | out = self.ostream | |
1383 | out.flush() |
|
1364 | out.flush() | |
1384 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1365 | out.write(self.text(etype, evalue, etb, tb_offset)) | |
1385 | out.write('\n') |
|
1366 | out.write('\n') | |
1386 | out.flush() |
|
1367 | out.flush() | |
1387 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1368 | # FIXME: we should remove the auto pdb behavior from here and leave | |
1388 | # that to the clients. |
|
1369 | # that to the clients. | |
1389 | try: |
|
1370 | try: | |
1390 | self.debugger() |
|
1371 | self.debugger() | |
1391 | except KeyboardInterrupt: |
|
1372 | except KeyboardInterrupt: | |
1392 | print("\nKeyboardInterrupt") |
|
1373 | print("\nKeyboardInterrupt") | |
1393 |
|
1374 | |||
1394 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1375 | def structured_traceback(self, etype=None, value=None, tb=None, | |
1395 | tb_offset=None, number_of_lines_of_context=5): |
|
1376 | tb_offset=None, number_of_lines_of_context=5): | |
1396 | if etype is None: |
|
1377 | if etype is None: | |
1397 | etype, value, tb = sys.exc_info() |
|
1378 | etype, value, tb = sys.exc_info() | |
1398 | self.tb = tb |
|
1379 | self.tb = tb | |
1399 | return FormattedTB.structured_traceback( |
|
1380 | return FormattedTB.structured_traceback( | |
1400 | self, etype, value, tb, tb_offset, number_of_lines_of_context) |
|
1381 | self, etype, value, tb, tb_offset, number_of_lines_of_context) | |
1401 |
|
1382 | |||
1402 |
|
1383 | |||
1403 | #--------------------------------------------------------------------------- |
|
1384 | #--------------------------------------------------------------------------- | |
1404 |
|
1385 | |||
1405 | # A simple class to preserve Nathan's original functionality. |
|
1386 | # A simple class to preserve Nathan's original functionality. | |
1406 | class ColorTB(FormattedTB): |
|
1387 | class ColorTB(FormattedTB): | |
1407 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1388 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" | |
1408 |
|
1389 | |||
1409 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): |
|
1390 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): | |
1410 | FormattedTB.__init__(self, color_scheme=color_scheme, |
|
1391 | FormattedTB.__init__(self, color_scheme=color_scheme, | |
1411 | call_pdb=call_pdb, **kwargs) |
|
1392 | call_pdb=call_pdb, **kwargs) | |
1412 |
|
1393 | |||
1413 |
|
1394 | |||
1414 | class SyntaxTB(ListTB): |
|
1395 | class SyntaxTB(ListTB): | |
1415 | """Extension which holds some state: the last exception value""" |
|
1396 | """Extension which holds some state: the last exception value""" | |
1416 |
|
1397 | |||
1417 | def __init__(self, color_scheme='NoColor', parent=None, config=None): |
|
1398 | def __init__(self, color_scheme='NoColor', parent=None, config=None): | |
1418 | ListTB.__init__(self, color_scheme, parent=parent, config=config) |
|
1399 | ListTB.__init__(self, color_scheme, parent=parent, config=config) | |
1419 | self.last_syntax_error = None |
|
1400 | self.last_syntax_error = None | |
1420 |
|
1401 | |||
1421 | def __call__(self, etype, value, elist): |
|
1402 | def __call__(self, etype, value, elist): | |
1422 | self.last_syntax_error = value |
|
1403 | self.last_syntax_error = value | |
1423 |
|
1404 | |||
1424 | ListTB.__call__(self, etype, value, elist) |
|
1405 | ListTB.__call__(self, etype, value, elist) | |
1425 |
|
1406 | |||
1426 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
1407 | def structured_traceback(self, etype, value, elist, tb_offset=None, | |
1427 | context=5): |
|
1408 | context=5): | |
1428 | # If the source file has been edited, the line in the syntax error can |
|
1409 | # If the source file has been edited, the line in the syntax error can | |
1429 | # be wrong (retrieved from an outdated cache). This replaces it with |
|
1410 | # be wrong (retrieved from an outdated cache). This replaces it with | |
1430 | # the current value. |
|
1411 | # the current value. | |
1431 | if isinstance(value, SyntaxError) \ |
|
1412 | if isinstance(value, SyntaxError) \ | |
1432 | and isinstance(value.filename, str) \ |
|
1413 | and isinstance(value.filename, str) \ | |
1433 | and isinstance(value.lineno, int): |
|
1414 | and isinstance(value.lineno, int): | |
1434 | linecache.checkcache(value.filename) |
|
1415 | linecache.checkcache(value.filename) | |
1435 | newtext = ulinecache.getline(value.filename, value.lineno) |
|
1416 | newtext = ulinecache.getline(value.filename, value.lineno) | |
1436 | if newtext: |
|
1417 | if newtext: | |
1437 | value.text = newtext |
|
1418 | value.text = newtext | |
1438 | self.last_syntax_error = value |
|
1419 | self.last_syntax_error = value | |
1439 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, |
|
1420 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, | |
1440 | tb_offset=tb_offset, context=context) |
|
1421 | tb_offset=tb_offset, context=context) | |
1441 |
|
1422 | |||
1442 | def clear_err_state(self): |
|
1423 | def clear_err_state(self): | |
1443 | """Return the current error state and clear it""" |
|
1424 | """Return the current error state and clear it""" | |
1444 | e = self.last_syntax_error |
|
1425 | e = self.last_syntax_error | |
1445 | self.last_syntax_error = None |
|
1426 | self.last_syntax_error = None | |
1446 | return e |
|
1427 | return e | |
1447 |
|
1428 | |||
1448 | def stb2text(self, stb): |
|
1429 | def stb2text(self, stb): | |
1449 | """Convert a structured traceback (a list) to a string.""" |
|
1430 | """Convert a structured traceback (a list) to a string.""" | |
1450 | return ''.join(stb) |
|
1431 | return ''.join(stb) | |
1451 |
|
1432 | |||
1452 |
|
1433 | |||
1453 | # some internal-use functions |
|
1434 | # some internal-use functions | |
1454 | def text_repr(value): |
|
1435 | def text_repr(value): | |
1455 | """Hopefully pretty robust repr equivalent.""" |
|
1436 | """Hopefully pretty robust repr equivalent.""" | |
1456 | # this is pretty horrible but should always return *something* |
|
1437 | # this is pretty horrible but should always return *something* | |
1457 | try: |
|
1438 | try: | |
1458 | return pydoc.text.repr(value) |
|
1439 | return pydoc.text.repr(value) | |
1459 | except KeyboardInterrupt: |
|
1440 | except KeyboardInterrupt: | |
1460 | raise |
|
1441 | raise | |
1461 | except: |
|
1442 | except: | |
1462 | try: |
|
1443 | try: | |
1463 | return repr(value) |
|
1444 | return repr(value) | |
1464 | except KeyboardInterrupt: |
|
1445 | except KeyboardInterrupt: | |
1465 | raise |
|
1446 | raise | |
1466 | except: |
|
1447 | except: | |
1467 | try: |
|
1448 | try: | |
1468 | # all still in an except block so we catch |
|
1449 | # all still in an except block so we catch | |
1469 | # getattr raising |
|
1450 | # getattr raising | |
1470 | name = getattr(value, '__name__', None) |
|
1451 | name = getattr(value, '__name__', None) | |
1471 | if name: |
|
1452 | if name: | |
1472 | # ick, recursion |
|
1453 | # ick, recursion | |
1473 | return text_repr(name) |
|
1454 | return text_repr(name) | |
1474 | klass = getattr(value, '__class__', None) |
|
1455 | klass = getattr(value, '__class__', None) | |
1475 | if klass: |
|
1456 | if klass: | |
1476 | return '%s instance' % text_repr(klass) |
|
1457 | return '%s instance' % text_repr(klass) | |
1477 | except KeyboardInterrupt: |
|
1458 | except KeyboardInterrupt: | |
1478 | raise |
|
1459 | raise | |
1479 | except: |
|
1460 | except: | |
1480 | return 'UNRECOVERABLE REPR FAILURE' |
|
1461 | return 'UNRECOVERABLE REPR FAILURE' | |
1481 |
|
1462 | |||
1482 |
|
1463 | |||
1483 | def eqrepr(value, repr=text_repr): |
|
1464 | def eqrepr(value, repr=text_repr): | |
1484 | return '=%s' % repr(value) |
|
1465 | return '=%s' % repr(value) | |
1485 |
|
1466 | |||
1486 |
|
1467 | |||
1487 | def nullrepr(value, repr=text_repr): |
|
1468 | def nullrepr(value, repr=text_repr): | |
1488 | return '' |
|
1469 | return '' |
@@ -1,532 +1,528 b'' | |||||
1 | """IPython extension to reload modules before executing user code. |
|
1 | """IPython extension to reload modules before executing user code. | |
2 |
|
2 | |||
3 | ``autoreload`` reloads modules automatically before entering the execution of |
|
3 | ``autoreload`` reloads modules automatically before entering the execution of | |
4 | code typed at the IPython prompt. |
|
4 | code typed at the IPython prompt. | |
5 |
|
5 | |||
6 | This makes for example the following workflow possible: |
|
6 | This makes for example the following workflow possible: | |
7 |
|
7 | |||
8 | .. sourcecode:: ipython |
|
8 | .. sourcecode:: ipython | |
9 |
|
9 | |||
10 | In [1]: %load_ext autoreload |
|
10 | In [1]: %load_ext autoreload | |
11 |
|
11 | |||
12 | In [2]: %autoreload 2 |
|
12 | In [2]: %autoreload 2 | |
13 |
|
13 | |||
14 | In [3]: from foo import some_function |
|
14 | In [3]: from foo import some_function | |
15 |
|
15 | |||
16 | In [4]: some_function() |
|
16 | In [4]: some_function() | |
17 | Out[4]: 42 |
|
17 | Out[4]: 42 | |
18 |
|
18 | |||
19 | In [5]: # open foo.py in an editor and change some_function to return 43 |
|
19 | In [5]: # open foo.py in an editor and change some_function to return 43 | |
20 |
|
20 | |||
21 | In [6]: some_function() |
|
21 | In [6]: some_function() | |
22 | Out[6]: 43 |
|
22 | Out[6]: 43 | |
23 |
|
23 | |||
24 | The module was reloaded without reloading it explicitly, and the object |
|
24 | The module was reloaded without reloading it explicitly, and the object | |
25 | imported with ``from foo import ...`` was also updated. |
|
25 | imported with ``from foo import ...`` was also updated. | |
26 |
|
26 | |||
27 | Usage |
|
27 | Usage | |
28 | ===== |
|
28 | ===== | |
29 |
|
29 | |||
30 | The following magic commands are provided: |
|
30 | The following magic commands are provided: | |
31 |
|
31 | |||
32 | ``%autoreload`` |
|
32 | ``%autoreload`` | |
33 |
|
33 | |||
34 | Reload all modules (except those excluded by ``%aimport``) |
|
34 | Reload all modules (except those excluded by ``%aimport``) | |
35 | automatically now. |
|
35 | automatically now. | |
36 |
|
36 | |||
37 | ``%autoreload 0`` |
|
37 | ``%autoreload 0`` | |
38 |
|
38 | |||
39 | Disable automatic reloading. |
|
39 | Disable automatic reloading. | |
40 |
|
40 | |||
41 | ``%autoreload 1`` |
|
41 | ``%autoreload 1`` | |
42 |
|
42 | |||
43 | Reload all modules imported with ``%aimport`` every time before |
|
43 | Reload all modules imported with ``%aimport`` every time before | |
44 | executing the Python code typed. |
|
44 | executing the Python code typed. | |
45 |
|
45 | |||
46 | ``%autoreload 2`` |
|
46 | ``%autoreload 2`` | |
47 |
|
47 | |||
48 | Reload all modules (except those excluded by ``%aimport``) every |
|
48 | Reload all modules (except those excluded by ``%aimport``) every | |
49 | time before executing the Python code typed. |
|
49 | time before executing the Python code typed. | |
50 |
|
50 | |||
51 | ``%aimport`` |
|
51 | ``%aimport`` | |
52 |
|
52 | |||
53 | List modules which are to be automatically imported or not to be imported. |
|
53 | List modules which are to be automatically imported or not to be imported. | |
54 |
|
54 | |||
55 | ``%aimport foo`` |
|
55 | ``%aimport foo`` | |
56 |
|
56 | |||
57 | Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1`` |
|
57 | Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1`` | |
58 |
|
58 | |||
59 | ``%aimport foo, bar`` |
|
59 | ``%aimport foo, bar`` | |
60 |
|
60 | |||
61 | Import modules 'foo', 'bar' and mark them to be autoreloaded for ``%autoreload 1`` |
|
61 | Import modules 'foo', 'bar' and mark them to be autoreloaded for ``%autoreload 1`` | |
62 |
|
62 | |||
63 | ``%aimport -foo`` |
|
63 | ``%aimport -foo`` | |
64 |
|
64 | |||
65 | Mark module 'foo' to not be autoreloaded. |
|
65 | Mark module 'foo' to not be autoreloaded. | |
66 |
|
66 | |||
67 | Caveats |
|
67 | Caveats | |
68 | ======= |
|
68 | ======= | |
69 |
|
69 | |||
70 | Reloading Python modules in a reliable way is in general difficult, |
|
70 | Reloading Python modules in a reliable way is in general difficult, | |
71 | and unexpected things may occur. ``%autoreload`` tries to work around |
|
71 | and unexpected things may occur. ``%autoreload`` tries to work around | |
72 | common pitfalls by replacing function code objects and parts of |
|
72 | common pitfalls by replacing function code objects and parts of | |
73 | classes previously in the module with new versions. This makes the |
|
73 | classes previously in the module with new versions. This makes the | |
74 | following things to work: |
|
74 | following things to work: | |
75 |
|
75 | |||
76 | - Functions and classes imported via 'from xxx import foo' are upgraded |
|
76 | - Functions and classes imported via 'from xxx import foo' are upgraded | |
77 | to new versions when 'xxx' is reloaded. |
|
77 | to new versions when 'xxx' is reloaded. | |
78 |
|
78 | |||
79 | - Methods and properties of classes are upgraded on reload, so that |
|
79 | - Methods and properties of classes are upgraded on reload, so that | |
80 | calling 'c.foo()' on an object 'c' created before the reload causes |
|
80 | calling 'c.foo()' on an object 'c' created before the reload causes | |
81 | the new code for 'foo' to be executed. |
|
81 | the new code for 'foo' to be executed. | |
82 |
|
82 | |||
83 | Some of the known remaining caveats are: |
|
83 | Some of the known remaining caveats are: | |
84 |
|
84 | |||
85 | - Replacing code objects does not always succeed: changing a @property |
|
85 | - Replacing code objects does not always succeed: changing a @property | |
86 | in a class to an ordinary method or a method to a member variable |
|
86 | in a class to an ordinary method or a method to a member variable | |
87 | can cause problems (but in old objects only). |
|
87 | can cause problems (but in old objects only). | |
88 |
|
88 | |||
89 | - Functions that are removed (eg. via monkey-patching) from a module |
|
89 | - Functions that are removed (eg. via monkey-patching) from a module | |
90 | before it is reloaded are not upgraded. |
|
90 | before it is reloaded are not upgraded. | |
91 |
|
91 | |||
92 | - C extension modules cannot be reloaded, and so cannot be autoreloaded. |
|
92 | - C extension modules cannot be reloaded, and so cannot be autoreloaded. | |
93 | """ |
|
93 | """ | |
94 |
|
94 | |||
95 | skip_doctest = True |
|
95 | skip_doctest = True | |
96 |
|
96 | |||
97 | #----------------------------------------------------------------------------- |
|
97 | #----------------------------------------------------------------------------- | |
98 | # Copyright (C) 2000 Thomas Heller |
|
98 | # Copyright (C) 2000 Thomas Heller | |
99 | # Copyright (C) 2008 Pauli Virtanen <pav@iki.fi> |
|
99 | # Copyright (C) 2008 Pauli Virtanen <pav@iki.fi> | |
100 | # Copyright (C) 2012 The IPython Development Team |
|
100 | # Copyright (C) 2012 The IPython Development Team | |
101 | # |
|
101 | # | |
102 | # Distributed under the terms of the BSD License. The full license is in |
|
102 | # Distributed under the terms of the BSD License. The full license is in | |
103 | # the file COPYING, distributed as part of this software. |
|
103 | # the file COPYING, distributed as part of this software. | |
104 | #----------------------------------------------------------------------------- |
|
104 | #----------------------------------------------------------------------------- | |
105 | # |
|
105 | # | |
106 | # This IPython module is written by Pauli Virtanen, based on the autoreload |
|
106 | # This IPython module is written by Pauli Virtanen, based on the autoreload | |
107 | # code by Thomas Heller. |
|
107 | # code by Thomas Heller. | |
108 |
|
108 | |||
109 | #----------------------------------------------------------------------------- |
|
109 | #----------------------------------------------------------------------------- | |
110 | # Imports |
|
110 | # Imports | |
111 | #----------------------------------------------------------------------------- |
|
111 | #----------------------------------------------------------------------------- | |
112 |
|
112 | |||
113 | import os |
|
113 | import os | |
114 | import sys |
|
114 | import sys | |
115 | import traceback |
|
115 | import traceback | |
116 | import types |
|
116 | import types | |
117 | import weakref |
|
117 | import weakref | |
118 | from importlib import import_module |
|
118 | from importlib import import_module | |
119 |
|
119 | from IPython.utils.py3compat import PY3 | ||
120 | try: |
|
120 | try: | |
121 | # Reload is not defined by default in Python3. |
|
121 | # Reload is not defined by default in Python3. | |
122 | reload |
|
122 | reload | |
123 | except NameError: |
|
123 | except NameError: | |
124 | from imp import reload |
|
124 | from imp import reload | |
125 |
|
125 | |||
126 | from IPython.utils import openpy |
|
126 | from IPython.utils import openpy | |
127 | from IPython.utils.py3compat import PY3 |
|
|||
128 |
|
127 | |||
129 | #------------------------------------------------------------------------------ |
|
128 | #------------------------------------------------------------------------------ | |
130 | # Autoreload functionality |
|
129 | # Autoreload functionality | |
131 | #------------------------------------------------------------------------------ |
|
130 | #------------------------------------------------------------------------------ | |
132 |
|
131 | |||
133 | class ModuleReloader(object): |
|
132 | class ModuleReloader(object): | |
134 | enabled = False |
|
133 | enabled = False | |
135 | """Whether this reloader is enabled""" |
|
134 | """Whether this reloader is enabled""" | |
136 |
|
135 | |||
137 | check_all = True |
|
136 | check_all = True | |
138 | """Autoreload all modules, not just those listed in 'modules'""" |
|
137 | """Autoreload all modules, not just those listed in 'modules'""" | |
139 |
|
138 | |||
140 | def __init__(self): |
|
139 | def __init__(self): | |
141 | # Modules that failed to reload: {module: mtime-on-failed-reload, ...} |
|
140 | # Modules that failed to reload: {module: mtime-on-failed-reload, ...} | |
142 | self.failed = {} |
|
141 | self.failed = {} | |
143 | # Modules specially marked as autoreloadable. |
|
142 | # Modules specially marked as autoreloadable. | |
144 | self.modules = {} |
|
143 | self.modules = {} | |
145 | # Modules specially marked as not autoreloadable. |
|
144 | # Modules specially marked as not autoreloadable. | |
146 | self.skip_modules = {} |
|
145 | self.skip_modules = {} | |
147 | # (module-name, name) -> weakref, for replacing old code objects |
|
146 | # (module-name, name) -> weakref, for replacing old code objects | |
148 | self.old_objects = {} |
|
147 | self.old_objects = {} | |
149 | # Module modification timestamps |
|
148 | # Module modification timestamps | |
150 | self.modules_mtimes = {} |
|
149 | self.modules_mtimes = {} | |
151 |
|
150 | |||
152 | # Cache module modification times |
|
151 | # Cache module modification times | |
153 | self.check(check_all=True, do_reload=False) |
|
152 | self.check(check_all=True, do_reload=False) | |
154 |
|
153 | |||
155 | def mark_module_skipped(self, module_name): |
|
154 | def mark_module_skipped(self, module_name): | |
156 | """Skip reloading the named module in the future""" |
|
155 | """Skip reloading the named module in the future""" | |
157 | try: |
|
156 | try: | |
158 | del self.modules[module_name] |
|
157 | del self.modules[module_name] | |
159 | except KeyError: |
|
158 | except KeyError: | |
160 | pass |
|
159 | pass | |
161 | self.skip_modules[module_name] = True |
|
160 | self.skip_modules[module_name] = True | |
162 |
|
161 | |||
163 | def mark_module_reloadable(self, module_name): |
|
162 | def mark_module_reloadable(self, module_name): | |
164 | """Reload the named module in the future (if it is imported)""" |
|
163 | """Reload the named module in the future (if it is imported)""" | |
165 | try: |
|
164 | try: | |
166 | del self.skip_modules[module_name] |
|
165 | del self.skip_modules[module_name] | |
167 | except KeyError: |
|
166 | except KeyError: | |
168 | pass |
|
167 | pass | |
169 | self.modules[module_name] = True |
|
168 | self.modules[module_name] = True | |
170 |
|
169 | |||
171 | def aimport_module(self, module_name): |
|
170 | def aimport_module(self, module_name): | |
172 | """Import a module, and mark it reloadable |
|
171 | """Import a module, and mark it reloadable | |
173 |
|
172 | |||
174 | Returns |
|
173 | Returns | |
175 | ------- |
|
174 | ------- | |
176 | top_module : module |
|
175 | top_module : module | |
177 | The imported module if it is top-level, or the top-level |
|
176 | The imported module if it is top-level, or the top-level | |
178 | top_name : module |
|
177 | top_name : module | |
179 | Name of top_module |
|
178 | Name of top_module | |
180 |
|
179 | |||
181 | """ |
|
180 | """ | |
182 | self.mark_module_reloadable(module_name) |
|
181 | self.mark_module_reloadable(module_name) | |
183 |
|
182 | |||
184 | import_module(module_name) |
|
183 | import_module(module_name) | |
185 | top_name = module_name.split('.')[0] |
|
184 | top_name = module_name.split('.')[0] | |
186 | top_module = sys.modules[top_name] |
|
185 | top_module = sys.modules[top_name] | |
187 | return top_module, top_name |
|
186 | return top_module, top_name | |
188 |
|
187 | |||
189 | def filename_and_mtime(self, module): |
|
188 | def filename_and_mtime(self, module): | |
190 | if not hasattr(module, '__file__') or module.__file__ is None: |
|
189 | if not hasattr(module, '__file__') or module.__file__ is None: | |
191 | return None, None |
|
190 | return None, None | |
192 |
|
191 | |||
193 | if getattr(module, '__name__', None) == '__main__': |
|
192 | if getattr(module, '__name__', None) == '__main__': | |
194 | # we cannot reload(__main__) |
|
193 | # we cannot reload(__main__) | |
195 | return None, None |
|
194 | return None, None | |
196 |
|
195 | |||
197 | filename = module.__file__ |
|
196 | filename = module.__file__ | |
198 | path, ext = os.path.splitext(filename) |
|
197 | path, ext = os.path.splitext(filename) | |
199 |
|
198 | |||
200 | if ext.lower() == '.py': |
|
199 | if ext.lower() == '.py': | |
201 | py_filename = filename |
|
200 | py_filename = filename | |
202 | else: |
|
201 | else: | |
203 | try: |
|
202 | try: | |
204 | py_filename = openpy.source_from_cache(filename) |
|
203 | py_filename = openpy.source_from_cache(filename) | |
205 | except ValueError: |
|
204 | except ValueError: | |
206 | return None, None |
|
205 | return None, None | |
207 |
|
206 | |||
208 | try: |
|
207 | try: | |
209 | pymtime = os.stat(py_filename).st_mtime |
|
208 | pymtime = os.stat(py_filename).st_mtime | |
210 | except OSError: |
|
209 | except OSError: | |
211 | return None, None |
|
210 | return None, None | |
212 |
|
211 | |||
213 | return py_filename, pymtime |
|
212 | return py_filename, pymtime | |
214 |
|
213 | |||
215 | def check(self, check_all=False, do_reload=True): |
|
214 | def check(self, check_all=False, do_reload=True): | |
216 | """Check whether some modules need to be reloaded.""" |
|
215 | """Check whether some modules need to be reloaded.""" | |
217 |
|
216 | |||
218 | if not self.enabled and not check_all: |
|
217 | if not self.enabled and not check_all: | |
219 | return |
|
218 | return | |
220 |
|
219 | |||
221 | if check_all or self.check_all: |
|
220 | if check_all or self.check_all: | |
222 | modules = list(sys.modules.keys()) |
|
221 | modules = list(sys.modules.keys()) | |
223 | else: |
|
222 | else: | |
224 | modules = list(self.modules.keys()) |
|
223 | modules = list(self.modules.keys()) | |
225 |
|
224 | |||
226 | for modname in modules: |
|
225 | for modname in modules: | |
227 | m = sys.modules.get(modname, None) |
|
226 | m = sys.modules.get(modname, None) | |
228 |
|
227 | |||
229 | if modname in self.skip_modules: |
|
228 | if modname in self.skip_modules: | |
230 | continue |
|
229 | continue | |
231 |
|
230 | |||
232 | py_filename, pymtime = self.filename_and_mtime(m) |
|
231 | py_filename, pymtime = self.filename_and_mtime(m) | |
233 | if py_filename is None: |
|
232 | if py_filename is None: | |
234 | continue |
|
233 | continue | |
235 |
|
234 | |||
236 | try: |
|
235 | try: | |
237 | if pymtime <= self.modules_mtimes[modname]: |
|
236 | if pymtime <= self.modules_mtimes[modname]: | |
238 | continue |
|
237 | continue | |
239 | except KeyError: |
|
238 | except KeyError: | |
240 | self.modules_mtimes[modname] = pymtime |
|
239 | self.modules_mtimes[modname] = pymtime | |
241 | continue |
|
240 | continue | |
242 | else: |
|
241 | else: | |
243 | if self.failed.get(py_filename, None) == pymtime: |
|
242 | if self.failed.get(py_filename, None) == pymtime: | |
244 | continue |
|
243 | continue | |
245 |
|
244 | |||
246 | self.modules_mtimes[modname] = pymtime |
|
245 | self.modules_mtimes[modname] = pymtime | |
247 |
|
246 | |||
248 | # If we've reached this point, we should try to reload the module |
|
247 | # If we've reached this point, we should try to reload the module | |
249 | if do_reload: |
|
248 | if do_reload: | |
250 | try: |
|
249 | try: | |
251 | superreload(m, reload, self.old_objects) |
|
250 | superreload(m, reload, self.old_objects) | |
252 | if py_filename in self.failed: |
|
251 | if py_filename in self.failed: | |
253 | del self.failed[py_filename] |
|
252 | del self.failed[py_filename] | |
254 | except: |
|
253 | except: | |
255 | print("[autoreload of %s failed: %s]" % ( |
|
254 | print("[autoreload of %s failed: %s]" % ( | |
256 | modname, traceback.format_exc(1)), file=sys.stderr) |
|
255 | modname, traceback.format_exc(1)), file=sys.stderr) | |
257 | self.failed[py_filename] = pymtime |
|
256 | self.failed[py_filename] = pymtime | |
258 |
|
257 | |||
259 | #------------------------------------------------------------------------------ |
|
258 | #------------------------------------------------------------------------------ | |
260 | # superreload |
|
259 | # superreload | |
261 | #------------------------------------------------------------------------------ |
|
260 | #------------------------------------------------------------------------------ | |
262 |
|
261 | |||
263 |
|
262 | |||
264 | func_attrs = ['__code__', '__defaults__', '__doc__', |
|
263 | func_attrs = ['__code__', '__defaults__', '__doc__', | |
265 | '__closure__', '__globals__', '__dict__'] |
|
264 | '__closure__', '__globals__', '__dict__'] | |
266 |
|
265 | |||
267 |
|
266 | |||
268 | def update_function(old, new): |
|
267 | def update_function(old, new): | |
269 | """Upgrade the code object of a function""" |
|
268 | """Upgrade the code object of a function""" | |
270 | for name in func_attrs: |
|
269 | for name in func_attrs: | |
271 | try: |
|
270 | try: | |
272 | setattr(old, name, getattr(new, name)) |
|
271 | setattr(old, name, getattr(new, name)) | |
273 | except (AttributeError, TypeError): |
|
272 | except (AttributeError, TypeError): | |
274 | pass |
|
273 | pass | |
275 |
|
274 | |||
276 |
|
275 | |||
277 | def update_class(old, new): |
|
276 | def update_class(old, new): | |
278 | """Replace stuff in the __dict__ of a class, and upgrade |
|
277 | """Replace stuff in the __dict__ of a class, and upgrade | |
279 | method code objects""" |
|
278 | method code objects""" | |
280 | for key in list(old.__dict__.keys()): |
|
279 | for key in list(old.__dict__.keys()): | |
281 | old_obj = getattr(old, key) |
|
280 | old_obj = getattr(old, key) | |
282 |
|
281 | |||
283 | try: |
|
282 | try: | |
284 | new_obj = getattr(new, key) |
|
283 | new_obj = getattr(new, key) | |
285 | except AttributeError: |
|
284 | except AttributeError: | |
286 | # obsolete attribute: remove it |
|
285 | # obsolete attribute: remove it | |
287 | try: |
|
286 | try: | |
288 | delattr(old, key) |
|
287 | delattr(old, key) | |
289 | except (AttributeError, TypeError): |
|
288 | except (AttributeError, TypeError): | |
290 | pass |
|
289 | pass | |
291 | continue |
|
290 | continue | |
292 |
|
291 | |||
293 | if update_generic(old_obj, new_obj): continue |
|
292 | if update_generic(old_obj, new_obj): continue | |
294 |
|
293 | |||
295 | try: |
|
294 | try: | |
296 | setattr(old, key, getattr(new, key)) |
|
295 | setattr(old, key, getattr(new, key)) | |
297 | except (AttributeError, TypeError): |
|
296 | except (AttributeError, TypeError): | |
298 | pass # skip non-writable attributes |
|
297 | pass # skip non-writable attributes | |
299 |
|
298 | |||
300 |
|
299 | |||
301 | def update_property(old, new): |
|
300 | def update_property(old, new): | |
302 | """Replace get/set/del functions of a property""" |
|
301 | """Replace get/set/del functions of a property""" | |
303 | update_generic(old.fdel, new.fdel) |
|
302 | update_generic(old.fdel, new.fdel) | |
304 | update_generic(old.fget, new.fget) |
|
303 | update_generic(old.fget, new.fget) | |
305 | update_generic(old.fset, new.fset) |
|
304 | update_generic(old.fset, new.fset) | |
306 |
|
305 | |||
307 |
|
306 | |||
308 | def isinstance2(a, b, typ): |
|
307 | def isinstance2(a, b, typ): | |
309 | return isinstance(a, typ) and isinstance(b, typ) |
|
308 | return isinstance(a, typ) and isinstance(b, typ) | |
310 |
|
309 | |||
311 |
|
310 | |||
312 | UPDATE_RULES = [ |
|
311 | UPDATE_RULES = [ | |
313 | (lambda a, b: isinstance2(a, b, type), |
|
312 | (lambda a, b: isinstance2(a, b, type), | |
314 | update_class), |
|
313 | update_class), | |
315 | (lambda a, b: isinstance2(a, b, types.FunctionType), |
|
314 | (lambda a, b: isinstance2(a, b, types.FunctionType), | |
316 | update_function), |
|
315 | update_function), | |
317 | (lambda a, b: isinstance2(a, b, property), |
|
316 | (lambda a, b: isinstance2(a, b, property), | |
318 | update_property), |
|
317 | update_property), | |
319 | ] |
|
318 | ] | |
320 | UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType), |
|
319 | UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType), | |
321 | lambda a, b: update_function(a.__func__, b.__func__)), |
|
320 | lambda a, b: update_function(a.__func__, b.__func__)), | |
322 | ]) |
|
321 | ]) | |
323 |
|
322 | |||
324 |
|
323 | |||
325 | def update_generic(a, b): |
|
324 | def update_generic(a, b): | |
326 | for type_check, update in UPDATE_RULES: |
|
325 | for type_check, update in UPDATE_RULES: | |
327 | if type_check(a, b): |
|
326 | if type_check(a, b): | |
328 | update(a, b) |
|
327 | update(a, b) | |
329 | return True |
|
328 | return True | |
330 | return False |
|
329 | return False | |
331 |
|
330 | |||
332 |
|
331 | |||
333 | class StrongRef(object): |
|
332 | class StrongRef(object): | |
334 | def __init__(self, obj): |
|
333 | def __init__(self, obj): | |
335 | self.obj = obj |
|
334 | self.obj = obj | |
336 | def __call__(self): |
|
335 | def __call__(self): | |
337 | return self.obj |
|
336 | return self.obj | |
338 |
|
337 | |||
339 |
|
338 | |||
340 | def superreload(module, reload=reload, old_objects={}): |
|
339 | def superreload(module, reload=reload, old_objects={}): | |
341 | """Enhanced version of the builtin reload function. |
|
340 | """Enhanced version of the builtin reload function. | |
342 |
|
341 | |||
343 | superreload remembers objects previously in the module, and |
|
342 | superreload remembers objects previously in the module, and | |
344 |
|
343 | |||
345 | - upgrades the class dictionary of every old class in the module |
|
344 | - upgrades the class dictionary of every old class in the module | |
346 | - upgrades the code object of every old function and method |
|
345 | - upgrades the code object of every old function and method | |
347 | - clears the module's namespace before reloading |
|
346 | - clears the module's namespace before reloading | |
348 |
|
347 | |||
349 | """ |
|
348 | """ | |
350 |
|
349 | |||
351 | # collect old objects in the module |
|
350 | # collect old objects in the module | |
352 | for name, obj in list(module.__dict__.items()): |
|
351 | for name, obj in list(module.__dict__.items()): | |
353 | if not hasattr(obj, '__module__') or obj.__module__ != module.__name__: |
|
352 | if not hasattr(obj, '__module__') or obj.__module__ != module.__name__: | |
354 | continue |
|
353 | continue | |
355 | key = (module.__name__, name) |
|
354 | key = (module.__name__, name) | |
356 | try: |
|
355 | try: | |
357 | old_objects.setdefault(key, []).append(weakref.ref(obj)) |
|
356 | old_objects.setdefault(key, []).append(weakref.ref(obj)) | |
358 | except TypeError: |
|
357 | except TypeError: | |
359 | # weakref doesn't work for all types; |
|
358 | pass | |
360 | # create strong references for 'important' cases |
|
|||
361 | if not PY3 and isinstance(obj, types.ClassType): |
|
|||
362 | old_objects.setdefault(key, []).append(StrongRef(obj)) |
|
|||
363 |
|
359 | |||
364 | # reload module |
|
360 | # reload module | |
365 | try: |
|
361 | try: | |
366 | # clear namespace first from old cruft |
|
362 | # clear namespace first from old cruft | |
367 | old_dict = module.__dict__.copy() |
|
363 | old_dict = module.__dict__.copy() | |
368 | old_name = module.__name__ |
|
364 | old_name = module.__name__ | |
369 | module.__dict__.clear() |
|
365 | module.__dict__.clear() | |
370 | module.__dict__['__name__'] = old_name |
|
366 | module.__dict__['__name__'] = old_name | |
371 | module.__dict__['__loader__'] = old_dict['__loader__'] |
|
367 | module.__dict__['__loader__'] = old_dict['__loader__'] | |
372 | except (TypeError, AttributeError, KeyError): |
|
368 | except (TypeError, AttributeError, KeyError): | |
373 | pass |
|
369 | pass | |
374 |
|
370 | |||
375 | try: |
|
371 | try: | |
376 | module = reload(module) |
|
372 | module = reload(module) | |
377 | except: |
|
373 | except: | |
378 | # restore module dictionary on failed reload |
|
374 | # restore module dictionary on failed reload | |
379 | module.__dict__.update(old_dict) |
|
375 | module.__dict__.update(old_dict) | |
380 | raise |
|
376 | raise | |
381 |
|
377 | |||
382 | # iterate over all objects and update functions & classes |
|
378 | # iterate over all objects and update functions & classes | |
383 | for name, new_obj in list(module.__dict__.items()): |
|
379 | for name, new_obj in list(module.__dict__.items()): | |
384 | key = (module.__name__, name) |
|
380 | key = (module.__name__, name) | |
385 | if key not in old_objects: continue |
|
381 | if key not in old_objects: continue | |
386 |
|
382 | |||
387 | new_refs = [] |
|
383 | new_refs = [] | |
388 | for old_ref in old_objects[key]: |
|
384 | for old_ref in old_objects[key]: | |
389 | old_obj = old_ref() |
|
385 | old_obj = old_ref() | |
390 | if old_obj is None: continue |
|
386 | if old_obj is None: continue | |
391 | new_refs.append(old_ref) |
|
387 | new_refs.append(old_ref) | |
392 | update_generic(old_obj, new_obj) |
|
388 | update_generic(old_obj, new_obj) | |
393 |
|
389 | |||
394 | if new_refs: |
|
390 | if new_refs: | |
395 | old_objects[key] = new_refs |
|
391 | old_objects[key] = new_refs | |
396 | else: |
|
392 | else: | |
397 | del old_objects[key] |
|
393 | del old_objects[key] | |
398 |
|
394 | |||
399 | return module |
|
395 | return module | |
400 |
|
396 | |||
401 | #------------------------------------------------------------------------------ |
|
397 | #------------------------------------------------------------------------------ | |
402 | # IPython connectivity |
|
398 | # IPython connectivity | |
403 | #------------------------------------------------------------------------------ |
|
399 | #------------------------------------------------------------------------------ | |
404 |
|
400 | |||
405 | from IPython.core.magic import Magics, magics_class, line_magic |
|
401 | from IPython.core.magic import Magics, magics_class, line_magic | |
406 |
|
402 | |||
407 | @magics_class |
|
403 | @magics_class | |
408 | class AutoreloadMagics(Magics): |
|
404 | class AutoreloadMagics(Magics): | |
409 | def __init__(self, *a, **kw): |
|
405 | def __init__(self, *a, **kw): | |
410 | super(AutoreloadMagics, self).__init__(*a, **kw) |
|
406 | super(AutoreloadMagics, self).__init__(*a, **kw) | |
411 | self._reloader = ModuleReloader() |
|
407 | self._reloader = ModuleReloader() | |
412 | self._reloader.check_all = False |
|
408 | self._reloader.check_all = False | |
413 | self.loaded_modules = set(sys.modules) |
|
409 | self.loaded_modules = set(sys.modules) | |
414 |
|
410 | |||
415 | @line_magic |
|
411 | @line_magic | |
416 | def autoreload(self, parameter_s=''): |
|
412 | def autoreload(self, parameter_s=''): | |
417 | r"""%autoreload => Reload modules automatically |
|
413 | r"""%autoreload => Reload modules automatically | |
418 |
|
414 | |||
419 | %autoreload |
|
415 | %autoreload | |
420 | Reload all modules (except those excluded by %aimport) automatically |
|
416 | Reload all modules (except those excluded by %aimport) automatically | |
421 | now. |
|
417 | now. | |
422 |
|
418 | |||
423 | %autoreload 0 |
|
419 | %autoreload 0 | |
424 | Disable automatic reloading. |
|
420 | Disable automatic reloading. | |
425 |
|
421 | |||
426 | %autoreload 1 |
|
422 | %autoreload 1 | |
427 | Reload all modules imported with %aimport every time before executing |
|
423 | Reload all modules imported with %aimport every time before executing | |
428 | the Python code typed. |
|
424 | the Python code typed. | |
429 |
|
425 | |||
430 | %autoreload 2 |
|
426 | %autoreload 2 | |
431 | Reload all modules (except those excluded by %aimport) every time |
|
427 | Reload all modules (except those excluded by %aimport) every time | |
432 | before executing the Python code typed. |
|
428 | before executing the Python code typed. | |
433 |
|
429 | |||
434 | Reloading Python modules in a reliable way is in general |
|
430 | Reloading Python modules in a reliable way is in general | |
435 | difficult, and unexpected things may occur. %autoreload tries to |
|
431 | difficult, and unexpected things may occur. %autoreload tries to | |
436 | work around common pitfalls by replacing function code objects and |
|
432 | work around common pitfalls by replacing function code objects and | |
437 | parts of classes previously in the module with new versions. This |
|
433 | parts of classes previously in the module with new versions. This | |
438 | makes the following things to work: |
|
434 | makes the following things to work: | |
439 |
|
435 | |||
440 | - Functions and classes imported via 'from xxx import foo' are upgraded |
|
436 | - Functions and classes imported via 'from xxx import foo' are upgraded | |
441 | to new versions when 'xxx' is reloaded. |
|
437 | to new versions when 'xxx' is reloaded. | |
442 |
|
438 | |||
443 | - Methods and properties of classes are upgraded on reload, so that |
|
439 | - Methods and properties of classes are upgraded on reload, so that | |
444 | calling 'c.foo()' on an object 'c' created before the reload causes |
|
440 | calling 'c.foo()' on an object 'c' created before the reload causes | |
445 | the new code for 'foo' to be executed. |
|
441 | the new code for 'foo' to be executed. | |
446 |
|
442 | |||
447 | Some of the known remaining caveats are: |
|
443 | Some of the known remaining caveats are: | |
448 |
|
444 | |||
449 | - Replacing code objects does not always succeed: changing a @property |
|
445 | - Replacing code objects does not always succeed: changing a @property | |
450 | in a class to an ordinary method or a method to a member variable |
|
446 | in a class to an ordinary method or a method to a member variable | |
451 | can cause problems (but in old objects only). |
|
447 | can cause problems (but in old objects only). | |
452 |
|
448 | |||
453 | - Functions that are removed (eg. via monkey-patching) from a module |
|
449 | - Functions that are removed (eg. via monkey-patching) from a module | |
454 | before it is reloaded are not upgraded. |
|
450 | before it is reloaded are not upgraded. | |
455 |
|
451 | |||
456 | - C extension modules cannot be reloaded, and so cannot be |
|
452 | - C extension modules cannot be reloaded, and so cannot be | |
457 | autoreloaded. |
|
453 | autoreloaded. | |
458 |
|
454 | |||
459 | """ |
|
455 | """ | |
460 | if parameter_s == '': |
|
456 | if parameter_s == '': | |
461 | self._reloader.check(True) |
|
457 | self._reloader.check(True) | |
462 | elif parameter_s == '0': |
|
458 | elif parameter_s == '0': | |
463 | self._reloader.enabled = False |
|
459 | self._reloader.enabled = False | |
464 | elif parameter_s == '1': |
|
460 | elif parameter_s == '1': | |
465 | self._reloader.check_all = False |
|
461 | self._reloader.check_all = False | |
466 | self._reloader.enabled = True |
|
462 | self._reloader.enabled = True | |
467 | elif parameter_s == '2': |
|
463 | elif parameter_s == '2': | |
468 | self._reloader.check_all = True |
|
464 | self._reloader.check_all = True | |
469 | self._reloader.enabled = True |
|
465 | self._reloader.enabled = True | |
470 |
|
466 | |||
471 | @line_magic |
|
467 | @line_magic | |
472 | def aimport(self, parameter_s='', stream=None): |
|
468 | def aimport(self, parameter_s='', stream=None): | |
473 | """%aimport => Import modules for automatic reloading. |
|
469 | """%aimport => Import modules for automatic reloading. | |
474 |
|
470 | |||
475 | %aimport |
|
471 | %aimport | |
476 | List modules to automatically import and not to import. |
|
472 | List modules to automatically import and not to import. | |
477 |
|
473 | |||
478 | %aimport foo |
|
474 | %aimport foo | |
479 | Import module 'foo' and mark it to be autoreloaded for %autoreload 1 |
|
475 | Import module 'foo' and mark it to be autoreloaded for %autoreload 1 | |
480 |
|
476 | |||
481 | %aimport foo, bar |
|
477 | %aimport foo, bar | |
482 | Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1 |
|
478 | Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1 | |
483 |
|
479 | |||
484 | %aimport -foo |
|
480 | %aimport -foo | |
485 | Mark module 'foo' to not be autoreloaded for %autoreload 1 |
|
481 | Mark module 'foo' to not be autoreloaded for %autoreload 1 | |
486 | """ |
|
482 | """ | |
487 | modname = parameter_s |
|
483 | modname = parameter_s | |
488 | if not modname: |
|
484 | if not modname: | |
489 | to_reload = sorted(self._reloader.modules.keys()) |
|
485 | to_reload = sorted(self._reloader.modules.keys()) | |
490 | to_skip = sorted(self._reloader.skip_modules.keys()) |
|
486 | to_skip = sorted(self._reloader.skip_modules.keys()) | |
491 | if stream is None: |
|
487 | if stream is None: | |
492 | stream = sys.stdout |
|
488 | stream = sys.stdout | |
493 | if self._reloader.check_all: |
|
489 | if self._reloader.check_all: | |
494 | stream.write("Modules to reload:\nall-except-skipped\n") |
|
490 | stream.write("Modules to reload:\nall-except-skipped\n") | |
495 | else: |
|
491 | else: | |
496 | stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload)) |
|
492 | stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload)) | |
497 | stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip)) |
|
493 | stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip)) | |
498 | elif modname.startswith('-'): |
|
494 | elif modname.startswith('-'): | |
499 | modname = modname[1:] |
|
495 | modname = modname[1:] | |
500 | self._reloader.mark_module_skipped(modname) |
|
496 | self._reloader.mark_module_skipped(modname) | |
501 | else: |
|
497 | else: | |
502 | for _module in ([_.strip() for _ in modname.split(',')]): |
|
498 | for _module in ([_.strip() for _ in modname.split(',')]): | |
503 | top_module, top_name = self._reloader.aimport_module(_module) |
|
499 | top_module, top_name = self._reloader.aimport_module(_module) | |
504 |
|
500 | |||
505 | # Inject module to user namespace |
|
501 | # Inject module to user namespace | |
506 | self.shell.push({top_name: top_module}) |
|
502 | self.shell.push({top_name: top_module}) | |
507 |
|
503 | |||
508 | def pre_run_cell(self): |
|
504 | def pre_run_cell(self): | |
509 | if self._reloader.enabled: |
|
505 | if self._reloader.enabled: | |
510 | try: |
|
506 | try: | |
511 | self._reloader.check() |
|
507 | self._reloader.check() | |
512 | except: |
|
508 | except: | |
513 | pass |
|
509 | pass | |
514 |
|
510 | |||
515 | def post_execute_hook(self): |
|
511 | def post_execute_hook(self): | |
516 | """Cache the modification times of any modules imported in this execution |
|
512 | """Cache the modification times of any modules imported in this execution | |
517 | """ |
|
513 | """ | |
518 | newly_loaded_modules = set(sys.modules) - self.loaded_modules |
|
514 | newly_loaded_modules = set(sys.modules) - self.loaded_modules | |
519 | for modname in newly_loaded_modules: |
|
515 | for modname in newly_loaded_modules: | |
520 | _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname]) |
|
516 | _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname]) | |
521 | if pymtime is not None: |
|
517 | if pymtime is not None: | |
522 | self._reloader.modules_mtimes[modname] = pymtime |
|
518 | self._reloader.modules_mtimes[modname] = pymtime | |
523 |
|
519 | |||
524 | self.loaded_modules.update(newly_loaded_modules) |
|
520 | self.loaded_modules.update(newly_loaded_modules) | |
525 |
|
521 | |||
526 |
|
522 | |||
527 | def load_ipython_extension(ip): |
|
523 | def load_ipython_extension(ip): | |
528 | """Load the extension in IPython.""" |
|
524 | """Load the extension in IPython.""" | |
529 | auto_reload = AutoreloadMagics(ip) |
|
525 | auto_reload = AutoreloadMagics(ip) | |
530 | ip.register_magics(auto_reload) |
|
526 | ip.register_magics(auto_reload) | |
531 | ip.events.register('pre_run_cell', auto_reload.pre_run_cell) |
|
527 | ip.events.register('pre_run_cell', auto_reload.pre_run_cell) | |
532 | ip.events.register('post_execute', auto_reload.post_execute_hook) |
|
528 | ip.events.register('post_execute', auto_reload.post_execute_hook) |
@@ -1,223 +1,212 b'' | |||||
1 | """Common utilities for the various process_* implementations. |
|
1 | """Common utilities for the various process_* implementations. | |
2 |
|
2 | |||
3 | This file is only meant to be imported by the platform-specific implementations |
|
3 | This file is only meant to be imported by the platform-specific implementations | |
4 | of subprocess utilities, and it contains tools that are common to all of them. |
|
4 | of subprocess utilities, and it contains tools that are common to all of them. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2010-2011 The IPython Development Team |
|
8 | # Copyright (C) 2010-2011 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | import subprocess |
|
17 | import subprocess | |
18 | import shlex |
|
18 | import shlex | |
19 | import sys |
|
19 | import sys | |
20 | import os |
|
20 | import os | |
21 |
|
21 | |||
22 | from IPython.utils import py3compat |
|
22 | from IPython.utils import py3compat | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Function definitions |
|
25 | # Function definitions | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | def read_no_interrupt(p): |
|
28 | def read_no_interrupt(p): | |
29 | """Read from a pipe ignoring EINTR errors. |
|
29 | """Read from a pipe ignoring EINTR errors. | |
30 |
|
30 | |||
31 | This is necessary because when reading from pipes with GUI event loops |
|
31 | This is necessary because when reading from pipes with GUI event loops | |
32 | running in the background, often interrupts are raised that stop the |
|
32 | running in the background, often interrupts are raised that stop the | |
33 | command from completing.""" |
|
33 | command from completing.""" | |
34 | import errno |
|
34 | import errno | |
35 |
|
35 | |||
36 | try: |
|
36 | try: | |
37 | return p.read() |
|
37 | return p.read() | |
38 | except IOError as err: |
|
38 | except IOError as err: | |
39 | if err.errno != errno.EINTR: |
|
39 | if err.errno != errno.EINTR: | |
40 | raise |
|
40 | raise | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | def process_handler(cmd, callback, stderr=subprocess.PIPE): |
|
43 | def process_handler(cmd, callback, stderr=subprocess.PIPE): | |
44 | """Open a command in a shell subprocess and execute a callback. |
|
44 | """Open a command in a shell subprocess and execute a callback. | |
45 |
|
45 | |||
46 | This function provides common scaffolding for creating subprocess.Popen() |
|
46 | This function provides common scaffolding for creating subprocess.Popen() | |
47 | calls. It creates a Popen object and then calls the callback with it. |
|
47 | calls. It creates a Popen object and then calls the callback with it. | |
48 |
|
48 | |||
49 | Parameters |
|
49 | Parameters | |
50 | ---------- |
|
50 | ---------- | |
51 | cmd : str or list |
|
51 | cmd : str or list | |
52 | A command to be executed by the system, using :class:`subprocess.Popen`. |
|
52 | A command to be executed by the system, using :class:`subprocess.Popen`. | |
53 | If a string is passed, it will be run in the system shell. If a list is |
|
53 | If a string is passed, it will be run in the system shell. If a list is | |
54 | passed, it will be used directly as arguments. |
|
54 | passed, it will be used directly as arguments. | |
55 |
|
55 | |||
56 | callback : callable |
|
56 | callback : callable | |
57 | A one-argument function that will be called with the Popen object. |
|
57 | A one-argument function that will be called with the Popen object. | |
58 |
|
58 | |||
59 | stderr : file descriptor number, optional |
|
59 | stderr : file descriptor number, optional | |
60 | By default this is set to ``subprocess.PIPE``, but you can also pass the |
|
60 | By default this is set to ``subprocess.PIPE``, but you can also pass the | |
61 | value ``subprocess.STDOUT`` to force the subprocess' stderr to go into |
|
61 | value ``subprocess.STDOUT`` to force the subprocess' stderr to go into | |
62 | the same file descriptor as its stdout. This is useful to read stdout |
|
62 | the same file descriptor as its stdout. This is useful to read stdout | |
63 | and stderr combined in the order they are generated. |
|
63 | and stderr combined in the order they are generated. | |
64 |
|
64 | |||
65 | Returns |
|
65 | Returns | |
66 | ------- |
|
66 | ------- | |
67 | The return value of the provided callback is returned. |
|
67 | The return value of the provided callback is returned. | |
68 | """ |
|
68 | """ | |
69 | sys.stdout.flush() |
|
69 | sys.stdout.flush() | |
70 | sys.stderr.flush() |
|
70 | sys.stderr.flush() | |
71 | # On win32, close_fds can't be true when using pipes for stdin/out/err |
|
71 | # On win32, close_fds can't be true when using pipes for stdin/out/err | |
72 | close_fds = sys.platform != 'win32' |
|
72 | close_fds = sys.platform != 'win32' | |
73 | # Determine if cmd should be run with system shell. |
|
73 | # Determine if cmd should be run with system shell. | |
74 | shell = isinstance(cmd, str) |
|
74 | shell = isinstance(cmd, str) | |
75 | # On POSIX systems run shell commands with user-preferred shell. |
|
75 | # On POSIX systems run shell commands with user-preferred shell. | |
76 | executable = None |
|
76 | executable = None | |
77 | if shell and os.name == 'posix' and 'SHELL' in os.environ: |
|
77 | if shell and os.name == 'posix' and 'SHELL' in os.environ: | |
78 | executable = os.environ['SHELL'] |
|
78 | executable = os.environ['SHELL'] | |
79 | p = subprocess.Popen(cmd, shell=shell, |
|
79 | p = subprocess.Popen(cmd, shell=shell, | |
80 | executable=executable, |
|
80 | executable=executable, | |
81 | stdin=subprocess.PIPE, |
|
81 | stdin=subprocess.PIPE, | |
82 | stdout=subprocess.PIPE, |
|
82 | stdout=subprocess.PIPE, | |
83 | stderr=stderr, |
|
83 | stderr=stderr, | |
84 | close_fds=close_fds) |
|
84 | close_fds=close_fds) | |
85 |
|
85 | |||
86 | try: |
|
86 | try: | |
87 | out = callback(p) |
|
87 | out = callback(p) | |
88 | except KeyboardInterrupt: |
|
88 | except KeyboardInterrupt: | |
89 | print('^C') |
|
89 | print('^C') | |
90 | sys.stdout.flush() |
|
90 | sys.stdout.flush() | |
91 | sys.stderr.flush() |
|
91 | sys.stderr.flush() | |
92 | out = None |
|
92 | out = None | |
93 | finally: |
|
93 | finally: | |
94 | # Make really sure that we don't leave processes behind, in case the |
|
94 | # Make really sure that we don't leave processes behind, in case the | |
95 | # call above raises an exception |
|
95 | # call above raises an exception | |
96 | # We start by assuming the subprocess finished (to avoid NameErrors |
|
96 | # We start by assuming the subprocess finished (to avoid NameErrors | |
97 | # later depending on the path taken) |
|
97 | # later depending on the path taken) | |
98 | if p.returncode is None: |
|
98 | if p.returncode is None: | |
99 | try: |
|
99 | try: | |
100 | p.terminate() |
|
100 | p.terminate() | |
101 | p.poll() |
|
101 | p.poll() | |
102 | except OSError: |
|
102 | except OSError: | |
103 | pass |
|
103 | pass | |
104 | # One last try on our way out |
|
104 | # One last try on our way out | |
105 | if p.returncode is None: |
|
105 | if p.returncode is None: | |
106 | try: |
|
106 | try: | |
107 | p.kill() |
|
107 | p.kill() | |
108 | except OSError: |
|
108 | except OSError: | |
109 | pass |
|
109 | pass | |
110 |
|
110 | |||
111 | return out |
|
111 | return out | |
112 |
|
112 | |||
113 |
|
113 | |||
114 | def getoutput(cmd): |
|
114 | def getoutput(cmd): | |
115 | """Run a command and return its stdout/stderr as a string. |
|
115 | """Run a command and return its stdout/stderr as a string. | |
116 |
|
116 | |||
117 | Parameters |
|
117 | Parameters | |
118 | ---------- |
|
118 | ---------- | |
119 | cmd : str or list |
|
119 | cmd : str or list | |
120 | A command to be executed in the system shell. |
|
120 | A command to be executed in the system shell. | |
121 |
|
121 | |||
122 | Returns |
|
122 | Returns | |
123 | ------- |
|
123 | ------- | |
124 | output : str |
|
124 | output : str | |
125 | A string containing the combination of stdout and stderr from the |
|
125 | A string containing the combination of stdout and stderr from the | |
126 | subprocess, in whatever order the subprocess originally wrote to its |
|
126 | subprocess, in whatever order the subprocess originally wrote to its | |
127 | file descriptors (so the order of the information in this string is the |
|
127 | file descriptors (so the order of the information in this string is the | |
128 | correct order as would be seen if running the command in a terminal). |
|
128 | correct order as would be seen if running the command in a terminal). | |
129 | """ |
|
129 | """ | |
130 | out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT) |
|
130 | out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT) | |
131 | if out is None: |
|
131 | if out is None: | |
132 | return '' |
|
132 | return '' | |
133 | return py3compat.bytes_to_str(out) |
|
133 | return py3compat.bytes_to_str(out) | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | def getoutputerror(cmd): |
|
136 | def getoutputerror(cmd): | |
137 | """Return (standard output, standard error) of executing cmd in a shell. |
|
137 | """Return (standard output, standard error) of executing cmd in a shell. | |
138 |
|
138 | |||
139 | Accepts the same arguments as os.system(). |
|
139 | Accepts the same arguments as os.system(). | |
140 |
|
140 | |||
141 | Parameters |
|
141 | Parameters | |
142 | ---------- |
|
142 | ---------- | |
143 | cmd : str or list |
|
143 | cmd : str or list | |
144 | A command to be executed in the system shell. |
|
144 | A command to be executed in the system shell. | |
145 |
|
145 | |||
146 | Returns |
|
146 | Returns | |
147 | ------- |
|
147 | ------- | |
148 | stdout : str |
|
148 | stdout : str | |
149 | stderr : str |
|
149 | stderr : str | |
150 | """ |
|
150 | """ | |
151 | return get_output_error_code(cmd)[:2] |
|
151 | return get_output_error_code(cmd)[:2] | |
152 |
|
152 | |||
153 | def get_output_error_code(cmd): |
|
153 | def get_output_error_code(cmd): | |
154 | """Return (standard output, standard error, return code) of executing cmd |
|
154 | """Return (standard output, standard error, return code) of executing cmd | |
155 | in a shell. |
|
155 | in a shell. | |
156 |
|
156 | |||
157 | Accepts the same arguments as os.system(). |
|
157 | Accepts the same arguments as os.system(). | |
158 |
|
158 | |||
159 | Parameters |
|
159 | Parameters | |
160 | ---------- |
|
160 | ---------- | |
161 | cmd : str or list |
|
161 | cmd : str or list | |
162 | A command to be executed in the system shell. |
|
162 | A command to be executed in the system shell. | |
163 |
|
163 | |||
164 | Returns |
|
164 | Returns | |
165 | ------- |
|
165 | ------- | |
166 | stdout : str |
|
166 | stdout : str | |
167 | stderr : str |
|
167 | stderr : str | |
168 | returncode: int |
|
168 | returncode: int | |
169 | """ |
|
169 | """ | |
170 |
|
170 | |||
171 | out_err, p = process_handler(cmd, lambda p: (p.communicate(), p)) |
|
171 | out_err, p = process_handler(cmd, lambda p: (p.communicate(), p)) | |
172 | if out_err is None: |
|
172 | if out_err is None: | |
173 | return '', '', p.returncode |
|
173 | return '', '', p.returncode | |
174 | out, err = out_err |
|
174 | out, err = out_err | |
175 | return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err), p.returncode |
|
175 | return py3compat.bytes_to_str(out), py3compat.bytes_to_str(err), p.returncode | |
176 |
|
176 | |||
177 | def arg_split(s, posix=False, strict=True): |
|
177 | def arg_split(s, posix=False, strict=True): | |
178 | """Split a command line's arguments in a shell-like manner. |
|
178 | """Split a command line's arguments in a shell-like manner. | |
179 |
|
179 | |||
180 | This is a modified version of the standard library's shlex.split() |
|
180 | This is a modified version of the standard library's shlex.split() | |
181 | function, but with a default of posix=False for splitting, so that quotes |
|
181 | function, but with a default of posix=False for splitting, so that quotes | |
182 | in inputs are respected. |
|
182 | in inputs are respected. | |
183 |
|
183 | |||
184 | if strict=False, then any errors shlex.split would raise will result in the |
|
184 | if strict=False, then any errors shlex.split would raise will result in the | |
185 | unparsed remainder being the last element of the list, rather than raising. |
|
185 | unparsed remainder being the last element of the list, rather than raising. | |
186 | This is because we sometimes use arg_split to parse things other than |
|
186 | This is because we sometimes use arg_split to parse things other than | |
187 | command-line args. |
|
187 | command-line args. | |
188 | """ |
|
188 | """ | |
189 |
|
189 | |||
190 | # Unfortunately, python's shlex module is buggy with unicode input: |
|
|||
191 | # http://bugs.python.org/issue1170 |
|
|||
192 | # At least encoding the input when it's unicode seems to help, but there |
|
|||
193 | # may be more problems lurking. Apparently this is fixed in python3. |
|
|||
194 | is_unicode = False |
|
|||
195 | if (not py3compat.PY3) and isinstance(s, unicode): |
|
|||
196 | is_unicode = True |
|
|||
197 | s = s.encode('utf-8') |
|
|||
198 | lex = shlex.shlex(s, posix=posix) |
|
190 | lex = shlex.shlex(s, posix=posix) | |
199 | lex.whitespace_split = True |
|
191 | lex.whitespace_split = True | |
200 | # Extract tokens, ensuring that things like leaving open quotes |
|
192 | # Extract tokens, ensuring that things like leaving open quotes | |
201 | # does not cause this to raise. This is important, because we |
|
193 | # does not cause this to raise. This is important, because we | |
202 | # sometimes pass Python source through this (e.g. %timeit f(" ")), |
|
194 | # sometimes pass Python source through this (e.g. %timeit f(" ")), | |
203 | # and it shouldn't raise an exception. |
|
195 | # and it shouldn't raise an exception. | |
204 | # It may be a bad idea to parse things that are not command-line args |
|
196 | # It may be a bad idea to parse things that are not command-line args | |
205 | # through this function, but we do, so let's be safe about it. |
|
197 | # through this function, but we do, so let's be safe about it. | |
206 | lex.commenters='' #fix for GH-1269 |
|
198 | lex.commenters='' #fix for GH-1269 | |
207 | tokens = [] |
|
199 | tokens = [] | |
208 | while True: |
|
200 | while True: | |
209 | try: |
|
201 | try: | |
210 | tokens.append(next(lex)) |
|
202 | tokens.append(next(lex)) | |
211 | except StopIteration: |
|
203 | except StopIteration: | |
212 | break |
|
204 | break | |
213 | except ValueError: |
|
205 | except ValueError: | |
214 | if strict: |
|
206 | if strict: | |
215 | raise |
|
207 | raise | |
216 | # couldn't parse, get remaining blob as last token |
|
208 | # couldn't parse, get remaining blob as last token | |
217 | tokens.append(lex.token) |
|
209 | tokens.append(lex.token) | |
218 | break |
|
210 | break | |
219 |
|
211 | |||
220 | if is_unicode: |
|
|||
221 | # Convert the tokens back to unicode. |
|
|||
222 | tokens = [x.decode('utf-8') for x in tokens] |
|
|||
223 | return tokens |
|
212 | return tokens |
General Comments 0
You need to be logged in to leave comments.
Login now