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