Show More
@@ -1,3237 +1,3249 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.contexts import NoOpContext |
|
65 | from IPython.utils.contexts import NoOpContext | |
66 | from IPython.utils.decorators import undoc |
|
66 | from IPython.utils.decorators import undoc | |
67 | from IPython.utils.io import ask_yes_no |
|
67 | from IPython.utils.io import ask_yes_no | |
68 | from IPython.utils.ipstruct import Struct |
|
68 | from IPython.utils.ipstruct import Struct | |
69 | from IPython.paths import get_ipython_dir |
|
69 | from IPython.paths import get_ipython_dir | |
70 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
70 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists | |
71 | from IPython.utils.process import system, getoutput |
|
71 | from IPython.utils.process import system, getoutput | |
72 | from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, |
|
72 | from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, | |
73 | with_metaclass, iteritems) |
|
73 | with_metaclass, iteritems) | |
74 | from IPython.utils.strdispatch import StrDispatch |
|
74 | from IPython.utils.strdispatch import StrDispatch | |
75 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
75 | from IPython.utils.syspathcontext import prepended_to_syspath | |
76 | from IPython.utils.text import (format_screen, LSString, SList, |
|
76 | from IPython.utils.text import (format_screen, LSString, SList, | |
77 | DollarFormatter) |
|
77 | DollarFormatter) | |
78 | from traitlets import ( |
|
78 | from traitlets import ( | |
79 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
79 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, | |
80 | observe, default, |
|
80 | observe, default, | |
81 | ) |
|
81 | ) | |
82 | from warnings import warn |
|
82 | from warnings import warn | |
83 | from logging import error |
|
83 | from logging import error | |
84 | import IPython.core.hooks |
|
84 | import IPython.core.hooks | |
85 |
|
85 | |||
|
86 | try: | |||
|
87 | import docrepr.sphinxify as sphx | |||
|
88 | ||||
|
89 | def docformat(doc): | |||
|
90 | dirname = tempfile.mkdtemp(prefix='ipython_sphinxify_') | |||
|
91 | return { | |||
|
92 | 'text/html': sphx.sphinxify(doc, dirname), | |||
|
93 | 'text/plain': doc | |||
|
94 | } | |||
|
95 | except: | |||
|
96 | docformat = None | |||
|
97 | ||||
86 | #----------------------------------------------------------------------------- |
|
98 | #----------------------------------------------------------------------------- | |
87 | # Globals |
|
99 | # Globals | |
88 | #----------------------------------------------------------------------------- |
|
100 | #----------------------------------------------------------------------------- | |
89 |
|
101 | |||
90 | # compiled regexps for autoindent management |
|
102 | # compiled regexps for autoindent management | |
91 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
103 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
92 |
|
104 | |||
93 | #----------------------------------------------------------------------------- |
|
105 | #----------------------------------------------------------------------------- | |
94 | # Utilities |
|
106 | # Utilities | |
95 | #----------------------------------------------------------------------------- |
|
107 | #----------------------------------------------------------------------------- | |
96 |
|
108 | |||
97 | @undoc |
|
109 | @undoc | |
98 | def softspace(file, newvalue): |
|
110 | def softspace(file, newvalue): | |
99 | """Copied from code.py, to remove the dependency""" |
|
111 | """Copied from code.py, to remove the dependency""" | |
100 |
|
112 | |||
101 | oldvalue = 0 |
|
113 | oldvalue = 0 | |
102 | try: |
|
114 | try: | |
103 | oldvalue = file.softspace |
|
115 | oldvalue = file.softspace | |
104 | except AttributeError: |
|
116 | except AttributeError: | |
105 | pass |
|
117 | pass | |
106 | try: |
|
118 | try: | |
107 | file.softspace = newvalue |
|
119 | file.softspace = newvalue | |
108 | except (AttributeError, TypeError): |
|
120 | except (AttributeError, TypeError): | |
109 | # "attribute-less object" or "read-only attributes" |
|
121 | # "attribute-less object" or "read-only attributes" | |
110 | pass |
|
122 | pass | |
111 | return oldvalue |
|
123 | return oldvalue | |
112 |
|
124 | |||
113 | @undoc |
|
125 | @undoc | |
114 | def no_op(*a, **kw): pass |
|
126 | def no_op(*a, **kw): pass | |
115 |
|
127 | |||
116 |
|
128 | |||
117 | class SpaceInInput(Exception): pass |
|
129 | class SpaceInInput(Exception): pass | |
118 |
|
130 | |||
119 |
|
131 | |||
120 | def get_default_colors(): |
|
132 | def get_default_colors(): | |
121 | if sys.platform=='darwin': |
|
133 | if sys.platform=='darwin': | |
122 | return "LightBG" |
|
134 | return "LightBG" | |
123 | elif os.name=='nt': |
|
135 | elif os.name=='nt': | |
124 | return 'Linux' |
|
136 | return 'Linux' | |
125 | else: |
|
137 | else: | |
126 | return 'Linux' |
|
138 | return 'Linux' | |
127 |
|
139 | |||
128 |
|
140 | |||
129 | class SeparateUnicode(Unicode): |
|
141 | class SeparateUnicode(Unicode): | |
130 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
142 | r"""A Unicode subclass to validate separate_in, separate_out, etc. | |
131 |
|
143 | |||
132 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
144 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. | |
133 | """ |
|
145 | """ | |
134 |
|
146 | |||
135 | def validate(self, obj, value): |
|
147 | def validate(self, obj, value): | |
136 | if value == '0': value = '' |
|
148 | if value == '0': value = '' | |
137 | value = value.replace('\\n','\n') |
|
149 | value = value.replace('\\n','\n') | |
138 | return super(SeparateUnicode, self).validate(obj, value) |
|
150 | return super(SeparateUnicode, self).validate(obj, value) | |
139 |
|
151 | |||
140 |
|
152 | |||
141 | @undoc |
|
153 | @undoc | |
142 | class DummyMod(object): |
|
154 | class DummyMod(object): | |
143 | """A dummy module used for IPython's interactive module when |
|
155 | """A dummy module used for IPython's interactive module when | |
144 | a namespace must be assigned to the module's __dict__.""" |
|
156 | a namespace must be assigned to the module's __dict__.""" | |
145 | pass |
|
157 | pass | |
146 |
|
158 | |||
147 |
|
159 | |||
148 | class ExecutionResult(object): |
|
160 | class ExecutionResult(object): | |
149 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
161 | """The result of a call to :meth:`InteractiveShell.run_cell` | |
150 |
|
162 | |||
151 | Stores information about what took place. |
|
163 | Stores information about what took place. | |
152 | """ |
|
164 | """ | |
153 | execution_count = None |
|
165 | execution_count = None | |
154 | error_before_exec = None |
|
166 | error_before_exec = None | |
155 | error_in_exec = None |
|
167 | error_in_exec = None | |
156 | result = None |
|
168 | result = None | |
157 |
|
169 | |||
158 | @property |
|
170 | @property | |
159 | def success(self): |
|
171 | def success(self): | |
160 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
172 | return (self.error_before_exec is None) and (self.error_in_exec is None) | |
161 |
|
173 | |||
162 | def raise_error(self): |
|
174 | def raise_error(self): | |
163 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
175 | """Reraises error if `success` is `False`, otherwise does nothing""" | |
164 | if self.error_before_exec is not None: |
|
176 | if self.error_before_exec is not None: | |
165 | raise self.error_before_exec |
|
177 | raise self.error_before_exec | |
166 | if self.error_in_exec is not None: |
|
178 | if self.error_in_exec is not None: | |
167 | raise self.error_in_exec |
|
179 | raise self.error_in_exec | |
168 |
|
180 | |||
169 | def __repr__(self): |
|
181 | def __repr__(self): | |
170 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ |
|
182 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ | |
171 | (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) |
|
183 | (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) | |
172 |
|
184 | |||
173 |
|
185 | |||
174 | class InteractiveShell(SingletonConfigurable): |
|
186 | class InteractiveShell(SingletonConfigurable): | |
175 | """An enhanced, interactive shell for Python.""" |
|
187 | """An enhanced, interactive shell for Python.""" | |
176 |
|
188 | |||
177 | _instance = None |
|
189 | _instance = None | |
178 |
|
190 | |||
179 | ast_transformers = List([], help= |
|
191 | ast_transformers = List([], help= | |
180 | """ |
|
192 | """ | |
181 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
193 | A list of ast.NodeTransformer subclass instances, which will be applied | |
182 | to user input before code is run. |
|
194 | to user input before code is run. | |
183 | """ |
|
195 | """ | |
184 | ).tag(config=True) |
|
196 | ).tag(config=True) | |
185 |
|
197 | |||
186 | autocall = Enum((0,1,2), default_value=0, help= |
|
198 | autocall = Enum((0,1,2), default_value=0, help= | |
187 | """ |
|
199 | """ | |
188 | Make IPython automatically call any callable object even if you didn't |
|
200 | Make IPython automatically call any callable object even if you didn't | |
189 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
201 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
190 | automatically. The value can be '0' to disable the feature, '1' for |
|
202 | automatically. The value can be '0' to disable the feature, '1' for | |
191 | 'smart' autocall, where it is not applied if there are no more |
|
203 | 'smart' autocall, where it is not applied if there are no more | |
192 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
204 | arguments on the line, and '2' for 'full' autocall, where all callable | |
193 | objects are automatically called (even if no arguments are present). |
|
205 | objects are automatically called (even if no arguments are present). | |
194 | """ |
|
206 | """ | |
195 | ).tag(config=True) |
|
207 | ).tag(config=True) | |
196 | # TODO: remove all autoindent logic and put into frontends. |
|
208 | # TODO: remove all autoindent logic and put into frontends. | |
197 | # We can't do this yet because even runlines uses the autoindent. |
|
209 | # We can't do this yet because even runlines uses the autoindent. | |
198 | autoindent = Bool(True, help= |
|
210 | autoindent = Bool(True, help= | |
199 | """ |
|
211 | """ | |
200 | Autoindent IPython code entered interactively. |
|
212 | Autoindent IPython code entered interactively. | |
201 | """ |
|
213 | """ | |
202 | ).tag(config=True) |
|
214 | ).tag(config=True) | |
203 | automagic = Bool(True, help= |
|
215 | automagic = Bool(True, help= | |
204 | """ |
|
216 | """ | |
205 | Enable magic commands to be called without the leading %. |
|
217 | Enable magic commands to be called without the leading %. | |
206 | """ |
|
218 | """ | |
207 | ).tag(config=True) |
|
219 | ).tag(config=True) | |
208 |
|
220 | |||
209 | banner1 = Unicode(default_banner, |
|
221 | banner1 = Unicode(default_banner, | |
210 | help="""The part of the banner to be printed before the profile""" |
|
222 | help="""The part of the banner to be printed before the profile""" | |
211 | ).tag(config=True) |
|
223 | ).tag(config=True) | |
212 | banner2 = Unicode('', |
|
224 | banner2 = Unicode('', | |
213 | help="""The part of the banner to be printed after the profile""" |
|
225 | help="""The part of the banner to be printed after the profile""" | |
214 | ).tag(config=True) |
|
226 | ).tag(config=True) | |
215 |
|
227 | |||
216 | cache_size = Integer(1000, help= |
|
228 | cache_size = Integer(1000, help= | |
217 | """ |
|
229 | """ | |
218 | Set the size of the output cache. The default is 1000, you can |
|
230 | Set the size of the output cache. The default is 1000, you can | |
219 | change it permanently in your config file. Setting it to 0 completely |
|
231 | change it permanently in your config file. Setting it to 0 completely | |
220 | disables the caching system, and the minimum value accepted is 20 (if |
|
232 | disables the caching system, and the minimum value accepted is 20 (if | |
221 | you provide a value less than 20, it is reset to 0 and a warning is |
|
233 | you provide a value less than 20, it is reset to 0 and a warning is | |
222 | issued). This limit is defined because otherwise you'll spend more |
|
234 | issued). This limit is defined because otherwise you'll spend more | |
223 | time re-flushing a too small cache than working |
|
235 | time re-flushing a too small cache than working | |
224 | """ |
|
236 | """ | |
225 | ).tag(config=True) |
|
237 | ).tag(config=True) | |
226 | color_info = Bool(True, help= |
|
238 | color_info = Bool(True, help= | |
227 | """ |
|
239 | """ | |
228 | Use colors for displaying information about objects. Because this |
|
240 | Use colors for displaying information about objects. Because this | |
229 | information is passed through a pager (like 'less'), and some pagers |
|
241 | information is passed through a pager (like 'less'), and some pagers | |
230 | get confused with color codes, this capability can be turned off. |
|
242 | get confused with color codes, this capability can be turned off. | |
231 | """ |
|
243 | """ | |
232 | ).tag(config=True) |
|
244 | ).tag(config=True) | |
233 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
245 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
234 | default_value=get_default_colors(), |
|
246 | default_value=get_default_colors(), | |
235 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
247 | help="Set the color scheme (NoColor, Linux, or LightBG)." | |
236 | ).tag(config=True) |
|
248 | ).tag(config=True) | |
237 | colors_force = Bool(False, help= |
|
249 | colors_force = Bool(False, help= | |
238 | """ |
|
250 | """ | |
239 | Force use of ANSI color codes, regardless of OS and readline |
|
251 | Force use of ANSI color codes, regardless of OS and readline | |
240 | availability. |
|
252 | availability. | |
241 | """ |
|
253 | """ | |
242 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
254 | # FIXME: This is essentially a hack to allow ZMQShell to show colors | |
243 | # without readline on Win32. When the ZMQ formatting system is |
|
255 | # without readline on Win32. When the ZMQ formatting system is | |
244 | # refactored, this should be removed. |
|
256 | # refactored, this should be removed. | |
245 | ) |
|
257 | ) | |
246 | debug = Bool(False).tag(config=True) |
|
258 | debug = Bool(False).tag(config=True) | |
247 | deep_reload = Bool(False, help= |
|
259 | deep_reload = Bool(False, help= | |
248 | """ |
|
260 | """ | |
249 | **Deprecated** |
|
261 | **Deprecated** | |
250 |
|
262 | |||
251 | Will be removed in IPython 6.0 |
|
263 | Will be removed in IPython 6.0 | |
252 |
|
264 | |||
253 | Enable deep (recursive) reloading by default. IPython can use the |
|
265 | Enable deep (recursive) reloading by default. IPython can use the | |
254 | deep_reload module which reloads changes in modules recursively (it |
|
266 | deep_reload module which reloads changes in modules recursively (it | |
255 | replaces the reload() function, so you don't need to change anything to |
|
267 | replaces the reload() function, so you don't need to change anything to | |
256 | use it). `deep_reload` forces a full reload of modules whose code may |
|
268 | use it). `deep_reload` forces a full reload of modules whose code may | |
257 | have changed, which the default reload() function does not. When |
|
269 | have changed, which the default reload() function does not. When | |
258 | deep_reload is off, IPython will use the normal reload(), but |
|
270 | deep_reload is off, IPython will use the normal reload(), but | |
259 | deep_reload will still be available as dreload(). |
|
271 | deep_reload will still be available as dreload(). | |
260 | """ |
|
272 | """ | |
261 | ).tag(config=True) |
|
273 | ).tag(config=True) | |
262 | disable_failing_post_execute = Bool(False, |
|
274 | disable_failing_post_execute = Bool(False, | |
263 | help="Don't call post-execute functions that have failed in the past." |
|
275 | help="Don't call post-execute functions that have failed in the past." | |
264 | ).tag(config=True) |
|
276 | ).tag(config=True) | |
265 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
277 | display_formatter = Instance(DisplayFormatter, allow_none=True) | |
266 | displayhook_class = Type(DisplayHook) |
|
278 | displayhook_class = Type(DisplayHook) | |
267 | display_pub_class = Type(DisplayPublisher) |
|
279 | display_pub_class = Type(DisplayPublisher) | |
268 | data_pub_class = None |
|
280 | data_pub_class = None | |
269 |
|
281 | |||
270 | exit_now = Bool(False) |
|
282 | exit_now = Bool(False) | |
271 | exiter = Instance(ExitAutocall) |
|
283 | exiter = Instance(ExitAutocall) | |
272 | @default('exiter') |
|
284 | @default('exiter') | |
273 | def _exiter_default(self): |
|
285 | def _exiter_default(self): | |
274 | return ExitAutocall(self) |
|
286 | return ExitAutocall(self) | |
275 | # Monotonically increasing execution counter |
|
287 | # Monotonically increasing execution counter | |
276 | execution_count = Integer(1) |
|
288 | execution_count = Integer(1) | |
277 | filename = Unicode("<ipython console>") |
|
289 | filename = Unicode("<ipython console>") | |
278 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
290 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ | |
279 |
|
291 | |||
280 | # Input splitter, to transform input line by line and detect when a block |
|
292 | # Input splitter, to transform input line by line and detect when a block | |
281 | # is ready to be executed. |
|
293 | # is ready to be executed. | |
282 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
294 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
283 | (), {'line_input_checker': True}) |
|
295 | (), {'line_input_checker': True}) | |
284 |
|
296 | |||
285 | # This InputSplitter instance is used to transform completed cells before |
|
297 | # This InputSplitter instance is used to transform completed cells before | |
286 | # running them. It allows cell magics to contain blank lines. |
|
298 | # running them. It allows cell magics to contain blank lines. | |
287 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
299 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
288 | (), {'line_input_checker': False}) |
|
300 | (), {'line_input_checker': False}) | |
289 |
|
301 | |||
290 | logstart = Bool(False, help= |
|
302 | logstart = Bool(False, help= | |
291 | """ |
|
303 | """ | |
292 | Start logging to the default log file in overwrite mode. |
|
304 | Start logging to the default log file in overwrite mode. | |
293 | Use `logappend` to specify a log file to **append** logs to. |
|
305 | Use `logappend` to specify a log file to **append** logs to. | |
294 | """ |
|
306 | """ | |
295 | ).tag(config=True) |
|
307 | ).tag(config=True) | |
296 | logfile = Unicode('', help= |
|
308 | logfile = Unicode('', help= | |
297 | """ |
|
309 | """ | |
298 | The name of the logfile to use. |
|
310 | The name of the logfile to use. | |
299 | """ |
|
311 | """ | |
300 | ).tag(config=True) |
|
312 | ).tag(config=True) | |
301 | logappend = Unicode('', help= |
|
313 | logappend = Unicode('', help= | |
302 | """ |
|
314 | """ | |
303 | Start logging to the given file in append mode. |
|
315 | Start logging to the given file in append mode. | |
304 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
316 | Use `logfile` to specify a log file to **overwrite** logs to. | |
305 | """ |
|
317 | """ | |
306 | ).tag(config=True) |
|
318 | ).tag(config=True) | |
307 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
319 | object_info_string_level = Enum((0,1,2), default_value=0, | |
308 | ).tag(config=True) |
|
320 | ).tag(config=True) | |
309 | pdb = Bool(False, help= |
|
321 | pdb = Bool(False, help= | |
310 | """ |
|
322 | """ | |
311 | Automatically call the pdb debugger after every exception. |
|
323 | Automatically call the pdb debugger after every exception. | |
312 | """ |
|
324 | """ | |
313 | ).tag(config=True) |
|
325 | ).tag(config=True) | |
314 | multiline_history = Bool(sys.platform != 'win32', |
|
326 | multiline_history = Bool(sys.platform != 'win32', | |
315 | help="Save multi-line entries as one entry in readline history" |
|
327 | help="Save multi-line entries as one entry in readline history" | |
316 | ).tag(config=True) |
|
328 | ).tag(config=True) | |
317 | display_page = Bool(False, |
|
329 | display_page = Bool(False, | |
318 | help="""If True, anything that would be passed to the pager |
|
330 | help="""If True, anything that would be passed to the pager | |
319 | will be displayed as regular output instead.""" |
|
331 | will be displayed as regular output instead.""" | |
320 | ).tag(config=True) |
|
332 | ).tag(config=True) | |
321 |
|
333 | |||
322 | # deprecated prompt traits: |
|
334 | # deprecated prompt traits: | |
323 |
|
335 | |||
324 | prompt_in1 = Unicode('In [\\#]: ', |
|
336 | prompt_in1 = Unicode('In [\\#]: ', | |
325 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." |
|
337 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." | |
326 | ).tag(config=True) |
|
338 | ).tag(config=True) | |
327 | prompt_in2 = Unicode(' .\\D.: ', |
|
339 | prompt_in2 = Unicode(' .\\D.: ', | |
328 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." |
|
340 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." | |
329 | ).tag(config=True) |
|
341 | ).tag(config=True) | |
330 | prompt_out = Unicode('Out[\\#]: ', |
|
342 | prompt_out = Unicode('Out[\\#]: ', | |
331 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." |
|
343 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." | |
332 | ).tag(config=True) |
|
344 | ).tag(config=True) | |
333 | prompts_pad_left = Bool(True, |
|
345 | prompts_pad_left = Bool(True, | |
334 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." |
|
346 | help="Deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly." | |
335 | ).tag(config=True) |
|
347 | ).tag(config=True) | |
336 |
|
348 | |||
337 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
349 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') | |
338 | def _prompt_trait_changed(self, change): |
|
350 | def _prompt_trait_changed(self, change): | |
339 | name = change['name'] |
|
351 | name = change['name'] | |
340 | warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly.".format( |
|
352 | warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set IPython.terminal.ptshell.TerminalInteractiveShell.prompts object directly.".format( | |
341 | name=name) |
|
353 | name=name) | |
342 | ) |
|
354 | ) | |
343 | # protect against weird cases where self.config may not exist: |
|
355 | # protect against weird cases where self.config may not exist: | |
344 |
|
356 | |||
345 | show_rewritten_input = Bool(True, |
|
357 | show_rewritten_input = Bool(True, | |
346 | help="Show rewritten input, e.g. for autocall." |
|
358 | help="Show rewritten input, e.g. for autocall." | |
347 | ).tag(config=True) |
|
359 | ).tag(config=True) | |
348 |
|
360 | |||
349 | quiet = Bool(False).tag(config=True) |
|
361 | quiet = Bool(False).tag(config=True) | |
350 |
|
362 | |||
351 | history_length = Integer(10000, |
|
363 | history_length = Integer(10000, | |
352 | help='Total length of command history' |
|
364 | help='Total length of command history' | |
353 | ).tag(config=True) |
|
365 | ).tag(config=True) | |
354 |
|
366 | |||
355 | history_load_length = Integer(1000, help= |
|
367 | history_load_length = Integer(1000, help= | |
356 | """ |
|
368 | """ | |
357 | The number of saved history entries to be loaded |
|
369 | The number of saved history entries to be loaded | |
358 | into the readline buffer at startup. |
|
370 | into the readline buffer at startup. | |
359 | """ |
|
371 | """ | |
360 | ).tag(config=True) |
|
372 | ).tag(config=True) | |
361 |
|
373 | |||
362 | # The readline stuff will eventually be moved to the terminal subclass |
|
374 | # The readline stuff will eventually be moved to the terminal subclass | |
363 | # but for now, we can't do that as readline is welded in everywhere. |
|
375 | # but for now, we can't do that as readline is welded in everywhere. | |
364 | readline_use = Bool(True).tag(config=True) |
|
376 | readline_use = Bool(True).tag(config=True) | |
365 | readline_remove_delims = Unicode('-/~').tag(config=True) |
|
377 | readline_remove_delims = Unicode('-/~').tag(config=True) | |
366 | readline_delims = Unicode() # set by init_readline() |
|
378 | readline_delims = Unicode() # set by init_readline() | |
367 | # don't use \M- bindings by default, because they |
|
379 | # don't use \M- bindings by default, because they | |
368 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
380 | # conflict with 8-bit encodings. See gh-58,gh-88 | |
369 | readline_parse_and_bind = List([ |
|
381 | readline_parse_and_bind = List([ | |
370 | 'tab: complete', |
|
382 | 'tab: complete', | |
371 | '"\C-l": clear-screen', |
|
383 | '"\C-l": clear-screen', | |
372 | 'set show-all-if-ambiguous on', |
|
384 | 'set show-all-if-ambiguous on', | |
373 | '"\C-o": tab-insert', |
|
385 | '"\C-o": tab-insert', | |
374 | '"\C-r": reverse-search-history', |
|
386 | '"\C-r": reverse-search-history', | |
375 | '"\C-s": forward-search-history', |
|
387 | '"\C-s": forward-search-history', | |
376 | '"\C-p": history-search-backward', |
|
388 | '"\C-p": history-search-backward', | |
377 | '"\C-n": history-search-forward', |
|
389 | '"\C-n": history-search-forward', | |
378 | '"\e[A": history-search-backward', |
|
390 | '"\e[A": history-search-backward', | |
379 | '"\e[B": history-search-forward', |
|
391 | '"\e[B": history-search-forward', | |
380 | '"\C-k": kill-line', |
|
392 | '"\C-k": kill-line', | |
381 | '"\C-u": unix-line-discard', |
|
393 | '"\C-u": unix-line-discard', | |
382 | ]).tag(config=True) |
|
394 | ]).tag(config=True) | |
383 |
|
395 | |||
384 | _custom_readline_config = False |
|
396 | _custom_readline_config = False | |
385 |
|
397 | |||
386 | @observe('readline_parse_and_bind') |
|
398 | @observe('readline_parse_and_bind') | |
387 | def _readline_parse_and_bind_changed(self, change): |
|
399 | def _readline_parse_and_bind_changed(self, change): | |
388 | # notice that readline config is customized |
|
400 | # notice that readline config is customized | |
389 | # indicates that it should have higher priority than inputrc |
|
401 | # indicates that it should have higher priority than inputrc | |
390 | self._custom_readline_config = True |
|
402 | self._custom_readline_config = True | |
391 |
|
403 | |||
392 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
404 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], | |
393 | default_value='last_expr', |
|
405 | default_value='last_expr', | |
394 | help=""" |
|
406 | help=""" | |
395 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
407 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
396 | run interactively (displaying output from expressions).""" |
|
408 | run interactively (displaying output from expressions).""" | |
397 | ).tag(config=True) |
|
409 | ).tag(config=True) | |
398 |
|
410 | |||
399 | # TODO: this part of prompt management should be moved to the frontends. |
|
411 | # TODO: this part of prompt management should be moved to the frontends. | |
400 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
412 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
401 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
413 | separate_in = SeparateUnicode('\n').tag(config=True) | |
402 | separate_out = SeparateUnicode('').tag(config=True) |
|
414 | separate_out = SeparateUnicode('').tag(config=True) | |
403 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
415 | separate_out2 = SeparateUnicode('').tag(config=True) | |
404 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
416 | wildcards_case_sensitive = Bool(True).tag(config=True) | |
405 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
417 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
406 | default_value='Context').tag(config=True) |
|
418 | default_value='Context').tag(config=True) | |
407 |
|
419 | |||
408 | # Subcomponents of InteractiveShell |
|
420 | # Subcomponents of InteractiveShell | |
409 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
421 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) | |
410 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
422 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) | |
411 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
423 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) | |
412 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
424 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) | |
413 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
425 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) | |
414 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
426 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) | |
415 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
427 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) | |
416 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
428 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) | |
417 |
|
429 | |||
418 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
430 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) | |
419 | @property |
|
431 | @property | |
420 | def profile(self): |
|
432 | def profile(self): | |
421 | if self.profile_dir is not None: |
|
433 | if self.profile_dir is not None: | |
422 | name = os.path.basename(self.profile_dir.location) |
|
434 | name = os.path.basename(self.profile_dir.location) | |
423 | return name.replace('profile_','') |
|
435 | return name.replace('profile_','') | |
424 |
|
436 | |||
425 |
|
437 | |||
426 | # Private interface |
|
438 | # Private interface | |
427 | _post_execute = Dict() |
|
439 | _post_execute = Dict() | |
428 |
|
440 | |||
429 | # Tracks any GUI loop loaded for pylab |
|
441 | # Tracks any GUI loop loaded for pylab | |
430 | pylab_gui_select = None |
|
442 | pylab_gui_select = None | |
431 |
|
443 | |||
432 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
444 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') | |
433 |
|
445 | |||
434 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
446 | def __init__(self, ipython_dir=None, profile_dir=None, | |
435 | user_module=None, user_ns=None, |
|
447 | user_module=None, user_ns=None, | |
436 | custom_exceptions=((), None), **kwargs): |
|
448 | custom_exceptions=((), None), **kwargs): | |
437 |
|
449 | |||
438 | # This is where traits with a config_key argument are updated |
|
450 | # This is where traits with a config_key argument are updated | |
439 | # from the values on config. |
|
451 | # from the values on config. | |
440 | super(InteractiveShell, self).__init__(**kwargs) |
|
452 | super(InteractiveShell, self).__init__(**kwargs) | |
441 | if 'PromptManager' in self.config: |
|
453 | if 'PromptManager' in self.config: | |
442 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
454 | warn('As of IPython 5.0 `PromptManager` config will have no effect' | |
443 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
455 | ' and has been replaced by TerminalInteractiveShell.prompts_class') | |
444 | self.configurables = [self] |
|
456 | self.configurables = [self] | |
445 |
|
457 | |||
446 | # These are relatively independent and stateless |
|
458 | # These are relatively independent and stateless | |
447 | self.init_ipython_dir(ipython_dir) |
|
459 | self.init_ipython_dir(ipython_dir) | |
448 | self.init_profile_dir(profile_dir) |
|
460 | self.init_profile_dir(profile_dir) | |
449 | self.init_instance_attrs() |
|
461 | self.init_instance_attrs() | |
450 | self.init_environment() |
|
462 | self.init_environment() | |
451 |
|
463 | |||
452 | # Check if we're in a virtualenv, and set up sys.path. |
|
464 | # Check if we're in a virtualenv, and set up sys.path. | |
453 | self.init_virtualenv() |
|
465 | self.init_virtualenv() | |
454 |
|
466 | |||
455 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
467 | # Create namespaces (user_ns, user_global_ns, etc.) | |
456 | self.init_create_namespaces(user_module, user_ns) |
|
468 | self.init_create_namespaces(user_module, user_ns) | |
457 | # This has to be done after init_create_namespaces because it uses |
|
469 | # This has to be done after init_create_namespaces because it uses | |
458 | # something in self.user_ns, but before init_sys_modules, which |
|
470 | # something in self.user_ns, but before init_sys_modules, which | |
459 | # is the first thing to modify sys. |
|
471 | # is the first thing to modify sys. | |
460 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
472 | # TODO: When we override sys.stdout and sys.stderr before this class | |
461 | # is created, we are saving the overridden ones here. Not sure if this |
|
473 | # is created, we are saving the overridden ones here. Not sure if this | |
462 | # is what we want to do. |
|
474 | # is what we want to do. | |
463 | self.save_sys_module_state() |
|
475 | self.save_sys_module_state() | |
464 | self.init_sys_modules() |
|
476 | self.init_sys_modules() | |
465 |
|
477 | |||
466 | # While we're trying to have each part of the code directly access what |
|
478 | # While we're trying to have each part of the code directly access what | |
467 | # it needs without keeping redundant references to objects, we have too |
|
479 | # it needs without keeping redundant references to objects, we have too | |
468 | # much legacy code that expects ip.db to exist. |
|
480 | # much legacy code that expects ip.db to exist. | |
469 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
481 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
470 |
|
482 | |||
471 | self.init_history() |
|
483 | self.init_history() | |
472 | self.init_encoding() |
|
484 | self.init_encoding() | |
473 | self.init_prefilter() |
|
485 | self.init_prefilter() | |
474 |
|
486 | |||
475 | self.init_syntax_highlighting() |
|
487 | self.init_syntax_highlighting() | |
476 | self.init_hooks() |
|
488 | self.init_hooks() | |
477 | self.init_events() |
|
489 | self.init_events() | |
478 | self.init_pushd_popd_magic() |
|
490 | self.init_pushd_popd_magic() | |
479 | # self.init_traceback_handlers use to be here, but we moved it below |
|
491 | # self.init_traceback_handlers use to be here, but we moved it below | |
480 | # because it and init_io have to come after init_readline. |
|
492 | # because it and init_io have to come after init_readline. | |
481 | self.init_user_ns() |
|
493 | self.init_user_ns() | |
482 | self.init_logger() |
|
494 | self.init_logger() | |
483 | self.init_builtins() |
|
495 | self.init_builtins() | |
484 |
|
496 | |||
485 | # The following was in post_config_initialization |
|
497 | # The following was in post_config_initialization | |
486 | self.init_inspector() |
|
498 | self.init_inspector() | |
487 | # init_readline() must come before init_io(), because init_io uses |
|
499 | # init_readline() must come before init_io(), because init_io uses | |
488 | # readline related things. |
|
500 | # readline related things. | |
489 | self.init_readline() |
|
501 | self.init_readline() | |
490 | # We save this here in case user code replaces raw_input, but it needs |
|
502 | # We save this here in case user code replaces raw_input, but it needs | |
491 | # to be after init_readline(), because PyPy's readline works by replacing |
|
503 | # to be after init_readline(), because PyPy's readline works by replacing | |
492 | # raw_input. |
|
504 | # raw_input. | |
493 | if py3compat.PY3: |
|
505 | if py3compat.PY3: | |
494 | self.raw_input_original = input |
|
506 | self.raw_input_original = input | |
495 | else: |
|
507 | else: | |
496 | self.raw_input_original = raw_input |
|
508 | self.raw_input_original = raw_input | |
497 | # init_completer must come after init_readline, because it needs to |
|
509 | # init_completer must come after init_readline, because it needs to | |
498 | # know whether readline is present or not system-wide to configure the |
|
510 | # know whether readline is present or not system-wide to configure the | |
499 | # completers, since the completion machinery can now operate |
|
511 | # completers, since the completion machinery can now operate | |
500 | # independently of readline (e.g. over the network) |
|
512 | # independently of readline (e.g. over the network) | |
501 | self.init_completer() |
|
513 | self.init_completer() | |
502 | # TODO: init_io() needs to happen before init_traceback handlers |
|
514 | # TODO: init_io() needs to happen before init_traceback handlers | |
503 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
515 | # because the traceback handlers hardcode the stdout/stderr streams. | |
504 | # This logic in in debugger.Pdb and should eventually be changed. |
|
516 | # This logic in in debugger.Pdb and should eventually be changed. | |
505 | self.init_io() |
|
517 | self.init_io() | |
506 | self.init_traceback_handlers(custom_exceptions) |
|
518 | self.init_traceback_handlers(custom_exceptions) | |
507 | self.init_prompts() |
|
519 | self.init_prompts() | |
508 | self.init_display_formatter() |
|
520 | self.init_display_formatter() | |
509 | self.init_display_pub() |
|
521 | self.init_display_pub() | |
510 | self.init_data_pub() |
|
522 | self.init_data_pub() | |
511 | self.init_displayhook() |
|
523 | self.init_displayhook() | |
512 | self.init_magics() |
|
524 | self.init_magics() | |
513 | self.init_alias() |
|
525 | self.init_alias() | |
514 | self.init_logstart() |
|
526 | self.init_logstart() | |
515 | self.init_pdb() |
|
527 | self.init_pdb() | |
516 | self.init_extension_manager() |
|
528 | self.init_extension_manager() | |
517 | self.init_payload() |
|
529 | self.init_payload() | |
518 | self.init_deprecation_warnings() |
|
530 | self.init_deprecation_warnings() | |
519 | self.hooks.late_startup_hook() |
|
531 | self.hooks.late_startup_hook() | |
520 | self.events.trigger('shell_initialized', self) |
|
532 | self.events.trigger('shell_initialized', self) | |
521 | atexit.register(self.atexit_operations) |
|
533 | atexit.register(self.atexit_operations) | |
522 |
|
534 | |||
523 | def get_ipython(self): |
|
535 | def get_ipython(self): | |
524 | """Return the currently running IPython instance.""" |
|
536 | """Return the currently running IPython instance.""" | |
525 | return self |
|
537 | return self | |
526 |
|
538 | |||
527 | #------------------------------------------------------------------------- |
|
539 | #------------------------------------------------------------------------- | |
528 | # Trait changed handlers |
|
540 | # Trait changed handlers | |
529 | #------------------------------------------------------------------------- |
|
541 | #------------------------------------------------------------------------- | |
530 | @observe('ipython_dir') |
|
542 | @observe('ipython_dir') | |
531 | def _ipython_dir_changed(self, change): |
|
543 | def _ipython_dir_changed(self, change): | |
532 | ensure_dir_exists(change['new']) |
|
544 | ensure_dir_exists(change['new']) | |
533 |
|
545 | |||
534 | def set_autoindent(self,value=None): |
|
546 | def set_autoindent(self,value=None): | |
535 | """Set the autoindent flag. |
|
547 | """Set the autoindent flag. | |
536 |
|
548 | |||
537 | If called with no arguments, it acts as a toggle.""" |
|
549 | If called with no arguments, it acts as a toggle.""" | |
538 | if value is None: |
|
550 | if value is None: | |
539 | self.autoindent = not self.autoindent |
|
551 | self.autoindent = not self.autoindent | |
540 | else: |
|
552 | else: | |
541 | self.autoindent = value |
|
553 | self.autoindent = value | |
542 |
|
554 | |||
543 | #------------------------------------------------------------------------- |
|
555 | #------------------------------------------------------------------------- | |
544 | # init_* methods called by __init__ |
|
556 | # init_* methods called by __init__ | |
545 | #------------------------------------------------------------------------- |
|
557 | #------------------------------------------------------------------------- | |
546 |
|
558 | |||
547 | def init_ipython_dir(self, ipython_dir): |
|
559 | def init_ipython_dir(self, ipython_dir): | |
548 | if ipython_dir is not None: |
|
560 | if ipython_dir is not None: | |
549 | self.ipython_dir = ipython_dir |
|
561 | self.ipython_dir = ipython_dir | |
550 | return |
|
562 | return | |
551 |
|
563 | |||
552 | self.ipython_dir = get_ipython_dir() |
|
564 | self.ipython_dir = get_ipython_dir() | |
553 |
|
565 | |||
554 | def init_profile_dir(self, profile_dir): |
|
566 | def init_profile_dir(self, profile_dir): | |
555 | if profile_dir is not None: |
|
567 | if profile_dir is not None: | |
556 | self.profile_dir = profile_dir |
|
568 | self.profile_dir = profile_dir | |
557 | return |
|
569 | return | |
558 | self.profile_dir =\ |
|
570 | self.profile_dir =\ | |
559 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
571 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
560 |
|
572 | |||
561 | def init_instance_attrs(self): |
|
573 | def init_instance_attrs(self): | |
562 | self.more = False |
|
574 | self.more = False | |
563 |
|
575 | |||
564 | # command compiler |
|
576 | # command compiler | |
565 | self.compile = CachingCompiler() |
|
577 | self.compile = CachingCompiler() | |
566 |
|
578 | |||
567 | # Make an empty namespace, which extension writers can rely on both |
|
579 | # Make an empty namespace, which extension writers can rely on both | |
568 | # existing and NEVER being used by ipython itself. This gives them a |
|
580 | # existing and NEVER being used by ipython itself. This gives them a | |
569 | # convenient location for storing additional information and state |
|
581 | # convenient location for storing additional information and state | |
570 | # their extensions may require, without fear of collisions with other |
|
582 | # their extensions may require, without fear of collisions with other | |
571 | # ipython names that may develop later. |
|
583 | # ipython names that may develop later. | |
572 | self.meta = Struct() |
|
584 | self.meta = Struct() | |
573 |
|
585 | |||
574 | # Temporary files used for various purposes. Deleted at exit. |
|
586 | # Temporary files used for various purposes. Deleted at exit. | |
575 | self.tempfiles = [] |
|
587 | self.tempfiles = [] | |
576 | self.tempdirs = [] |
|
588 | self.tempdirs = [] | |
577 |
|
589 | |||
578 | # Keep track of readline usage (later set by init_readline) |
|
590 | # Keep track of readline usage (later set by init_readline) | |
579 | self.has_readline = False |
|
591 | self.has_readline = False | |
580 |
|
592 | |||
581 | # keep track of where we started running (mainly for crash post-mortem) |
|
593 | # keep track of where we started running (mainly for crash post-mortem) | |
582 | # This is not being used anywhere currently. |
|
594 | # This is not being used anywhere currently. | |
583 | self.starting_dir = py3compat.getcwd() |
|
595 | self.starting_dir = py3compat.getcwd() | |
584 |
|
596 | |||
585 | # Indentation management |
|
597 | # Indentation management | |
586 | self.indent_current_nsp = 0 |
|
598 | self.indent_current_nsp = 0 | |
587 |
|
599 | |||
588 | # Dict to track post-execution functions that have been registered |
|
600 | # Dict to track post-execution functions that have been registered | |
589 | self._post_execute = {} |
|
601 | self._post_execute = {} | |
590 |
|
602 | |||
591 | def init_environment(self): |
|
603 | def init_environment(self): | |
592 | """Any changes we need to make to the user's environment.""" |
|
604 | """Any changes we need to make to the user's environment.""" | |
593 | pass |
|
605 | pass | |
594 |
|
606 | |||
595 | def init_encoding(self): |
|
607 | def init_encoding(self): | |
596 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
608 | # Get system encoding at startup time. Certain terminals (like Emacs | |
597 | # under Win32 have it set to None, and we need to have a known valid |
|
609 | # under Win32 have it set to None, and we need to have a known valid | |
598 | # encoding to use in the raw_input() method |
|
610 | # encoding to use in the raw_input() method | |
599 | try: |
|
611 | try: | |
600 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
612 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
601 | except AttributeError: |
|
613 | except AttributeError: | |
602 | self.stdin_encoding = 'ascii' |
|
614 | self.stdin_encoding = 'ascii' | |
603 |
|
615 | |||
604 | def init_syntax_highlighting(self): |
|
616 | def init_syntax_highlighting(self): | |
605 | # Python source parser/formatter for syntax highlighting |
|
617 | # Python source parser/formatter for syntax highlighting | |
606 | pyformat = PyColorize.Parser().format |
|
618 | pyformat = PyColorize.Parser().format | |
607 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
619 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
608 |
|
620 | |||
609 | def init_pushd_popd_magic(self): |
|
621 | def init_pushd_popd_magic(self): | |
610 | # for pushd/popd management |
|
622 | # for pushd/popd management | |
611 | self.home_dir = get_home_dir() |
|
623 | self.home_dir = get_home_dir() | |
612 |
|
624 | |||
613 | self.dir_stack = [] |
|
625 | self.dir_stack = [] | |
614 |
|
626 | |||
615 | def init_logger(self): |
|
627 | def init_logger(self): | |
616 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
628 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
617 | logmode='rotate') |
|
629 | logmode='rotate') | |
618 |
|
630 | |||
619 | def init_logstart(self): |
|
631 | def init_logstart(self): | |
620 | """Initialize logging in case it was requested at the command line. |
|
632 | """Initialize logging in case it was requested at the command line. | |
621 | """ |
|
633 | """ | |
622 | if self.logappend: |
|
634 | if self.logappend: | |
623 | self.magic('logstart %s append' % self.logappend) |
|
635 | self.magic('logstart %s append' % self.logappend) | |
624 | elif self.logfile: |
|
636 | elif self.logfile: | |
625 | self.magic('logstart %s' % self.logfile) |
|
637 | self.magic('logstart %s' % self.logfile) | |
626 | elif self.logstart: |
|
638 | elif self.logstart: | |
627 | self.magic('logstart') |
|
639 | self.magic('logstart') | |
628 |
|
640 | |||
629 | def init_deprecation_warnings(self): |
|
641 | def init_deprecation_warnings(self): | |
630 | """ |
|
642 | """ | |
631 | register default filter for deprecation warning. |
|
643 | register default filter for deprecation warning. | |
632 |
|
644 | |||
633 | This will allow deprecation warning of function used interactively to show |
|
645 | This will allow deprecation warning of function used interactively to show | |
634 | warning to users, and still hide deprecation warning from libraries import. |
|
646 | warning to users, and still hide deprecation warning from libraries import. | |
635 | """ |
|
647 | """ | |
636 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
648 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) | |
637 |
|
649 | |||
638 | def init_builtins(self): |
|
650 | def init_builtins(self): | |
639 | # A single, static flag that we set to True. Its presence indicates |
|
651 | # A single, static flag that we set to True. Its presence indicates | |
640 | # that an IPython shell has been created, and we make no attempts at |
|
652 | # that an IPython shell has been created, and we make no attempts at | |
641 | # removing on exit or representing the existence of more than one |
|
653 | # removing on exit or representing the existence of more than one | |
642 | # IPython at a time. |
|
654 | # IPython at a time. | |
643 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
655 | builtin_mod.__dict__['__IPYTHON__'] = True | |
644 |
|
656 | |||
645 | self.builtin_trap = BuiltinTrap(shell=self) |
|
657 | self.builtin_trap = BuiltinTrap(shell=self) | |
646 |
|
658 | |||
647 | def init_inspector(self): |
|
659 | def init_inspector(self): | |
648 | # Object inspector |
|
660 | # Object inspector | |
649 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
661 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
650 | PyColorize.ANSICodeColors, |
|
662 | PyColorize.ANSICodeColors, | |
651 | 'NoColor', |
|
663 | 'NoColor', | |
652 | self.object_info_string_level) |
|
664 | self.object_info_string_level) | |
653 |
|
665 | |||
654 | def init_io(self): |
|
666 | def init_io(self): | |
655 | # This will just use sys.stdout and sys.stderr. If you want to |
|
667 | # This will just use sys.stdout and sys.stderr. If you want to | |
656 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
668 | # override sys.stdout and sys.stderr themselves, you need to do that | |
657 | # *before* instantiating this class, because io holds onto |
|
669 | # *before* instantiating this class, because io holds onto | |
658 | # references to the underlying streams. |
|
670 | # references to the underlying streams. | |
659 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
671 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: | |
660 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
672 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) | |
661 | else: |
|
673 | else: | |
662 | io.stdout = io.IOStream(sys.stdout) |
|
674 | io.stdout = io.IOStream(sys.stdout) | |
663 | io.stderr = io.IOStream(sys.stderr) |
|
675 | io.stderr = io.IOStream(sys.stderr) | |
664 |
|
676 | |||
665 | def init_prompts(self): |
|
677 | def init_prompts(self): | |
666 | # Set system prompts, so that scripts can decide if they are running |
|
678 | # Set system prompts, so that scripts can decide if they are running | |
667 | # interactively. |
|
679 | # interactively. | |
668 | sys.ps1 = 'In : ' |
|
680 | sys.ps1 = 'In : ' | |
669 | sys.ps2 = '...: ' |
|
681 | sys.ps2 = '...: ' | |
670 | sys.ps3 = 'Out: ' |
|
682 | sys.ps3 = 'Out: ' | |
671 |
|
683 | |||
672 | def init_display_formatter(self): |
|
684 | def init_display_formatter(self): | |
673 | self.display_formatter = DisplayFormatter(parent=self) |
|
685 | self.display_formatter = DisplayFormatter(parent=self) | |
674 | self.configurables.append(self.display_formatter) |
|
686 | self.configurables.append(self.display_formatter) | |
675 |
|
687 | |||
676 | def init_display_pub(self): |
|
688 | def init_display_pub(self): | |
677 | self.display_pub = self.display_pub_class(parent=self) |
|
689 | self.display_pub = self.display_pub_class(parent=self) | |
678 | self.configurables.append(self.display_pub) |
|
690 | self.configurables.append(self.display_pub) | |
679 |
|
691 | |||
680 | def init_data_pub(self): |
|
692 | def init_data_pub(self): | |
681 | if not self.data_pub_class: |
|
693 | if not self.data_pub_class: | |
682 | self.data_pub = None |
|
694 | self.data_pub = None | |
683 | return |
|
695 | return | |
684 | self.data_pub = self.data_pub_class(parent=self) |
|
696 | self.data_pub = self.data_pub_class(parent=self) | |
685 | self.configurables.append(self.data_pub) |
|
697 | self.configurables.append(self.data_pub) | |
686 |
|
698 | |||
687 | def init_displayhook(self): |
|
699 | def init_displayhook(self): | |
688 | # Initialize displayhook, set in/out prompts and printing system |
|
700 | # Initialize displayhook, set in/out prompts and printing system | |
689 | self.displayhook = self.displayhook_class( |
|
701 | self.displayhook = self.displayhook_class( | |
690 | parent=self, |
|
702 | parent=self, | |
691 | shell=self, |
|
703 | shell=self, | |
692 | cache_size=self.cache_size, |
|
704 | cache_size=self.cache_size, | |
693 | ) |
|
705 | ) | |
694 | self.configurables.append(self.displayhook) |
|
706 | self.configurables.append(self.displayhook) | |
695 | # This is a context manager that installs/revmoes the displayhook at |
|
707 | # This is a context manager that installs/revmoes the displayhook at | |
696 | # the appropriate time. |
|
708 | # the appropriate time. | |
697 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
709 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
698 |
|
710 | |||
699 | def init_virtualenv(self): |
|
711 | def init_virtualenv(self): | |
700 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
712 | """Add a virtualenv to sys.path so the user can import modules from it. | |
701 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
713 | This isn't perfect: it doesn't use the Python interpreter with which the | |
702 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
714 | virtualenv was built, and it ignores the --no-site-packages option. A | |
703 | warning will appear suggesting the user installs IPython in the |
|
715 | warning will appear suggesting the user installs IPython in the | |
704 | virtualenv, but for many cases, it probably works well enough. |
|
716 | virtualenv, but for many cases, it probably works well enough. | |
705 |
|
717 | |||
706 | Adapted from code snippets online. |
|
718 | Adapted from code snippets online. | |
707 |
|
719 | |||
708 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
720 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv | |
709 | """ |
|
721 | """ | |
710 | if 'VIRTUAL_ENV' not in os.environ: |
|
722 | if 'VIRTUAL_ENV' not in os.environ: | |
711 | # Not in a virtualenv |
|
723 | # Not in a virtualenv | |
712 | return |
|
724 | return | |
713 |
|
725 | |||
714 | # venv detection: |
|
726 | # venv detection: | |
715 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
727 | # stdlib venv may symlink sys.executable, so we can't use realpath. | |
716 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
728 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. | |
717 | # So we just check every item in the symlink tree (generally <= 3) |
|
729 | # So we just check every item in the symlink tree (generally <= 3) | |
718 | p = os.path.normcase(sys.executable) |
|
730 | p = os.path.normcase(sys.executable) | |
719 | paths = [p] |
|
731 | paths = [p] | |
720 | while os.path.islink(p): |
|
732 | while os.path.islink(p): | |
721 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
733 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) | |
722 | paths.append(p) |
|
734 | paths.append(p) | |
723 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
735 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) | |
724 | if any(p.startswith(p_venv) for p in paths): |
|
736 | if any(p.startswith(p_venv) for p in paths): | |
725 | # Running properly in the virtualenv, don't need to do anything |
|
737 | # Running properly in the virtualenv, don't need to do anything | |
726 | return |
|
738 | return | |
727 |
|
739 | |||
728 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
740 | warn("Attempting to work in a virtualenv. If you encounter problems, please " | |
729 | "install IPython inside the virtualenv.") |
|
741 | "install IPython inside the virtualenv.") | |
730 | if sys.platform == "win32": |
|
742 | if sys.platform == "win32": | |
731 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
743 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') | |
732 | else: |
|
744 | else: | |
733 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
745 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', | |
734 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
746 | 'python%d.%d' % sys.version_info[:2], 'site-packages') | |
735 |
|
747 | |||
736 | import site |
|
748 | import site | |
737 | sys.path.insert(0, virtual_env) |
|
749 | sys.path.insert(0, virtual_env) | |
738 | site.addsitedir(virtual_env) |
|
750 | site.addsitedir(virtual_env) | |
739 |
|
751 | |||
740 | #------------------------------------------------------------------------- |
|
752 | #------------------------------------------------------------------------- | |
741 | # Things related to injections into the sys module |
|
753 | # Things related to injections into the sys module | |
742 | #------------------------------------------------------------------------- |
|
754 | #------------------------------------------------------------------------- | |
743 |
|
755 | |||
744 | def save_sys_module_state(self): |
|
756 | def save_sys_module_state(self): | |
745 | """Save the state of hooks in the sys module. |
|
757 | """Save the state of hooks in the sys module. | |
746 |
|
758 | |||
747 | This has to be called after self.user_module is created. |
|
759 | This has to be called after self.user_module is created. | |
748 | """ |
|
760 | """ | |
749 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
761 | self._orig_sys_module_state = {'stdin': sys.stdin, | |
750 | 'stdout': sys.stdout, |
|
762 | 'stdout': sys.stdout, | |
751 | 'stderr': sys.stderr, |
|
763 | 'stderr': sys.stderr, | |
752 | 'excepthook': sys.excepthook} |
|
764 | 'excepthook': sys.excepthook} | |
753 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
765 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
754 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
766 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) | |
755 |
|
767 | |||
756 | def restore_sys_module_state(self): |
|
768 | def restore_sys_module_state(self): | |
757 | """Restore the state of the sys module.""" |
|
769 | """Restore the state of the sys module.""" | |
758 | try: |
|
770 | try: | |
759 | for k, v in iteritems(self._orig_sys_module_state): |
|
771 | for k, v in iteritems(self._orig_sys_module_state): | |
760 | setattr(sys, k, v) |
|
772 | setattr(sys, k, v) | |
761 | except AttributeError: |
|
773 | except AttributeError: | |
762 | pass |
|
774 | pass | |
763 | # Reset what what done in self.init_sys_modules |
|
775 | # Reset what what done in self.init_sys_modules | |
764 | if self._orig_sys_modules_main_mod is not None: |
|
776 | if self._orig_sys_modules_main_mod is not None: | |
765 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
777 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | |
766 |
|
778 | |||
767 | #------------------------------------------------------------------------- |
|
779 | #------------------------------------------------------------------------- | |
768 | # Things related to the banner |
|
780 | # Things related to the banner | |
769 | #------------------------------------------------------------------------- |
|
781 | #------------------------------------------------------------------------- | |
770 |
|
782 | |||
771 | @property |
|
783 | @property | |
772 | def banner(self): |
|
784 | def banner(self): | |
773 | banner = self.banner1 |
|
785 | banner = self.banner1 | |
774 | if self.profile and self.profile != 'default': |
|
786 | if self.profile and self.profile != 'default': | |
775 | banner += '\nIPython profile: %s\n' % self.profile |
|
787 | banner += '\nIPython profile: %s\n' % self.profile | |
776 | if self.banner2: |
|
788 | if self.banner2: | |
777 | banner += '\n' + self.banner2 |
|
789 | banner += '\n' + self.banner2 | |
778 | return banner |
|
790 | return banner | |
779 |
|
791 | |||
780 | def show_banner(self, banner=None): |
|
792 | def show_banner(self, banner=None): | |
781 | if banner is None: |
|
793 | if banner is None: | |
782 | banner = self.banner |
|
794 | banner = self.banner | |
783 | sys.stdout.write(banner) |
|
795 | sys.stdout.write(banner) | |
784 |
|
796 | |||
785 | #------------------------------------------------------------------------- |
|
797 | #------------------------------------------------------------------------- | |
786 | # Things related to hooks |
|
798 | # Things related to hooks | |
787 | #------------------------------------------------------------------------- |
|
799 | #------------------------------------------------------------------------- | |
788 |
|
800 | |||
789 | def init_hooks(self): |
|
801 | def init_hooks(self): | |
790 | # hooks holds pointers used for user-side customizations |
|
802 | # hooks holds pointers used for user-side customizations | |
791 | self.hooks = Struct() |
|
803 | self.hooks = Struct() | |
792 |
|
804 | |||
793 | self.strdispatchers = {} |
|
805 | self.strdispatchers = {} | |
794 |
|
806 | |||
795 | # Set all default hooks, defined in the IPython.hooks module. |
|
807 | # Set all default hooks, defined in the IPython.hooks module. | |
796 | hooks = IPython.core.hooks |
|
808 | hooks = IPython.core.hooks | |
797 | for hook_name in hooks.__all__: |
|
809 | for hook_name in hooks.__all__: | |
798 | # default hooks have priority 100, i.e. low; user hooks should have |
|
810 | # default hooks have priority 100, i.e. low; user hooks should have | |
799 | # 0-100 priority |
|
811 | # 0-100 priority | |
800 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
812 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) | |
801 |
|
813 | |||
802 | if self.display_page: |
|
814 | if self.display_page: | |
803 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
815 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) | |
804 |
|
816 | |||
805 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
817 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, | |
806 | _warn_deprecated=True): |
|
818 | _warn_deprecated=True): | |
807 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
819 | """set_hook(name,hook) -> sets an internal IPython hook. | |
808 |
|
820 | |||
809 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
821 | IPython exposes some of its internal API as user-modifiable hooks. By | |
810 | adding your function to one of these hooks, you can modify IPython's |
|
822 | adding your function to one of these hooks, you can modify IPython's | |
811 | behavior to call at runtime your own routines.""" |
|
823 | behavior to call at runtime your own routines.""" | |
812 |
|
824 | |||
813 | # At some point in the future, this should validate the hook before it |
|
825 | # At some point in the future, this should validate the hook before it | |
814 | # accepts it. Probably at least check that the hook takes the number |
|
826 | # accepts it. Probably at least check that the hook takes the number | |
815 | # of args it's supposed to. |
|
827 | # of args it's supposed to. | |
816 |
|
828 | |||
817 | f = types.MethodType(hook,self) |
|
829 | f = types.MethodType(hook,self) | |
818 |
|
830 | |||
819 | # check if the hook is for strdispatcher first |
|
831 | # check if the hook is for strdispatcher first | |
820 | if str_key is not None: |
|
832 | if str_key is not None: | |
821 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
833 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
822 | sdp.add_s(str_key, f, priority ) |
|
834 | sdp.add_s(str_key, f, priority ) | |
823 | self.strdispatchers[name] = sdp |
|
835 | self.strdispatchers[name] = sdp | |
824 | return |
|
836 | return | |
825 | if re_key is not None: |
|
837 | if re_key is not None: | |
826 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
838 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
827 | sdp.add_re(re.compile(re_key), f, priority ) |
|
839 | sdp.add_re(re.compile(re_key), f, priority ) | |
828 | self.strdispatchers[name] = sdp |
|
840 | self.strdispatchers[name] = sdp | |
829 | return |
|
841 | return | |
830 |
|
842 | |||
831 | dp = getattr(self.hooks, name, None) |
|
843 | dp = getattr(self.hooks, name, None) | |
832 | if name not in IPython.core.hooks.__all__: |
|
844 | if name not in IPython.core.hooks.__all__: | |
833 | print("Warning! Hook '%s' is not one of %s" % \ |
|
845 | print("Warning! Hook '%s' is not one of %s" % \ | |
834 | (name, IPython.core.hooks.__all__ )) |
|
846 | (name, IPython.core.hooks.__all__ )) | |
835 |
|
847 | |||
836 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
848 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): | |
837 | alternative = IPython.core.hooks.deprecated[name] |
|
849 | alternative = IPython.core.hooks.deprecated[name] | |
838 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative)) |
|
850 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative)) | |
839 |
|
851 | |||
840 | if not dp: |
|
852 | if not dp: | |
841 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
853 | dp = IPython.core.hooks.CommandChainDispatcher() | |
842 |
|
854 | |||
843 | try: |
|
855 | try: | |
844 | dp.add(f,priority) |
|
856 | dp.add(f,priority) | |
845 | except AttributeError: |
|
857 | except AttributeError: | |
846 | # it was not commandchain, plain old func - replace |
|
858 | # it was not commandchain, plain old func - replace | |
847 | dp = f |
|
859 | dp = f | |
848 |
|
860 | |||
849 | setattr(self.hooks,name, dp) |
|
861 | setattr(self.hooks,name, dp) | |
850 |
|
862 | |||
851 | #------------------------------------------------------------------------- |
|
863 | #------------------------------------------------------------------------- | |
852 | # Things related to events |
|
864 | # Things related to events | |
853 | #------------------------------------------------------------------------- |
|
865 | #------------------------------------------------------------------------- | |
854 |
|
866 | |||
855 | def init_events(self): |
|
867 | def init_events(self): | |
856 | self.events = EventManager(self, available_events) |
|
868 | self.events = EventManager(self, available_events) | |
857 |
|
869 | |||
858 | self.events.register("pre_execute", self._clear_warning_registry) |
|
870 | self.events.register("pre_execute", self._clear_warning_registry) | |
859 |
|
871 | |||
860 | def register_post_execute(self, func): |
|
872 | def register_post_execute(self, func): | |
861 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
873 | """DEPRECATED: Use ip.events.register('post_run_cell', func) | |
862 |
|
874 | |||
863 | Register a function for calling after code execution. |
|
875 | Register a function for calling after code execution. | |
864 | """ |
|
876 | """ | |
865 | warn("ip.register_post_execute is deprecated, use " |
|
877 | warn("ip.register_post_execute is deprecated, use " | |
866 | "ip.events.register('post_run_cell', func) instead.") |
|
878 | "ip.events.register('post_run_cell', func) instead.") | |
867 | self.events.register('post_run_cell', func) |
|
879 | self.events.register('post_run_cell', func) | |
868 |
|
880 | |||
869 | def _clear_warning_registry(self): |
|
881 | def _clear_warning_registry(self): | |
870 | # clear the warning registry, so that different code blocks with |
|
882 | # clear the warning registry, so that different code blocks with | |
871 | # overlapping line number ranges don't cause spurious suppression of |
|
883 | # overlapping line number ranges don't cause spurious suppression of | |
872 | # warnings (see gh-6611 for details) |
|
884 | # warnings (see gh-6611 for details) | |
873 | if "__warningregistry__" in self.user_global_ns: |
|
885 | if "__warningregistry__" in self.user_global_ns: | |
874 | del self.user_global_ns["__warningregistry__"] |
|
886 | del self.user_global_ns["__warningregistry__"] | |
875 |
|
887 | |||
876 | #------------------------------------------------------------------------- |
|
888 | #------------------------------------------------------------------------- | |
877 | # Things related to the "main" module |
|
889 | # Things related to the "main" module | |
878 | #------------------------------------------------------------------------- |
|
890 | #------------------------------------------------------------------------- | |
879 |
|
891 | |||
880 | def new_main_mod(self, filename, modname): |
|
892 | def new_main_mod(self, filename, modname): | |
881 | """Return a new 'main' module object for user code execution. |
|
893 | """Return a new 'main' module object for user code execution. | |
882 |
|
894 | |||
883 | ``filename`` should be the path of the script which will be run in the |
|
895 | ``filename`` should be the path of the script which will be run in the | |
884 | module. Requests with the same filename will get the same module, with |
|
896 | module. Requests with the same filename will get the same module, with | |
885 | its namespace cleared. |
|
897 | its namespace cleared. | |
886 |
|
898 | |||
887 | ``modname`` should be the module name - normally either '__main__' or |
|
899 | ``modname`` should be the module name - normally either '__main__' or | |
888 | the basename of the file without the extension. |
|
900 | the basename of the file without the extension. | |
889 |
|
901 | |||
890 | When scripts are executed via %run, we must keep a reference to their |
|
902 | When scripts are executed via %run, we must keep a reference to their | |
891 | __main__ module around so that Python doesn't |
|
903 | __main__ module around so that Python doesn't | |
892 | clear it, rendering references to module globals useless. |
|
904 | clear it, rendering references to module globals useless. | |
893 |
|
905 | |||
894 | This method keeps said reference in a private dict, keyed by the |
|
906 | This method keeps said reference in a private dict, keyed by the | |
895 | absolute path of the script. This way, for multiple executions of the |
|
907 | absolute path of the script. This way, for multiple executions of the | |
896 | same script we only keep one copy of the namespace (the last one), |
|
908 | same script we only keep one copy of the namespace (the last one), | |
897 | thus preventing memory leaks from old references while allowing the |
|
909 | thus preventing memory leaks from old references while allowing the | |
898 | objects from the last execution to be accessible. |
|
910 | objects from the last execution to be accessible. | |
899 | """ |
|
911 | """ | |
900 | filename = os.path.abspath(filename) |
|
912 | filename = os.path.abspath(filename) | |
901 | try: |
|
913 | try: | |
902 | main_mod = self._main_mod_cache[filename] |
|
914 | main_mod = self._main_mod_cache[filename] | |
903 | except KeyError: |
|
915 | except KeyError: | |
904 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
916 | main_mod = self._main_mod_cache[filename] = types.ModuleType( | |
905 | py3compat.cast_bytes_py2(modname), |
|
917 | py3compat.cast_bytes_py2(modname), | |
906 | doc="Module created for script run in IPython") |
|
918 | doc="Module created for script run in IPython") | |
907 | else: |
|
919 | else: | |
908 | main_mod.__dict__.clear() |
|
920 | main_mod.__dict__.clear() | |
909 | main_mod.__name__ = modname |
|
921 | main_mod.__name__ = modname | |
910 |
|
922 | |||
911 | main_mod.__file__ = filename |
|
923 | main_mod.__file__ = filename | |
912 | # It seems pydoc (and perhaps others) needs any module instance to |
|
924 | # It seems pydoc (and perhaps others) needs any module instance to | |
913 | # implement a __nonzero__ method |
|
925 | # implement a __nonzero__ method | |
914 | main_mod.__nonzero__ = lambda : True |
|
926 | main_mod.__nonzero__ = lambda : True | |
915 |
|
927 | |||
916 | return main_mod |
|
928 | return main_mod | |
917 |
|
929 | |||
918 | def clear_main_mod_cache(self): |
|
930 | def clear_main_mod_cache(self): | |
919 | """Clear the cache of main modules. |
|
931 | """Clear the cache of main modules. | |
920 |
|
932 | |||
921 | Mainly for use by utilities like %reset. |
|
933 | Mainly for use by utilities like %reset. | |
922 |
|
934 | |||
923 | Examples |
|
935 | Examples | |
924 | -------- |
|
936 | -------- | |
925 |
|
937 | |||
926 | In [15]: import IPython |
|
938 | In [15]: import IPython | |
927 |
|
939 | |||
928 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
940 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') | |
929 |
|
941 | |||
930 | In [17]: len(_ip._main_mod_cache) > 0 |
|
942 | In [17]: len(_ip._main_mod_cache) > 0 | |
931 | Out[17]: True |
|
943 | Out[17]: True | |
932 |
|
944 | |||
933 | In [18]: _ip.clear_main_mod_cache() |
|
945 | In [18]: _ip.clear_main_mod_cache() | |
934 |
|
946 | |||
935 | In [19]: len(_ip._main_mod_cache) == 0 |
|
947 | In [19]: len(_ip._main_mod_cache) == 0 | |
936 | Out[19]: True |
|
948 | Out[19]: True | |
937 | """ |
|
949 | """ | |
938 | self._main_mod_cache.clear() |
|
950 | self._main_mod_cache.clear() | |
939 |
|
951 | |||
940 | #------------------------------------------------------------------------- |
|
952 | #------------------------------------------------------------------------- | |
941 | # Things related to debugging |
|
953 | # Things related to debugging | |
942 | #------------------------------------------------------------------------- |
|
954 | #------------------------------------------------------------------------- | |
943 |
|
955 | |||
944 | def init_pdb(self): |
|
956 | def init_pdb(self): | |
945 | # Set calling of pdb on exceptions |
|
957 | # Set calling of pdb on exceptions | |
946 | # self.call_pdb is a property |
|
958 | # self.call_pdb is a property | |
947 | self.call_pdb = self.pdb |
|
959 | self.call_pdb = self.pdb | |
948 |
|
960 | |||
949 | def _get_call_pdb(self): |
|
961 | def _get_call_pdb(self): | |
950 | return self._call_pdb |
|
962 | return self._call_pdb | |
951 |
|
963 | |||
952 | def _set_call_pdb(self,val): |
|
964 | def _set_call_pdb(self,val): | |
953 |
|
965 | |||
954 | if val not in (0,1,False,True): |
|
966 | if val not in (0,1,False,True): | |
955 | raise ValueError('new call_pdb value must be boolean') |
|
967 | raise ValueError('new call_pdb value must be boolean') | |
956 |
|
968 | |||
957 | # store value in instance |
|
969 | # store value in instance | |
958 | self._call_pdb = val |
|
970 | self._call_pdb = val | |
959 |
|
971 | |||
960 | # notify the actual exception handlers |
|
972 | # notify the actual exception handlers | |
961 | self.InteractiveTB.call_pdb = val |
|
973 | self.InteractiveTB.call_pdb = val | |
962 |
|
974 | |||
963 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
975 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
964 | 'Control auto-activation of pdb at exceptions') |
|
976 | 'Control auto-activation of pdb at exceptions') | |
965 |
|
977 | |||
966 | def debugger(self,force=False): |
|
978 | def debugger(self,force=False): | |
967 | """Call the pdb debugger. |
|
979 | """Call the pdb debugger. | |
968 |
|
980 | |||
969 | Keywords: |
|
981 | Keywords: | |
970 |
|
982 | |||
971 | - force(False): by default, this routine checks the instance call_pdb |
|
983 | - force(False): by default, this routine checks the instance call_pdb | |
972 | flag and does not actually invoke the debugger if the flag is false. |
|
984 | flag and does not actually invoke the debugger if the flag is false. | |
973 | The 'force' option forces the debugger to activate even if the flag |
|
985 | The 'force' option forces the debugger to activate even if the flag | |
974 | is false. |
|
986 | is false. | |
975 | """ |
|
987 | """ | |
976 |
|
988 | |||
977 | if not (force or self.call_pdb): |
|
989 | if not (force or self.call_pdb): | |
978 | return |
|
990 | return | |
979 |
|
991 | |||
980 | if not hasattr(sys,'last_traceback'): |
|
992 | if not hasattr(sys,'last_traceback'): | |
981 | error('No traceback has been produced, nothing to debug.') |
|
993 | error('No traceback has been produced, nothing to debug.') | |
982 | return |
|
994 | return | |
983 |
|
995 | |||
984 |
|
996 | |||
985 | with self.readline_no_record: |
|
997 | with self.readline_no_record: | |
986 | self.InteractiveTB.debugger(force=True) |
|
998 | self.InteractiveTB.debugger(force=True) | |
987 |
|
999 | |||
988 | #------------------------------------------------------------------------- |
|
1000 | #------------------------------------------------------------------------- | |
989 | # Things related to IPython's various namespaces |
|
1001 | # Things related to IPython's various namespaces | |
990 | #------------------------------------------------------------------------- |
|
1002 | #------------------------------------------------------------------------- | |
991 | default_user_namespaces = True |
|
1003 | default_user_namespaces = True | |
992 |
|
1004 | |||
993 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1005 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
994 | # Create the namespace where the user will operate. user_ns is |
|
1006 | # Create the namespace where the user will operate. user_ns is | |
995 | # normally the only one used, and it is passed to the exec calls as |
|
1007 | # normally the only one used, and it is passed to the exec calls as | |
996 | # the locals argument. But we do carry a user_global_ns namespace |
|
1008 | # the locals argument. But we do carry a user_global_ns namespace | |
997 | # given as the exec 'globals' argument, This is useful in embedding |
|
1009 | # given as the exec 'globals' argument, This is useful in embedding | |
998 | # situations where the ipython shell opens in a context where the |
|
1010 | # situations where the ipython shell opens in a context where the | |
999 | # distinction between locals and globals is meaningful. For |
|
1011 | # distinction between locals and globals is meaningful. For | |
1000 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1012 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
1001 |
|
1013 | |||
1002 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1014 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
1003 | # level as a dict instead of a module. This is a manual fix, but I |
|
1015 | # level as a dict instead of a module. This is a manual fix, but I | |
1004 | # should really track down where the problem is coming from. Alex |
|
1016 | # should really track down where the problem is coming from. Alex | |
1005 | # Schmolck reported this problem first. |
|
1017 | # Schmolck reported this problem first. | |
1006 |
|
1018 | |||
1007 | # A useful post by Alex Martelli on this topic: |
|
1019 | # A useful post by Alex Martelli on this topic: | |
1008 | # Re: inconsistent value from __builtins__ |
|
1020 | # Re: inconsistent value from __builtins__ | |
1009 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1021 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
1010 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1022 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
1011 | # Gruppen: comp.lang.python |
|
1023 | # Gruppen: comp.lang.python | |
1012 |
|
1024 | |||
1013 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1025 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
1014 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1026 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
1015 | # > <type 'dict'> |
|
1027 | # > <type 'dict'> | |
1016 | # > >>> print type(__builtins__) |
|
1028 | # > >>> print type(__builtins__) | |
1017 | # > <type 'module'> |
|
1029 | # > <type 'module'> | |
1018 | # > Is this difference in return value intentional? |
|
1030 | # > Is this difference in return value intentional? | |
1019 |
|
1031 | |||
1020 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1032 | # Well, it's documented that '__builtins__' can be either a dictionary | |
1021 | # or a module, and it's been that way for a long time. Whether it's |
|
1033 | # or a module, and it's been that way for a long time. Whether it's | |
1022 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1034 | # intentional (or sensible), I don't know. In any case, the idea is | |
1023 | # that if you need to access the built-in namespace directly, you |
|
1035 | # that if you need to access the built-in namespace directly, you | |
1024 | # should start with "import __builtin__" (note, no 's') which will |
|
1036 | # should start with "import __builtin__" (note, no 's') which will | |
1025 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1037 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
1026 |
|
1038 | |||
1027 | # These routines return a properly built module and dict as needed by |
|
1039 | # These routines return a properly built module and dict as needed by | |
1028 | # the rest of the code, and can also be used by extension writers to |
|
1040 | # the rest of the code, and can also be used by extension writers to | |
1029 | # generate properly initialized namespaces. |
|
1041 | # generate properly initialized namespaces. | |
1030 | if (user_ns is not None) or (user_module is not None): |
|
1042 | if (user_ns is not None) or (user_module is not None): | |
1031 | self.default_user_namespaces = False |
|
1043 | self.default_user_namespaces = False | |
1032 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1044 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) | |
1033 |
|
1045 | |||
1034 | # A record of hidden variables we have added to the user namespace, so |
|
1046 | # A record of hidden variables we have added to the user namespace, so | |
1035 | # we can list later only variables defined in actual interactive use. |
|
1047 | # we can list later only variables defined in actual interactive use. | |
1036 | self.user_ns_hidden = {} |
|
1048 | self.user_ns_hidden = {} | |
1037 |
|
1049 | |||
1038 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1050 | # Now that FakeModule produces a real module, we've run into a nasty | |
1039 | # problem: after script execution (via %run), the module where the user |
|
1051 | # problem: after script execution (via %run), the module where the user | |
1040 | # code ran is deleted. Now that this object is a true module (needed |
|
1052 | # code ran is deleted. Now that this object is a true module (needed | |
1041 | # so doctest and other tools work correctly), the Python module |
|
1053 | # so doctest and other tools work correctly), the Python module | |
1042 | # teardown mechanism runs over it, and sets to None every variable |
|
1054 | # teardown mechanism runs over it, and sets to None every variable | |
1043 | # present in that module. Top-level references to objects from the |
|
1055 | # present in that module. Top-level references to objects from the | |
1044 | # script survive, because the user_ns is updated with them. However, |
|
1056 | # script survive, because the user_ns is updated with them. However, | |
1045 | # calling functions defined in the script that use other things from |
|
1057 | # calling functions defined in the script that use other things from | |
1046 | # the script will fail, because the function's closure had references |
|
1058 | # the script will fail, because the function's closure had references | |
1047 | # to the original objects, which are now all None. So we must protect |
|
1059 | # to the original objects, which are now all None. So we must protect | |
1048 | # these modules from deletion by keeping a cache. |
|
1060 | # these modules from deletion by keeping a cache. | |
1049 | # |
|
1061 | # | |
1050 | # To avoid keeping stale modules around (we only need the one from the |
|
1062 | # To avoid keeping stale modules around (we only need the one from the | |
1051 | # last run), we use a dict keyed with the full path to the script, so |
|
1063 | # last run), we use a dict keyed with the full path to the script, so | |
1052 | # only the last version of the module is held in the cache. Note, |
|
1064 | # only the last version of the module is held in the cache. Note, | |
1053 | # however, that we must cache the module *namespace contents* (their |
|
1065 | # however, that we must cache the module *namespace contents* (their | |
1054 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1066 | # __dict__). Because if we try to cache the actual modules, old ones | |
1055 | # (uncached) could be destroyed while still holding references (such as |
|
1067 | # (uncached) could be destroyed while still holding references (such as | |
1056 | # those held by GUI objects that tend to be long-lived)> |
|
1068 | # those held by GUI objects that tend to be long-lived)> | |
1057 | # |
|
1069 | # | |
1058 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1070 | # The %reset command will flush this cache. See the cache_main_mod() | |
1059 | # and clear_main_mod_cache() methods for details on use. |
|
1071 | # and clear_main_mod_cache() methods for details on use. | |
1060 |
|
1072 | |||
1061 | # This is the cache used for 'main' namespaces |
|
1073 | # This is the cache used for 'main' namespaces | |
1062 | self._main_mod_cache = {} |
|
1074 | self._main_mod_cache = {} | |
1063 |
|
1075 | |||
1064 | # A table holding all the namespaces IPython deals with, so that |
|
1076 | # A table holding all the namespaces IPython deals with, so that | |
1065 | # introspection facilities can search easily. |
|
1077 | # introspection facilities can search easily. | |
1066 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1078 | self.ns_table = {'user_global':self.user_module.__dict__, | |
1067 | 'user_local':self.user_ns, |
|
1079 | 'user_local':self.user_ns, | |
1068 | 'builtin':builtin_mod.__dict__ |
|
1080 | 'builtin':builtin_mod.__dict__ | |
1069 | } |
|
1081 | } | |
1070 |
|
1082 | |||
1071 | @property |
|
1083 | @property | |
1072 | def user_global_ns(self): |
|
1084 | def user_global_ns(self): | |
1073 | return self.user_module.__dict__ |
|
1085 | return self.user_module.__dict__ | |
1074 |
|
1086 | |||
1075 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1087 | def prepare_user_module(self, user_module=None, user_ns=None): | |
1076 | """Prepare the module and namespace in which user code will be run. |
|
1088 | """Prepare the module and namespace in which user code will be run. | |
1077 |
|
1089 | |||
1078 | When IPython is started normally, both parameters are None: a new module |
|
1090 | When IPython is started normally, both parameters are None: a new module | |
1079 | is created automatically, and its __dict__ used as the namespace. |
|
1091 | is created automatically, and its __dict__ used as the namespace. | |
1080 |
|
1092 | |||
1081 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1093 | If only user_module is provided, its __dict__ is used as the namespace. | |
1082 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1094 | If only user_ns is provided, a dummy module is created, and user_ns | |
1083 | becomes the global namespace. If both are provided (as they may be |
|
1095 | becomes the global namespace. If both are provided (as they may be | |
1084 | when embedding), user_ns is the local namespace, and user_module |
|
1096 | when embedding), user_ns is the local namespace, and user_module | |
1085 | provides the global namespace. |
|
1097 | provides the global namespace. | |
1086 |
|
1098 | |||
1087 | Parameters |
|
1099 | Parameters | |
1088 | ---------- |
|
1100 | ---------- | |
1089 | user_module : module, optional |
|
1101 | user_module : module, optional | |
1090 | The current user module in which IPython is being run. If None, |
|
1102 | The current user module in which IPython is being run. If None, | |
1091 | a clean module will be created. |
|
1103 | a clean module will be created. | |
1092 | user_ns : dict, optional |
|
1104 | user_ns : dict, optional | |
1093 | A namespace in which to run interactive commands. |
|
1105 | A namespace in which to run interactive commands. | |
1094 |
|
1106 | |||
1095 | Returns |
|
1107 | Returns | |
1096 | ------- |
|
1108 | ------- | |
1097 | A tuple of user_module and user_ns, each properly initialised. |
|
1109 | A tuple of user_module and user_ns, each properly initialised. | |
1098 | """ |
|
1110 | """ | |
1099 | if user_module is None and user_ns is not None: |
|
1111 | if user_module is None and user_ns is not None: | |
1100 | user_ns.setdefault("__name__", "__main__") |
|
1112 | user_ns.setdefault("__name__", "__main__") | |
1101 | user_module = DummyMod() |
|
1113 | user_module = DummyMod() | |
1102 | user_module.__dict__ = user_ns |
|
1114 | user_module.__dict__ = user_ns | |
1103 |
|
1115 | |||
1104 | if user_module is None: |
|
1116 | if user_module is None: | |
1105 | user_module = types.ModuleType("__main__", |
|
1117 | user_module = types.ModuleType("__main__", | |
1106 | doc="Automatically created module for IPython interactive environment") |
|
1118 | doc="Automatically created module for IPython interactive environment") | |
1107 |
|
1119 | |||
1108 | # We must ensure that __builtin__ (without the final 's') is always |
|
1120 | # We must ensure that __builtin__ (without the final 's') is always | |
1109 | # available and pointing to the __builtin__ *module*. For more details: |
|
1121 | # available and pointing to the __builtin__ *module*. For more details: | |
1110 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1122 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1111 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1123 | user_module.__dict__.setdefault('__builtin__', builtin_mod) | |
1112 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1124 | user_module.__dict__.setdefault('__builtins__', builtin_mod) | |
1113 |
|
1125 | |||
1114 | if user_ns is None: |
|
1126 | if user_ns is None: | |
1115 | user_ns = user_module.__dict__ |
|
1127 | user_ns = user_module.__dict__ | |
1116 |
|
1128 | |||
1117 | return user_module, user_ns |
|
1129 | return user_module, user_ns | |
1118 |
|
1130 | |||
1119 | def init_sys_modules(self): |
|
1131 | def init_sys_modules(self): | |
1120 | # We need to insert into sys.modules something that looks like a |
|
1132 | # We need to insert into sys.modules something that looks like a | |
1121 | # module but which accesses the IPython namespace, for shelve and |
|
1133 | # module but which accesses the IPython namespace, for shelve and | |
1122 | # pickle to work interactively. Normally they rely on getting |
|
1134 | # pickle to work interactively. Normally they rely on getting | |
1123 | # everything out of __main__, but for embedding purposes each IPython |
|
1135 | # everything out of __main__, but for embedding purposes each IPython | |
1124 | # instance has its own private namespace, so we can't go shoving |
|
1136 | # instance has its own private namespace, so we can't go shoving | |
1125 | # everything into __main__. |
|
1137 | # everything into __main__. | |
1126 |
|
1138 | |||
1127 | # note, however, that we should only do this for non-embedded |
|
1139 | # note, however, that we should only do this for non-embedded | |
1128 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1140 | # ipythons, which really mimic the __main__.__dict__ with their own | |
1129 | # namespace. Embedded instances, on the other hand, should not do |
|
1141 | # namespace. Embedded instances, on the other hand, should not do | |
1130 | # this because they need to manage the user local/global namespaces |
|
1142 | # this because they need to manage the user local/global namespaces | |
1131 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1143 | # only, but they live within a 'normal' __main__ (meaning, they | |
1132 | # shouldn't overtake the execution environment of the script they're |
|
1144 | # shouldn't overtake the execution environment of the script they're | |
1133 | # embedded in). |
|
1145 | # embedded in). | |
1134 |
|
1146 | |||
1135 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1147 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1136 | main_name = self.user_module.__name__ |
|
1148 | main_name = self.user_module.__name__ | |
1137 | sys.modules[main_name] = self.user_module |
|
1149 | sys.modules[main_name] = self.user_module | |
1138 |
|
1150 | |||
1139 | def init_user_ns(self): |
|
1151 | def init_user_ns(self): | |
1140 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1152 | """Initialize all user-visible namespaces to their minimum defaults. | |
1141 |
|
1153 | |||
1142 | Certain history lists are also initialized here, as they effectively |
|
1154 | Certain history lists are also initialized here, as they effectively | |
1143 | act as user namespaces. |
|
1155 | act as user namespaces. | |
1144 |
|
1156 | |||
1145 | Notes |
|
1157 | Notes | |
1146 | ----- |
|
1158 | ----- | |
1147 | All data structures here are only filled in, they are NOT reset by this |
|
1159 | All data structures here are only filled in, they are NOT reset by this | |
1148 | method. If they were not empty before, data will simply be added to |
|
1160 | method. If they were not empty before, data will simply be added to | |
1149 | therm. |
|
1161 | therm. | |
1150 | """ |
|
1162 | """ | |
1151 | # This function works in two parts: first we put a few things in |
|
1163 | # This function works in two parts: first we put a few things in | |
1152 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1164 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1153 | # initial variables aren't shown by %who. After the sync, we add the |
|
1165 | # initial variables aren't shown by %who. After the sync, we add the | |
1154 | # rest of what we *do* want the user to see with %who even on a new |
|
1166 | # rest of what we *do* want the user to see with %who even on a new | |
1155 | # session (probably nothing, so they really only see their own stuff) |
|
1167 | # session (probably nothing, so they really only see their own stuff) | |
1156 |
|
1168 | |||
1157 | # The user dict must *always* have a __builtin__ reference to the |
|
1169 | # The user dict must *always* have a __builtin__ reference to the | |
1158 | # Python standard __builtin__ namespace, which must be imported. |
|
1170 | # Python standard __builtin__ namespace, which must be imported. | |
1159 | # This is so that certain operations in prompt evaluation can be |
|
1171 | # This is so that certain operations in prompt evaluation can be | |
1160 | # reliably executed with builtins. Note that we can NOT use |
|
1172 | # reliably executed with builtins. Note that we can NOT use | |
1161 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1173 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1162 | # module, and can even mutate at runtime, depending on the context |
|
1174 | # module, and can even mutate at runtime, depending on the context | |
1163 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1175 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1164 | # always a module object, though it must be explicitly imported. |
|
1176 | # always a module object, though it must be explicitly imported. | |
1165 |
|
1177 | |||
1166 | # For more details: |
|
1178 | # For more details: | |
1167 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1179 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1168 | ns = dict() |
|
1180 | ns = dict() | |
1169 |
|
1181 | |||
1170 | # make global variables for user access to the histories |
|
1182 | # make global variables for user access to the histories | |
1171 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1183 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1172 | ns['_oh'] = self.history_manager.output_hist |
|
1184 | ns['_oh'] = self.history_manager.output_hist | |
1173 | ns['_dh'] = self.history_manager.dir_hist |
|
1185 | ns['_dh'] = self.history_manager.dir_hist | |
1174 |
|
1186 | |||
1175 | ns['_sh'] = shadowns |
|
1187 | ns['_sh'] = shadowns | |
1176 |
|
1188 | |||
1177 | # user aliases to input and output histories. These shouldn't show up |
|
1189 | # user aliases to input and output histories. These shouldn't show up | |
1178 | # in %who, as they can have very large reprs. |
|
1190 | # in %who, as they can have very large reprs. | |
1179 | ns['In'] = self.history_manager.input_hist_parsed |
|
1191 | ns['In'] = self.history_manager.input_hist_parsed | |
1180 | ns['Out'] = self.history_manager.output_hist |
|
1192 | ns['Out'] = self.history_manager.output_hist | |
1181 |
|
1193 | |||
1182 | # Store myself as the public api!!! |
|
1194 | # Store myself as the public api!!! | |
1183 | ns['get_ipython'] = self.get_ipython |
|
1195 | ns['get_ipython'] = self.get_ipython | |
1184 |
|
1196 | |||
1185 | ns['exit'] = self.exiter |
|
1197 | ns['exit'] = self.exiter | |
1186 | ns['quit'] = self.exiter |
|
1198 | ns['quit'] = self.exiter | |
1187 |
|
1199 | |||
1188 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1200 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1189 | # by %who |
|
1201 | # by %who | |
1190 | self.user_ns_hidden.update(ns) |
|
1202 | self.user_ns_hidden.update(ns) | |
1191 |
|
1203 | |||
1192 | # Anything put into ns now would show up in %who. Think twice before |
|
1204 | # Anything put into ns now would show up in %who. Think twice before | |
1193 | # putting anything here, as we really want %who to show the user their |
|
1205 | # putting anything here, as we really want %who to show the user their | |
1194 | # stuff, not our variables. |
|
1206 | # stuff, not our variables. | |
1195 |
|
1207 | |||
1196 | # Finally, update the real user's namespace |
|
1208 | # Finally, update the real user's namespace | |
1197 | self.user_ns.update(ns) |
|
1209 | self.user_ns.update(ns) | |
1198 |
|
1210 | |||
1199 | @property |
|
1211 | @property | |
1200 | def all_ns_refs(self): |
|
1212 | def all_ns_refs(self): | |
1201 | """Get a list of references to all the namespace dictionaries in which |
|
1213 | """Get a list of references to all the namespace dictionaries in which | |
1202 | IPython might store a user-created object. |
|
1214 | IPython might store a user-created object. | |
1203 |
|
1215 | |||
1204 | Note that this does not include the displayhook, which also caches |
|
1216 | Note that this does not include the displayhook, which also caches | |
1205 | objects from the output.""" |
|
1217 | objects from the output.""" | |
1206 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1218 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ | |
1207 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1219 | [m.__dict__ for m in self._main_mod_cache.values()] | |
1208 |
|
1220 | |||
1209 | def reset(self, new_session=True): |
|
1221 | def reset(self, new_session=True): | |
1210 | """Clear all internal namespaces, and attempt to release references to |
|
1222 | """Clear all internal namespaces, and attempt to release references to | |
1211 | user objects. |
|
1223 | user objects. | |
1212 |
|
1224 | |||
1213 | If new_session is True, a new history session will be opened. |
|
1225 | If new_session is True, a new history session will be opened. | |
1214 | """ |
|
1226 | """ | |
1215 | # Clear histories |
|
1227 | # Clear histories | |
1216 | self.history_manager.reset(new_session) |
|
1228 | self.history_manager.reset(new_session) | |
1217 | # Reset counter used to index all histories |
|
1229 | # Reset counter used to index all histories | |
1218 | if new_session: |
|
1230 | if new_session: | |
1219 | self.execution_count = 1 |
|
1231 | self.execution_count = 1 | |
1220 |
|
1232 | |||
1221 | # Flush cached output items |
|
1233 | # Flush cached output items | |
1222 | if self.displayhook.do_full_cache: |
|
1234 | if self.displayhook.do_full_cache: | |
1223 | self.displayhook.flush() |
|
1235 | self.displayhook.flush() | |
1224 |
|
1236 | |||
1225 | # The main execution namespaces must be cleared very carefully, |
|
1237 | # The main execution namespaces must be cleared very carefully, | |
1226 | # skipping the deletion of the builtin-related keys, because doing so |
|
1238 | # skipping the deletion of the builtin-related keys, because doing so | |
1227 | # would cause errors in many object's __del__ methods. |
|
1239 | # would cause errors in many object's __del__ methods. | |
1228 | if self.user_ns is not self.user_global_ns: |
|
1240 | if self.user_ns is not self.user_global_ns: | |
1229 | self.user_ns.clear() |
|
1241 | self.user_ns.clear() | |
1230 | ns = self.user_global_ns |
|
1242 | ns = self.user_global_ns | |
1231 | drop_keys = set(ns.keys()) |
|
1243 | drop_keys = set(ns.keys()) | |
1232 | drop_keys.discard('__builtin__') |
|
1244 | drop_keys.discard('__builtin__') | |
1233 | drop_keys.discard('__builtins__') |
|
1245 | drop_keys.discard('__builtins__') | |
1234 | drop_keys.discard('__name__') |
|
1246 | drop_keys.discard('__name__') | |
1235 | for k in drop_keys: |
|
1247 | for k in drop_keys: | |
1236 | del ns[k] |
|
1248 | del ns[k] | |
1237 |
|
1249 | |||
1238 | self.user_ns_hidden.clear() |
|
1250 | self.user_ns_hidden.clear() | |
1239 |
|
1251 | |||
1240 | # Restore the user namespaces to minimal usability |
|
1252 | # Restore the user namespaces to minimal usability | |
1241 | self.init_user_ns() |
|
1253 | self.init_user_ns() | |
1242 |
|
1254 | |||
1243 | # Restore the default and user aliases |
|
1255 | # Restore the default and user aliases | |
1244 | self.alias_manager.clear_aliases() |
|
1256 | self.alias_manager.clear_aliases() | |
1245 | self.alias_manager.init_aliases() |
|
1257 | self.alias_manager.init_aliases() | |
1246 |
|
1258 | |||
1247 | # Flush the private list of module references kept for script |
|
1259 | # Flush the private list of module references kept for script | |
1248 | # execution protection |
|
1260 | # execution protection | |
1249 | self.clear_main_mod_cache() |
|
1261 | self.clear_main_mod_cache() | |
1250 |
|
1262 | |||
1251 | def del_var(self, varname, by_name=False): |
|
1263 | def del_var(self, varname, by_name=False): | |
1252 | """Delete a variable from the various namespaces, so that, as |
|
1264 | """Delete a variable from the various namespaces, so that, as | |
1253 | far as possible, we're not keeping any hidden references to it. |
|
1265 | far as possible, we're not keeping any hidden references to it. | |
1254 |
|
1266 | |||
1255 | Parameters |
|
1267 | Parameters | |
1256 | ---------- |
|
1268 | ---------- | |
1257 | varname : str |
|
1269 | varname : str | |
1258 | The name of the variable to delete. |
|
1270 | The name of the variable to delete. | |
1259 | by_name : bool |
|
1271 | by_name : bool | |
1260 | If True, delete variables with the given name in each |
|
1272 | If True, delete variables with the given name in each | |
1261 | namespace. If False (default), find the variable in the user |
|
1273 | namespace. If False (default), find the variable in the user | |
1262 | namespace, and delete references to it. |
|
1274 | namespace, and delete references to it. | |
1263 | """ |
|
1275 | """ | |
1264 | if varname in ('__builtin__', '__builtins__'): |
|
1276 | if varname in ('__builtin__', '__builtins__'): | |
1265 | raise ValueError("Refusing to delete %s" % varname) |
|
1277 | raise ValueError("Refusing to delete %s" % varname) | |
1266 |
|
1278 | |||
1267 | ns_refs = self.all_ns_refs |
|
1279 | ns_refs = self.all_ns_refs | |
1268 |
|
1280 | |||
1269 | if by_name: # Delete by name |
|
1281 | if by_name: # Delete by name | |
1270 | for ns in ns_refs: |
|
1282 | for ns in ns_refs: | |
1271 | try: |
|
1283 | try: | |
1272 | del ns[varname] |
|
1284 | del ns[varname] | |
1273 | except KeyError: |
|
1285 | except KeyError: | |
1274 | pass |
|
1286 | pass | |
1275 | else: # Delete by object |
|
1287 | else: # Delete by object | |
1276 | try: |
|
1288 | try: | |
1277 | obj = self.user_ns[varname] |
|
1289 | obj = self.user_ns[varname] | |
1278 | except KeyError: |
|
1290 | except KeyError: | |
1279 | raise NameError("name '%s' is not defined" % varname) |
|
1291 | raise NameError("name '%s' is not defined" % varname) | |
1280 | # Also check in output history |
|
1292 | # Also check in output history | |
1281 | ns_refs.append(self.history_manager.output_hist) |
|
1293 | ns_refs.append(self.history_manager.output_hist) | |
1282 | for ns in ns_refs: |
|
1294 | for ns in ns_refs: | |
1283 | to_delete = [n for n, o in iteritems(ns) if o is obj] |
|
1295 | to_delete = [n for n, o in iteritems(ns) if o is obj] | |
1284 | for name in to_delete: |
|
1296 | for name in to_delete: | |
1285 | del ns[name] |
|
1297 | del ns[name] | |
1286 |
|
1298 | |||
1287 | # displayhook keeps extra references, but not in a dictionary |
|
1299 | # displayhook keeps extra references, but not in a dictionary | |
1288 | for name in ('_', '__', '___'): |
|
1300 | for name in ('_', '__', '___'): | |
1289 | if getattr(self.displayhook, name) is obj: |
|
1301 | if getattr(self.displayhook, name) is obj: | |
1290 | setattr(self.displayhook, name, None) |
|
1302 | setattr(self.displayhook, name, None) | |
1291 |
|
1303 | |||
1292 | def reset_selective(self, regex=None): |
|
1304 | def reset_selective(self, regex=None): | |
1293 | """Clear selective variables from internal namespaces based on a |
|
1305 | """Clear selective variables from internal namespaces based on a | |
1294 | specified regular expression. |
|
1306 | specified regular expression. | |
1295 |
|
1307 | |||
1296 | Parameters |
|
1308 | Parameters | |
1297 | ---------- |
|
1309 | ---------- | |
1298 | regex : string or compiled pattern, optional |
|
1310 | regex : string or compiled pattern, optional | |
1299 | A regular expression pattern that will be used in searching |
|
1311 | A regular expression pattern that will be used in searching | |
1300 | variable names in the users namespaces. |
|
1312 | variable names in the users namespaces. | |
1301 | """ |
|
1313 | """ | |
1302 | if regex is not None: |
|
1314 | if regex is not None: | |
1303 | try: |
|
1315 | try: | |
1304 | m = re.compile(regex) |
|
1316 | m = re.compile(regex) | |
1305 | except TypeError: |
|
1317 | except TypeError: | |
1306 | raise TypeError('regex must be a string or compiled pattern') |
|
1318 | raise TypeError('regex must be a string or compiled pattern') | |
1307 | # Search for keys in each namespace that match the given regex |
|
1319 | # Search for keys in each namespace that match the given regex | |
1308 | # If a match is found, delete the key/value pair. |
|
1320 | # If a match is found, delete the key/value pair. | |
1309 | for ns in self.all_ns_refs: |
|
1321 | for ns in self.all_ns_refs: | |
1310 | for var in ns: |
|
1322 | for var in ns: | |
1311 | if m.search(var): |
|
1323 | if m.search(var): | |
1312 | del ns[var] |
|
1324 | del ns[var] | |
1313 |
|
1325 | |||
1314 | def push(self, variables, interactive=True): |
|
1326 | def push(self, variables, interactive=True): | |
1315 | """Inject a group of variables into the IPython user namespace. |
|
1327 | """Inject a group of variables into the IPython user namespace. | |
1316 |
|
1328 | |||
1317 | Parameters |
|
1329 | Parameters | |
1318 | ---------- |
|
1330 | ---------- | |
1319 | variables : dict, str or list/tuple of str |
|
1331 | variables : dict, str or list/tuple of str | |
1320 | The variables to inject into the user's namespace. If a dict, a |
|
1332 | The variables to inject into the user's namespace. If a dict, a | |
1321 | simple update is done. If a str, the string is assumed to have |
|
1333 | simple update is done. If a str, the string is assumed to have | |
1322 | variable names separated by spaces. A list/tuple of str can also |
|
1334 | variable names separated by spaces. A list/tuple of str can also | |
1323 | be used to give the variable names. If just the variable names are |
|
1335 | be used to give the variable names. If just the variable names are | |
1324 | give (list/tuple/str) then the variable values looked up in the |
|
1336 | give (list/tuple/str) then the variable values looked up in the | |
1325 | callers frame. |
|
1337 | callers frame. | |
1326 | interactive : bool |
|
1338 | interactive : bool | |
1327 | If True (default), the variables will be listed with the ``who`` |
|
1339 | If True (default), the variables will be listed with the ``who`` | |
1328 | magic. |
|
1340 | magic. | |
1329 | """ |
|
1341 | """ | |
1330 | vdict = None |
|
1342 | vdict = None | |
1331 |
|
1343 | |||
1332 | # We need a dict of name/value pairs to do namespace updates. |
|
1344 | # We need a dict of name/value pairs to do namespace updates. | |
1333 | if isinstance(variables, dict): |
|
1345 | if isinstance(variables, dict): | |
1334 | vdict = variables |
|
1346 | vdict = variables | |
1335 | elif isinstance(variables, string_types+(list, tuple)): |
|
1347 | elif isinstance(variables, string_types+(list, tuple)): | |
1336 | if isinstance(variables, string_types): |
|
1348 | if isinstance(variables, string_types): | |
1337 | vlist = variables.split() |
|
1349 | vlist = variables.split() | |
1338 | else: |
|
1350 | else: | |
1339 | vlist = variables |
|
1351 | vlist = variables | |
1340 | vdict = {} |
|
1352 | vdict = {} | |
1341 | cf = sys._getframe(1) |
|
1353 | cf = sys._getframe(1) | |
1342 | for name in vlist: |
|
1354 | for name in vlist: | |
1343 | try: |
|
1355 | try: | |
1344 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1356 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1345 | except: |
|
1357 | except: | |
1346 | print('Could not get variable %s from %s' % |
|
1358 | print('Could not get variable %s from %s' % | |
1347 | (name,cf.f_code.co_name)) |
|
1359 | (name,cf.f_code.co_name)) | |
1348 | else: |
|
1360 | else: | |
1349 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1361 | raise ValueError('variables must be a dict/str/list/tuple') | |
1350 |
|
1362 | |||
1351 | # Propagate variables to user namespace |
|
1363 | # Propagate variables to user namespace | |
1352 | self.user_ns.update(vdict) |
|
1364 | self.user_ns.update(vdict) | |
1353 |
|
1365 | |||
1354 | # And configure interactive visibility |
|
1366 | # And configure interactive visibility | |
1355 | user_ns_hidden = self.user_ns_hidden |
|
1367 | user_ns_hidden = self.user_ns_hidden | |
1356 | if interactive: |
|
1368 | if interactive: | |
1357 | for name in vdict: |
|
1369 | for name in vdict: | |
1358 | user_ns_hidden.pop(name, None) |
|
1370 | user_ns_hidden.pop(name, None) | |
1359 | else: |
|
1371 | else: | |
1360 | user_ns_hidden.update(vdict) |
|
1372 | user_ns_hidden.update(vdict) | |
1361 |
|
1373 | |||
1362 | def drop_by_id(self, variables): |
|
1374 | def drop_by_id(self, variables): | |
1363 | """Remove a dict of variables from the user namespace, if they are the |
|
1375 | """Remove a dict of variables from the user namespace, if they are the | |
1364 | same as the values in the dictionary. |
|
1376 | same as the values in the dictionary. | |
1365 |
|
1377 | |||
1366 | This is intended for use by extensions: variables that they've added can |
|
1378 | This is intended for use by extensions: variables that they've added can | |
1367 | be taken back out if they are unloaded, without removing any that the |
|
1379 | be taken back out if they are unloaded, without removing any that the | |
1368 | user has overwritten. |
|
1380 | user has overwritten. | |
1369 |
|
1381 | |||
1370 | Parameters |
|
1382 | Parameters | |
1371 | ---------- |
|
1383 | ---------- | |
1372 | variables : dict |
|
1384 | variables : dict | |
1373 | A dictionary mapping object names (as strings) to the objects. |
|
1385 | A dictionary mapping object names (as strings) to the objects. | |
1374 | """ |
|
1386 | """ | |
1375 | for name, obj in iteritems(variables): |
|
1387 | for name, obj in iteritems(variables): | |
1376 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1388 | if name in self.user_ns and self.user_ns[name] is obj: | |
1377 | del self.user_ns[name] |
|
1389 | del self.user_ns[name] | |
1378 | self.user_ns_hidden.pop(name, None) |
|
1390 | self.user_ns_hidden.pop(name, None) | |
1379 |
|
1391 | |||
1380 | #------------------------------------------------------------------------- |
|
1392 | #------------------------------------------------------------------------- | |
1381 | # Things related to object introspection |
|
1393 | # Things related to object introspection | |
1382 | #------------------------------------------------------------------------- |
|
1394 | #------------------------------------------------------------------------- | |
1383 |
|
1395 | |||
1384 | def _ofind(self, oname, namespaces=None): |
|
1396 | def _ofind(self, oname, namespaces=None): | |
1385 | """Find an object in the available namespaces. |
|
1397 | """Find an object in the available namespaces. | |
1386 |
|
1398 | |||
1387 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1399 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1388 |
|
1400 | |||
1389 | Has special code to detect magic functions. |
|
1401 | Has special code to detect magic functions. | |
1390 | """ |
|
1402 | """ | |
1391 | oname = oname.strip() |
|
1403 | oname = oname.strip() | |
1392 | #print '1- oname: <%r>' % oname # dbg |
|
1404 | #print '1- oname: <%r>' % oname # dbg | |
1393 | if not oname.startswith(ESC_MAGIC) and \ |
|
1405 | if not oname.startswith(ESC_MAGIC) and \ | |
1394 | not oname.startswith(ESC_MAGIC2) and \ |
|
1406 | not oname.startswith(ESC_MAGIC2) and \ | |
1395 | not py3compat.isidentifier(oname, dotted=True): |
|
1407 | not py3compat.isidentifier(oname, dotted=True): | |
1396 | return dict(found=False) |
|
1408 | return dict(found=False) | |
1397 |
|
1409 | |||
1398 | if namespaces is None: |
|
1410 | if namespaces is None: | |
1399 | # Namespaces to search in: |
|
1411 | # Namespaces to search in: | |
1400 | # Put them in a list. The order is important so that we |
|
1412 | # Put them in a list. The order is important so that we | |
1401 | # find things in the same order that Python finds them. |
|
1413 | # find things in the same order that Python finds them. | |
1402 | namespaces = [ ('Interactive', self.user_ns), |
|
1414 | namespaces = [ ('Interactive', self.user_ns), | |
1403 | ('Interactive (global)', self.user_global_ns), |
|
1415 | ('Interactive (global)', self.user_global_ns), | |
1404 | ('Python builtin', builtin_mod.__dict__), |
|
1416 | ('Python builtin', builtin_mod.__dict__), | |
1405 | ] |
|
1417 | ] | |
1406 |
|
1418 | |||
1407 | # initialize results to 'null' |
|
1419 | # initialize results to 'null' | |
1408 | found = False; obj = None; ospace = None; |
|
1420 | found = False; obj = None; ospace = None; | |
1409 | ismagic = False; isalias = False; parent = None |
|
1421 | ismagic = False; isalias = False; parent = None | |
1410 |
|
1422 | |||
1411 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1423 | # We need to special-case 'print', which as of python2.6 registers as a | |
1412 | # function but should only be treated as one if print_function was |
|
1424 | # function but should only be treated as one if print_function was | |
1413 | # loaded with a future import. In this case, just bail. |
|
1425 | # loaded with a future import. In this case, just bail. | |
1414 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1426 | if (oname == 'print' and not py3compat.PY3 and not \ | |
1415 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1427 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1416 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1428 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1417 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1429 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1418 |
|
1430 | |||
1419 | # Look for the given name by splitting it in parts. If the head is |
|
1431 | # Look for the given name by splitting it in parts. If the head is | |
1420 | # found, then we look for all the remaining parts as members, and only |
|
1432 | # found, then we look for all the remaining parts as members, and only | |
1421 | # declare success if we can find them all. |
|
1433 | # declare success if we can find them all. | |
1422 | oname_parts = oname.split('.') |
|
1434 | oname_parts = oname.split('.') | |
1423 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1435 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1424 | for nsname,ns in namespaces: |
|
1436 | for nsname,ns in namespaces: | |
1425 | try: |
|
1437 | try: | |
1426 | obj = ns[oname_head] |
|
1438 | obj = ns[oname_head] | |
1427 | except KeyError: |
|
1439 | except KeyError: | |
1428 | continue |
|
1440 | continue | |
1429 | else: |
|
1441 | else: | |
1430 | #print 'oname_rest:', oname_rest # dbg |
|
1442 | #print 'oname_rest:', oname_rest # dbg | |
1431 | for idx, part in enumerate(oname_rest): |
|
1443 | for idx, part in enumerate(oname_rest): | |
1432 | try: |
|
1444 | try: | |
1433 | parent = obj |
|
1445 | parent = obj | |
1434 | # The last part is looked up in a special way to avoid |
|
1446 | # The last part is looked up in a special way to avoid | |
1435 | # descriptor invocation as it may raise or have side |
|
1447 | # descriptor invocation as it may raise or have side | |
1436 | # effects. |
|
1448 | # effects. | |
1437 | if idx == len(oname_rest) - 1: |
|
1449 | if idx == len(oname_rest) - 1: | |
1438 | obj = self._getattr_property(obj, part) |
|
1450 | obj = self._getattr_property(obj, part) | |
1439 | else: |
|
1451 | else: | |
1440 | obj = getattr(obj, part) |
|
1452 | obj = getattr(obj, part) | |
1441 | except: |
|
1453 | except: | |
1442 | # Blanket except b/c some badly implemented objects |
|
1454 | # Blanket except b/c some badly implemented objects | |
1443 | # allow __getattr__ to raise exceptions other than |
|
1455 | # allow __getattr__ to raise exceptions other than | |
1444 | # AttributeError, which then crashes IPython. |
|
1456 | # AttributeError, which then crashes IPython. | |
1445 | break |
|
1457 | break | |
1446 | else: |
|
1458 | else: | |
1447 | # If we finish the for loop (no break), we got all members |
|
1459 | # If we finish the for loop (no break), we got all members | |
1448 | found = True |
|
1460 | found = True | |
1449 | ospace = nsname |
|
1461 | ospace = nsname | |
1450 | break # namespace loop |
|
1462 | break # namespace loop | |
1451 |
|
1463 | |||
1452 | # Try to see if it's magic |
|
1464 | # Try to see if it's magic | |
1453 | if not found: |
|
1465 | if not found: | |
1454 | obj = None |
|
1466 | obj = None | |
1455 | if oname.startswith(ESC_MAGIC2): |
|
1467 | if oname.startswith(ESC_MAGIC2): | |
1456 | oname = oname.lstrip(ESC_MAGIC2) |
|
1468 | oname = oname.lstrip(ESC_MAGIC2) | |
1457 | obj = self.find_cell_magic(oname) |
|
1469 | obj = self.find_cell_magic(oname) | |
1458 | elif oname.startswith(ESC_MAGIC): |
|
1470 | elif oname.startswith(ESC_MAGIC): | |
1459 | oname = oname.lstrip(ESC_MAGIC) |
|
1471 | oname = oname.lstrip(ESC_MAGIC) | |
1460 | obj = self.find_line_magic(oname) |
|
1472 | obj = self.find_line_magic(oname) | |
1461 | else: |
|
1473 | else: | |
1462 | # search without prefix, so run? will find %run? |
|
1474 | # search without prefix, so run? will find %run? | |
1463 | obj = self.find_line_magic(oname) |
|
1475 | obj = self.find_line_magic(oname) | |
1464 | if obj is None: |
|
1476 | if obj is None: | |
1465 | obj = self.find_cell_magic(oname) |
|
1477 | obj = self.find_cell_magic(oname) | |
1466 | if obj is not None: |
|
1478 | if obj is not None: | |
1467 | found = True |
|
1479 | found = True | |
1468 | ospace = 'IPython internal' |
|
1480 | ospace = 'IPython internal' | |
1469 | ismagic = True |
|
1481 | ismagic = True | |
1470 | isalias = isinstance(obj, Alias) |
|
1482 | isalias = isinstance(obj, Alias) | |
1471 |
|
1483 | |||
1472 | # Last try: special-case some literals like '', [], {}, etc: |
|
1484 | # Last try: special-case some literals like '', [], {}, etc: | |
1473 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1485 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1474 | obj = eval(oname_head) |
|
1486 | obj = eval(oname_head) | |
1475 | found = True |
|
1487 | found = True | |
1476 | ospace = 'Interactive' |
|
1488 | ospace = 'Interactive' | |
1477 |
|
1489 | |||
1478 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1490 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1479 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1491 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1480 |
|
1492 | |||
1481 | @staticmethod |
|
1493 | @staticmethod | |
1482 | def _getattr_property(obj, attrname): |
|
1494 | def _getattr_property(obj, attrname): | |
1483 | """Property-aware getattr to use in object finding. |
|
1495 | """Property-aware getattr to use in object finding. | |
1484 |
|
1496 | |||
1485 | If attrname represents a property, return it unevaluated (in case it has |
|
1497 | If attrname represents a property, return it unevaluated (in case it has | |
1486 | side effects or raises an error. |
|
1498 | side effects or raises an error. | |
1487 |
|
1499 | |||
1488 | """ |
|
1500 | """ | |
1489 | if not isinstance(obj, type): |
|
1501 | if not isinstance(obj, type): | |
1490 | try: |
|
1502 | try: | |
1491 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1503 | # `getattr(type(obj), attrname)` is not guaranteed to return | |
1492 | # `obj`, but does so for property: |
|
1504 | # `obj`, but does so for property: | |
1493 | # |
|
1505 | # | |
1494 | # property.__get__(self, None, cls) -> self |
|
1506 | # property.__get__(self, None, cls) -> self | |
1495 | # |
|
1507 | # | |
1496 | # The universal alternative is to traverse the mro manually |
|
1508 | # The universal alternative is to traverse the mro manually | |
1497 | # searching for attrname in class dicts. |
|
1509 | # searching for attrname in class dicts. | |
1498 | attr = getattr(type(obj), attrname) |
|
1510 | attr = getattr(type(obj), attrname) | |
1499 | except AttributeError: |
|
1511 | except AttributeError: | |
1500 | pass |
|
1512 | pass | |
1501 | else: |
|
1513 | else: | |
1502 | # This relies on the fact that data descriptors (with both |
|
1514 | # This relies on the fact that data descriptors (with both | |
1503 | # __get__ & __set__ magic methods) take precedence over |
|
1515 | # __get__ & __set__ magic methods) take precedence over | |
1504 | # instance-level attributes: |
|
1516 | # instance-level attributes: | |
1505 | # |
|
1517 | # | |
1506 | # class A(object): |
|
1518 | # class A(object): | |
1507 | # @property |
|
1519 | # @property | |
1508 | # def foobar(self): return 123 |
|
1520 | # def foobar(self): return 123 | |
1509 | # a = A() |
|
1521 | # a = A() | |
1510 | # a.__dict__['foobar'] = 345 |
|
1522 | # a.__dict__['foobar'] = 345 | |
1511 | # a.foobar # == 123 |
|
1523 | # a.foobar # == 123 | |
1512 | # |
|
1524 | # | |
1513 | # So, a property may be returned right away. |
|
1525 | # So, a property may be returned right away. | |
1514 | if isinstance(attr, property): |
|
1526 | if isinstance(attr, property): | |
1515 | return attr |
|
1527 | return attr | |
1516 |
|
1528 | |||
1517 | # Nothing helped, fall back. |
|
1529 | # Nothing helped, fall back. | |
1518 | return getattr(obj, attrname) |
|
1530 | return getattr(obj, attrname) | |
1519 |
|
1531 | |||
1520 | def _object_find(self, oname, namespaces=None): |
|
1532 | def _object_find(self, oname, namespaces=None): | |
1521 | """Find an object and return a struct with info about it.""" |
|
1533 | """Find an object and return a struct with info about it.""" | |
1522 | return Struct(self._ofind(oname, namespaces)) |
|
1534 | return Struct(self._ofind(oname, namespaces)) | |
1523 |
|
1535 | |||
1524 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1536 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1525 | """Generic interface to the inspector system. |
|
1537 | """Generic interface to the inspector system. | |
1526 |
|
1538 | |||
1527 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1539 | This function is meant to be called by pdef, pdoc & friends.""" | |
1528 | info = self._object_find(oname, namespaces) |
|
1540 | info = self._object_find(oname, namespaces) | |
1529 | if info.found: |
|
1541 | if info.found: | |
1530 | pmethod = getattr(self.inspector, meth) |
|
1542 | pmethod = getattr(self.inspector, meth) | |
1531 |
formatter = format_screen if info.ismagic else |
|
1543 | formatter = format_screen if info.ismagic else docformat | |
1532 | if meth == 'pdoc': |
|
1544 | if meth == 'pdoc': | |
1533 | pmethod(info.obj, oname, formatter) |
|
1545 | pmethod(info.obj, oname, formatter) | |
1534 | elif meth == 'pinfo': |
|
1546 | elif meth == 'pinfo': | |
1535 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1547 | pmethod(info.obj, oname, formatter, info, **kw) | |
1536 | else: |
|
1548 | else: | |
1537 | pmethod(info.obj, oname) |
|
1549 | pmethod(info.obj, oname) | |
1538 | else: |
|
1550 | else: | |
1539 | print('Object `%s` not found.' % oname) |
|
1551 | print('Object `%s` not found.' % oname) | |
1540 | return 'not found' # so callers can take other action |
|
1552 | return 'not found' # so callers can take other action | |
1541 |
|
1553 | |||
1542 | def object_inspect(self, oname, detail_level=0): |
|
1554 | def object_inspect(self, oname, detail_level=0): | |
1543 | """Get object info about oname""" |
|
1555 | """Get object info about oname""" | |
1544 | with self.builtin_trap: |
|
1556 | with self.builtin_trap: | |
1545 | info = self._object_find(oname) |
|
1557 | info = self._object_find(oname) | |
1546 | if info.found: |
|
1558 | if info.found: | |
1547 | return self.inspector.info(info.obj, oname, info=info, |
|
1559 | return self.inspector.info(info.obj, oname, info=info, | |
1548 | detail_level=detail_level |
|
1560 | detail_level=detail_level | |
1549 | ) |
|
1561 | ) | |
1550 | else: |
|
1562 | else: | |
1551 | return oinspect.object_info(name=oname, found=False) |
|
1563 | return oinspect.object_info(name=oname, found=False) | |
1552 |
|
1564 | |||
1553 | def object_inspect_text(self, oname, detail_level=0): |
|
1565 | def object_inspect_text(self, oname, detail_level=0): | |
1554 | """Get object info as formatted text""" |
|
1566 | """Get object info as formatted text""" | |
1555 | with self.builtin_trap: |
|
1567 | with self.builtin_trap: | |
1556 | info = self._object_find(oname) |
|
1568 | info = self._object_find(oname) | |
1557 | if info.found: |
|
1569 | if info.found: | |
1558 | return self.inspector._format_info(info.obj, oname, info=info, |
|
1570 | return self.inspector._format_info(info.obj, oname, info=info, | |
1559 | detail_level=detail_level |
|
1571 | detail_level=detail_level | |
1560 | ) |
|
1572 | ) | |
1561 | else: |
|
1573 | else: | |
1562 | raise KeyError(oname) |
|
1574 | raise KeyError(oname) | |
1563 |
|
1575 | |||
1564 | #------------------------------------------------------------------------- |
|
1576 | #------------------------------------------------------------------------- | |
1565 | # Things related to history management |
|
1577 | # Things related to history management | |
1566 | #------------------------------------------------------------------------- |
|
1578 | #------------------------------------------------------------------------- | |
1567 |
|
1579 | |||
1568 | def init_history(self): |
|
1580 | def init_history(self): | |
1569 | """Sets up the command history, and starts regular autosaves.""" |
|
1581 | """Sets up the command history, and starts regular autosaves.""" | |
1570 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1582 | self.history_manager = HistoryManager(shell=self, parent=self) | |
1571 | self.configurables.append(self.history_manager) |
|
1583 | self.configurables.append(self.history_manager) | |
1572 |
|
1584 | |||
1573 | #------------------------------------------------------------------------- |
|
1585 | #------------------------------------------------------------------------- | |
1574 | # Things related to exception handling and tracebacks (not debugging) |
|
1586 | # Things related to exception handling and tracebacks (not debugging) | |
1575 | #------------------------------------------------------------------------- |
|
1587 | #------------------------------------------------------------------------- | |
1576 |
|
1588 | |||
1577 | debugger_cls = Pdb |
|
1589 | debugger_cls = Pdb | |
1578 |
|
1590 | |||
1579 | def init_traceback_handlers(self, custom_exceptions): |
|
1591 | def init_traceback_handlers(self, custom_exceptions): | |
1580 | # Syntax error handler. |
|
1592 | # Syntax error handler. | |
1581 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1593 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1582 |
|
1594 | |||
1583 | # The interactive one is initialized with an offset, meaning we always |
|
1595 | # The interactive one is initialized with an offset, meaning we always | |
1584 | # want to remove the topmost item in the traceback, which is our own |
|
1596 | # want to remove the topmost item in the traceback, which is our own | |
1585 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1597 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1586 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1598 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1587 | color_scheme='NoColor', |
|
1599 | color_scheme='NoColor', | |
1588 | tb_offset = 1, |
|
1600 | tb_offset = 1, | |
1589 | check_cache=check_linecache_ipython, |
|
1601 | check_cache=check_linecache_ipython, | |
1590 | debugger_cls=self.debugger_cls) |
|
1602 | debugger_cls=self.debugger_cls) | |
1591 |
|
1603 | |||
1592 | # The instance will store a pointer to the system-wide exception hook, |
|
1604 | # The instance will store a pointer to the system-wide exception hook, | |
1593 | # so that runtime code (such as magics) can access it. This is because |
|
1605 | # so that runtime code (such as magics) can access it. This is because | |
1594 | # during the read-eval loop, it may get temporarily overwritten. |
|
1606 | # during the read-eval loop, it may get temporarily overwritten. | |
1595 | self.sys_excepthook = sys.excepthook |
|
1607 | self.sys_excepthook = sys.excepthook | |
1596 |
|
1608 | |||
1597 | # and add any custom exception handlers the user may have specified |
|
1609 | # and add any custom exception handlers the user may have specified | |
1598 | self.set_custom_exc(*custom_exceptions) |
|
1610 | self.set_custom_exc(*custom_exceptions) | |
1599 |
|
1611 | |||
1600 | # Set the exception mode |
|
1612 | # Set the exception mode | |
1601 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1613 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1602 |
|
1614 | |||
1603 | def set_custom_exc(self, exc_tuple, handler): |
|
1615 | def set_custom_exc(self, exc_tuple, handler): | |
1604 | """set_custom_exc(exc_tuple, handler) |
|
1616 | """set_custom_exc(exc_tuple, handler) | |
1605 |
|
1617 | |||
1606 | Set a custom exception handler, which will be called if any of the |
|
1618 | Set a custom exception handler, which will be called if any of the | |
1607 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1619 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1608 | run_code() method). |
|
1620 | run_code() method). | |
1609 |
|
1621 | |||
1610 | Parameters |
|
1622 | Parameters | |
1611 | ---------- |
|
1623 | ---------- | |
1612 |
|
1624 | |||
1613 | exc_tuple : tuple of exception classes |
|
1625 | exc_tuple : tuple of exception classes | |
1614 | A *tuple* of exception classes, for which to call the defined |
|
1626 | A *tuple* of exception classes, for which to call the defined | |
1615 | handler. It is very important that you use a tuple, and NOT A |
|
1627 | handler. It is very important that you use a tuple, and NOT A | |
1616 | LIST here, because of the way Python's except statement works. If |
|
1628 | LIST here, because of the way Python's except statement works. If | |
1617 | you only want to trap a single exception, use a singleton tuple:: |
|
1629 | you only want to trap a single exception, use a singleton tuple:: | |
1618 |
|
1630 | |||
1619 | exc_tuple == (MyCustomException,) |
|
1631 | exc_tuple == (MyCustomException,) | |
1620 |
|
1632 | |||
1621 | handler : callable |
|
1633 | handler : callable | |
1622 | handler must have the following signature:: |
|
1634 | handler must have the following signature:: | |
1623 |
|
1635 | |||
1624 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1636 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1625 | ... |
|
1637 | ... | |
1626 | return structured_traceback |
|
1638 | return structured_traceback | |
1627 |
|
1639 | |||
1628 | Your handler must return a structured traceback (a list of strings), |
|
1640 | Your handler must return a structured traceback (a list of strings), | |
1629 | or None. |
|
1641 | or None. | |
1630 |
|
1642 | |||
1631 | This will be made into an instance method (via types.MethodType) |
|
1643 | This will be made into an instance method (via types.MethodType) | |
1632 | of IPython itself, and it will be called if any of the exceptions |
|
1644 | of IPython itself, and it will be called if any of the exceptions | |
1633 | listed in the exc_tuple are caught. If the handler is None, an |
|
1645 | listed in the exc_tuple are caught. If the handler is None, an | |
1634 | internal basic one is used, which just prints basic info. |
|
1646 | internal basic one is used, which just prints basic info. | |
1635 |
|
1647 | |||
1636 | To protect IPython from crashes, if your handler ever raises an |
|
1648 | To protect IPython from crashes, if your handler ever raises an | |
1637 | exception or returns an invalid result, it will be immediately |
|
1649 | exception or returns an invalid result, it will be immediately | |
1638 | disabled. |
|
1650 | disabled. | |
1639 |
|
1651 | |||
1640 | WARNING: by putting in your own exception handler into IPython's main |
|
1652 | WARNING: by putting in your own exception handler into IPython's main | |
1641 | execution loop, you run a very good chance of nasty crashes. This |
|
1653 | execution loop, you run a very good chance of nasty crashes. This | |
1642 | facility should only be used if you really know what you are doing.""" |
|
1654 | facility should only be used if you really know what you are doing.""" | |
1643 |
|
1655 | |||
1644 | assert type(exc_tuple)==type(()) , \ |
|
1656 | assert type(exc_tuple)==type(()) , \ | |
1645 | "The custom exceptions must be given AS A TUPLE." |
|
1657 | "The custom exceptions must be given AS A TUPLE." | |
1646 |
|
1658 | |||
1647 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1659 | def dummy_handler(self, etype, value, tb, tb_offset=None): | |
1648 | print('*** Simple custom exception handler ***') |
|
1660 | print('*** Simple custom exception handler ***') | |
1649 | print('Exception type :',etype) |
|
1661 | print('Exception type :',etype) | |
1650 | print('Exception value:',value) |
|
1662 | print('Exception value:',value) | |
1651 | print('Traceback :',tb) |
|
1663 | print('Traceback :',tb) | |
1652 | #print 'Source code :','\n'.join(self.buffer) |
|
1664 | #print 'Source code :','\n'.join(self.buffer) | |
1653 |
|
1665 | |||
1654 | def validate_stb(stb): |
|
1666 | def validate_stb(stb): | |
1655 | """validate structured traceback return type |
|
1667 | """validate structured traceback return type | |
1656 |
|
1668 | |||
1657 | return type of CustomTB *should* be a list of strings, but allow |
|
1669 | return type of CustomTB *should* be a list of strings, but allow | |
1658 | single strings or None, which are harmless. |
|
1670 | single strings or None, which are harmless. | |
1659 |
|
1671 | |||
1660 | This function will *always* return a list of strings, |
|
1672 | This function will *always* return a list of strings, | |
1661 | and will raise a TypeError if stb is inappropriate. |
|
1673 | and will raise a TypeError if stb is inappropriate. | |
1662 | """ |
|
1674 | """ | |
1663 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1675 | msg = "CustomTB must return list of strings, not %r" % stb | |
1664 | if stb is None: |
|
1676 | if stb is None: | |
1665 | return [] |
|
1677 | return [] | |
1666 | elif isinstance(stb, string_types): |
|
1678 | elif isinstance(stb, string_types): | |
1667 | return [stb] |
|
1679 | return [stb] | |
1668 | elif not isinstance(stb, list): |
|
1680 | elif not isinstance(stb, list): | |
1669 | raise TypeError(msg) |
|
1681 | raise TypeError(msg) | |
1670 | # it's a list |
|
1682 | # it's a list | |
1671 | for line in stb: |
|
1683 | for line in stb: | |
1672 | # check every element |
|
1684 | # check every element | |
1673 | if not isinstance(line, string_types): |
|
1685 | if not isinstance(line, string_types): | |
1674 | raise TypeError(msg) |
|
1686 | raise TypeError(msg) | |
1675 | return stb |
|
1687 | return stb | |
1676 |
|
1688 | |||
1677 | if handler is None: |
|
1689 | if handler is None: | |
1678 | wrapped = dummy_handler |
|
1690 | wrapped = dummy_handler | |
1679 | else: |
|
1691 | else: | |
1680 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1692 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1681 | """wrap CustomTB handler, to protect IPython from user code |
|
1693 | """wrap CustomTB handler, to protect IPython from user code | |
1682 |
|
1694 | |||
1683 | This makes it harder (but not impossible) for custom exception |
|
1695 | This makes it harder (but not impossible) for custom exception | |
1684 | handlers to crash IPython. |
|
1696 | handlers to crash IPython. | |
1685 | """ |
|
1697 | """ | |
1686 | try: |
|
1698 | try: | |
1687 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1699 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1688 | return validate_stb(stb) |
|
1700 | return validate_stb(stb) | |
1689 | except: |
|
1701 | except: | |
1690 | # clear custom handler immediately |
|
1702 | # clear custom handler immediately | |
1691 | self.set_custom_exc((), None) |
|
1703 | self.set_custom_exc((), None) | |
1692 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1704 | print("Custom TB Handler failed, unregistering", file=sys.stderr) | |
1693 | # show the exception in handler first |
|
1705 | # show the exception in handler first | |
1694 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1706 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1695 | print(self.InteractiveTB.stb2text(stb)) |
|
1707 | print(self.InteractiveTB.stb2text(stb)) | |
1696 | print("The original exception:") |
|
1708 | print("The original exception:") | |
1697 | stb = self.InteractiveTB.structured_traceback( |
|
1709 | stb = self.InteractiveTB.structured_traceback( | |
1698 | (etype,value,tb), tb_offset=tb_offset |
|
1710 | (etype,value,tb), tb_offset=tb_offset | |
1699 | ) |
|
1711 | ) | |
1700 | return stb |
|
1712 | return stb | |
1701 |
|
1713 | |||
1702 | self.CustomTB = types.MethodType(wrapped,self) |
|
1714 | self.CustomTB = types.MethodType(wrapped,self) | |
1703 | self.custom_exceptions = exc_tuple |
|
1715 | self.custom_exceptions = exc_tuple | |
1704 |
|
1716 | |||
1705 | def excepthook(self, etype, value, tb): |
|
1717 | def excepthook(self, etype, value, tb): | |
1706 | """One more defense for GUI apps that call sys.excepthook. |
|
1718 | """One more defense for GUI apps that call sys.excepthook. | |
1707 |
|
1719 | |||
1708 | GUI frameworks like wxPython trap exceptions and call |
|
1720 | GUI frameworks like wxPython trap exceptions and call | |
1709 | sys.excepthook themselves. I guess this is a feature that |
|
1721 | sys.excepthook themselves. I guess this is a feature that | |
1710 | enables them to keep running after exceptions that would |
|
1722 | enables them to keep running after exceptions that would | |
1711 | otherwise kill their mainloop. This is a bother for IPython |
|
1723 | otherwise kill their mainloop. This is a bother for IPython | |
1712 | which excepts to catch all of the program exceptions with a try: |
|
1724 | which excepts to catch all of the program exceptions with a try: | |
1713 | except: statement. |
|
1725 | except: statement. | |
1714 |
|
1726 | |||
1715 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1727 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1716 | any app directly invokes sys.excepthook, it will look to the user like |
|
1728 | any app directly invokes sys.excepthook, it will look to the user like | |
1717 | IPython crashed. In order to work around this, we can disable the |
|
1729 | IPython crashed. In order to work around this, we can disable the | |
1718 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1730 | CrashHandler and replace it with this excepthook instead, which prints a | |
1719 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1731 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1720 | call sys.excepthook will generate a regular-looking exception from |
|
1732 | call sys.excepthook will generate a regular-looking exception from | |
1721 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1733 | IPython, and the CrashHandler will only be triggered by real IPython | |
1722 | crashes. |
|
1734 | crashes. | |
1723 |
|
1735 | |||
1724 | This hook should be used sparingly, only in places which are not likely |
|
1736 | This hook should be used sparingly, only in places which are not likely | |
1725 | to be true IPython errors. |
|
1737 | to be true IPython errors. | |
1726 | """ |
|
1738 | """ | |
1727 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1739 | self.showtraceback((etype, value, tb), tb_offset=0) | |
1728 |
|
1740 | |||
1729 | def _get_exc_info(self, exc_tuple=None): |
|
1741 | def _get_exc_info(self, exc_tuple=None): | |
1730 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1742 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. | |
1731 |
|
1743 | |||
1732 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1744 | Ensures sys.last_type,value,traceback hold the exc_info we found, | |
1733 | from whichever source. |
|
1745 | from whichever source. | |
1734 |
|
1746 | |||
1735 | raises ValueError if none of these contain any information |
|
1747 | raises ValueError if none of these contain any information | |
1736 | """ |
|
1748 | """ | |
1737 | if exc_tuple is None: |
|
1749 | if exc_tuple is None: | |
1738 | etype, value, tb = sys.exc_info() |
|
1750 | etype, value, tb = sys.exc_info() | |
1739 | else: |
|
1751 | else: | |
1740 | etype, value, tb = exc_tuple |
|
1752 | etype, value, tb = exc_tuple | |
1741 |
|
1753 | |||
1742 | if etype is None: |
|
1754 | if etype is None: | |
1743 | if hasattr(sys, 'last_type'): |
|
1755 | if hasattr(sys, 'last_type'): | |
1744 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1756 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1745 | sys.last_traceback |
|
1757 | sys.last_traceback | |
1746 |
|
1758 | |||
1747 | if etype is None: |
|
1759 | if etype is None: | |
1748 | raise ValueError("No exception to find") |
|
1760 | raise ValueError("No exception to find") | |
1749 |
|
1761 | |||
1750 | # Now store the exception info in sys.last_type etc. |
|
1762 | # Now store the exception info in sys.last_type etc. | |
1751 | # WARNING: these variables are somewhat deprecated and not |
|
1763 | # WARNING: these variables are somewhat deprecated and not | |
1752 | # necessarily safe to use in a threaded environment, but tools |
|
1764 | # necessarily safe to use in a threaded environment, but tools | |
1753 | # like pdb depend on their existence, so let's set them. If we |
|
1765 | # like pdb depend on their existence, so let's set them. If we | |
1754 | # find problems in the field, we'll need to revisit their use. |
|
1766 | # find problems in the field, we'll need to revisit their use. | |
1755 | sys.last_type = etype |
|
1767 | sys.last_type = etype | |
1756 | sys.last_value = value |
|
1768 | sys.last_value = value | |
1757 | sys.last_traceback = tb |
|
1769 | sys.last_traceback = tb | |
1758 |
|
1770 | |||
1759 | return etype, value, tb |
|
1771 | return etype, value, tb | |
1760 |
|
1772 | |||
1761 | def show_usage_error(self, exc): |
|
1773 | def show_usage_error(self, exc): | |
1762 | """Show a short message for UsageErrors |
|
1774 | """Show a short message for UsageErrors | |
1763 |
|
1775 | |||
1764 | These are special exceptions that shouldn't show a traceback. |
|
1776 | These are special exceptions that shouldn't show a traceback. | |
1765 | """ |
|
1777 | """ | |
1766 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1778 | print("UsageError: %s" % exc, file=sys.stderr) | |
1767 |
|
1779 | |||
1768 | def get_exception_only(self, exc_tuple=None): |
|
1780 | def get_exception_only(self, exc_tuple=None): | |
1769 | """ |
|
1781 | """ | |
1770 | Return as a string (ending with a newline) the exception that |
|
1782 | Return as a string (ending with a newline) the exception that | |
1771 | just occurred, without any traceback. |
|
1783 | just occurred, without any traceback. | |
1772 | """ |
|
1784 | """ | |
1773 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1785 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1774 | msg = traceback.format_exception_only(etype, value) |
|
1786 | msg = traceback.format_exception_only(etype, value) | |
1775 | return ''.join(msg) |
|
1787 | return ''.join(msg) | |
1776 |
|
1788 | |||
1777 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1789 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, | |
1778 | exception_only=False): |
|
1790 | exception_only=False): | |
1779 | """Display the exception that just occurred. |
|
1791 | """Display the exception that just occurred. | |
1780 |
|
1792 | |||
1781 | If nothing is known about the exception, this is the method which |
|
1793 | If nothing is known about the exception, this is the method which | |
1782 | should be used throughout the code for presenting user tracebacks, |
|
1794 | should be used throughout the code for presenting user tracebacks, | |
1783 | rather than directly invoking the InteractiveTB object. |
|
1795 | rather than directly invoking the InteractiveTB object. | |
1784 |
|
1796 | |||
1785 | A specific showsyntaxerror() also exists, but this method can take |
|
1797 | A specific showsyntaxerror() also exists, but this method can take | |
1786 | care of calling it if needed, so unless you are explicitly catching a |
|
1798 | care of calling it if needed, so unless you are explicitly catching a | |
1787 | SyntaxError exception, don't try to analyze the stack manually and |
|
1799 | SyntaxError exception, don't try to analyze the stack manually and | |
1788 | simply call this method.""" |
|
1800 | simply call this method.""" | |
1789 |
|
1801 | |||
1790 | try: |
|
1802 | try: | |
1791 | try: |
|
1803 | try: | |
1792 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1804 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1793 | except ValueError: |
|
1805 | except ValueError: | |
1794 | print('No traceback available to show.', file=sys.stderr) |
|
1806 | print('No traceback available to show.', file=sys.stderr) | |
1795 | return |
|
1807 | return | |
1796 |
|
1808 | |||
1797 | if issubclass(etype, SyntaxError): |
|
1809 | if issubclass(etype, SyntaxError): | |
1798 | # Though this won't be called by syntax errors in the input |
|
1810 | # Though this won't be called by syntax errors in the input | |
1799 | # line, there may be SyntaxError cases with imported code. |
|
1811 | # line, there may be SyntaxError cases with imported code. | |
1800 | self.showsyntaxerror(filename) |
|
1812 | self.showsyntaxerror(filename) | |
1801 | elif etype is UsageError: |
|
1813 | elif etype is UsageError: | |
1802 | self.show_usage_error(value) |
|
1814 | self.show_usage_error(value) | |
1803 | else: |
|
1815 | else: | |
1804 | if exception_only: |
|
1816 | if exception_only: | |
1805 | stb = ['An exception has occurred, use %tb to see ' |
|
1817 | stb = ['An exception has occurred, use %tb to see ' | |
1806 | 'the full traceback.\n'] |
|
1818 | 'the full traceback.\n'] | |
1807 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1819 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1808 | value)) |
|
1820 | value)) | |
1809 | else: |
|
1821 | else: | |
1810 | try: |
|
1822 | try: | |
1811 | # Exception classes can customise their traceback - we |
|
1823 | # Exception classes can customise their traceback - we | |
1812 | # use this in IPython.parallel for exceptions occurring |
|
1824 | # use this in IPython.parallel for exceptions occurring | |
1813 | # in the engines. This should return a list of strings. |
|
1825 | # in the engines. This should return a list of strings. | |
1814 | stb = value._render_traceback_() |
|
1826 | stb = value._render_traceback_() | |
1815 | except Exception: |
|
1827 | except Exception: | |
1816 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1828 | stb = self.InteractiveTB.structured_traceback(etype, | |
1817 | value, tb, tb_offset=tb_offset) |
|
1829 | value, tb, tb_offset=tb_offset) | |
1818 |
|
1830 | |||
1819 | self._showtraceback(etype, value, stb) |
|
1831 | self._showtraceback(etype, value, stb) | |
1820 | if self.call_pdb: |
|
1832 | if self.call_pdb: | |
1821 | # drop into debugger |
|
1833 | # drop into debugger | |
1822 | self.debugger(force=True) |
|
1834 | self.debugger(force=True) | |
1823 | return |
|
1835 | return | |
1824 |
|
1836 | |||
1825 | # Actually show the traceback |
|
1837 | # Actually show the traceback | |
1826 | self._showtraceback(etype, value, stb) |
|
1838 | self._showtraceback(etype, value, stb) | |
1827 |
|
1839 | |||
1828 | except KeyboardInterrupt: |
|
1840 | except KeyboardInterrupt: | |
1829 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
1841 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
1830 |
|
1842 | |||
1831 | def _showtraceback(self, etype, evalue, stb): |
|
1843 | def _showtraceback(self, etype, evalue, stb): | |
1832 | """Actually show a traceback. |
|
1844 | """Actually show a traceback. | |
1833 |
|
1845 | |||
1834 | Subclasses may override this method to put the traceback on a different |
|
1846 | Subclasses may override this method to put the traceback on a different | |
1835 | place, like a side channel. |
|
1847 | place, like a side channel. | |
1836 | """ |
|
1848 | """ | |
1837 | print(self.InteractiveTB.stb2text(stb)) |
|
1849 | print(self.InteractiveTB.stb2text(stb)) | |
1838 |
|
1850 | |||
1839 | def showsyntaxerror(self, filename=None): |
|
1851 | def showsyntaxerror(self, filename=None): | |
1840 | """Display the syntax error that just occurred. |
|
1852 | """Display the syntax error that just occurred. | |
1841 |
|
1853 | |||
1842 | This doesn't display a stack trace because there isn't one. |
|
1854 | This doesn't display a stack trace because there isn't one. | |
1843 |
|
1855 | |||
1844 | If a filename is given, it is stuffed in the exception instead |
|
1856 | If a filename is given, it is stuffed in the exception instead | |
1845 | of what was there before (because Python's parser always uses |
|
1857 | of what was there before (because Python's parser always uses | |
1846 | "<string>" when reading from a string). |
|
1858 | "<string>" when reading from a string). | |
1847 | """ |
|
1859 | """ | |
1848 | etype, value, last_traceback = self._get_exc_info() |
|
1860 | etype, value, last_traceback = self._get_exc_info() | |
1849 |
|
1861 | |||
1850 | if filename and issubclass(etype, SyntaxError): |
|
1862 | if filename and issubclass(etype, SyntaxError): | |
1851 | try: |
|
1863 | try: | |
1852 | value.filename = filename |
|
1864 | value.filename = filename | |
1853 | except: |
|
1865 | except: | |
1854 | # Not the format we expect; leave it alone |
|
1866 | # Not the format we expect; leave it alone | |
1855 | pass |
|
1867 | pass | |
1856 |
|
1868 | |||
1857 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1869 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1858 | self._showtraceback(etype, value, stb) |
|
1870 | self._showtraceback(etype, value, stb) | |
1859 |
|
1871 | |||
1860 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1872 | # This is overridden in TerminalInteractiveShell to show a message about | |
1861 | # the %paste magic. |
|
1873 | # the %paste magic. | |
1862 | def showindentationerror(self): |
|
1874 | def showindentationerror(self): | |
1863 | """Called by run_cell when there's an IndentationError in code entered |
|
1875 | """Called by run_cell when there's an IndentationError in code entered | |
1864 | at the prompt. |
|
1876 | at the prompt. | |
1865 |
|
1877 | |||
1866 | This is overridden in TerminalInteractiveShell to show a message about |
|
1878 | This is overridden in TerminalInteractiveShell to show a message about | |
1867 | the %paste magic.""" |
|
1879 | the %paste magic.""" | |
1868 | self.showsyntaxerror() |
|
1880 | self.showsyntaxerror() | |
1869 |
|
1881 | |||
1870 | #------------------------------------------------------------------------- |
|
1882 | #------------------------------------------------------------------------- | |
1871 | # Things related to readline |
|
1883 | # Things related to readline | |
1872 | #------------------------------------------------------------------------- |
|
1884 | #------------------------------------------------------------------------- | |
1873 |
|
1885 | |||
1874 | def init_readline(self): |
|
1886 | def init_readline(self): | |
1875 | """Moved to terminal subclass, here only to simplify the init logic.""" |
|
1887 | """Moved to terminal subclass, here only to simplify the init logic.""" | |
1876 | self.readline = None |
|
1888 | self.readline = None | |
1877 | # Set a number of methods that depend on readline to be no-op |
|
1889 | # Set a number of methods that depend on readline to be no-op | |
1878 | self.readline_no_record = NoOpContext() |
|
1890 | self.readline_no_record = NoOpContext() | |
1879 | self.set_readline_completer = no_op |
|
1891 | self.set_readline_completer = no_op | |
1880 | self.set_custom_completer = no_op |
|
1892 | self.set_custom_completer = no_op | |
1881 |
|
1893 | |||
1882 | @skip_doctest |
|
1894 | @skip_doctest | |
1883 | def set_next_input(self, s, replace=False): |
|
1895 | def set_next_input(self, s, replace=False): | |
1884 | """ Sets the 'default' input string for the next command line. |
|
1896 | """ Sets the 'default' input string for the next command line. | |
1885 |
|
1897 | |||
1886 | Example:: |
|
1898 | Example:: | |
1887 |
|
1899 | |||
1888 | In [1]: _ip.set_next_input("Hello Word") |
|
1900 | In [1]: _ip.set_next_input("Hello Word") | |
1889 | In [2]: Hello Word_ # cursor is here |
|
1901 | In [2]: Hello Word_ # cursor is here | |
1890 | """ |
|
1902 | """ | |
1891 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1903 | self.rl_next_input = py3compat.cast_bytes_py2(s) | |
1892 |
|
1904 | |||
1893 | def _indent_current_str(self): |
|
1905 | def _indent_current_str(self): | |
1894 | """return the current level of indentation as a string""" |
|
1906 | """return the current level of indentation as a string""" | |
1895 | return self.input_splitter.indent_spaces * ' ' |
|
1907 | return self.input_splitter.indent_spaces * ' ' | |
1896 |
|
1908 | |||
1897 | #------------------------------------------------------------------------- |
|
1909 | #------------------------------------------------------------------------- | |
1898 | # Things related to text completion |
|
1910 | # Things related to text completion | |
1899 | #------------------------------------------------------------------------- |
|
1911 | #------------------------------------------------------------------------- | |
1900 |
|
1912 | |||
1901 | def init_completer(self): |
|
1913 | def init_completer(self): | |
1902 | """Initialize the completion machinery. |
|
1914 | """Initialize the completion machinery. | |
1903 |
|
1915 | |||
1904 | This creates completion machinery that can be used by client code, |
|
1916 | This creates completion machinery that can be used by client code, | |
1905 | either interactively in-process (typically triggered by the readline |
|
1917 | either interactively in-process (typically triggered by the readline | |
1906 | library), programmatically (such as in test suites) or out-of-process |
|
1918 | library), programmatically (such as in test suites) or out-of-process | |
1907 | (typically over the network by remote frontends). |
|
1919 | (typically over the network by remote frontends). | |
1908 | """ |
|
1920 | """ | |
1909 | from IPython.core.completer import IPCompleter |
|
1921 | from IPython.core.completer import IPCompleter | |
1910 | from IPython.core.completerlib import (module_completer, |
|
1922 | from IPython.core.completerlib import (module_completer, | |
1911 | magic_run_completer, cd_completer, reset_completer) |
|
1923 | magic_run_completer, cd_completer, reset_completer) | |
1912 |
|
1924 | |||
1913 | self.Completer = IPCompleter(shell=self, |
|
1925 | self.Completer = IPCompleter(shell=self, | |
1914 | namespace=self.user_ns, |
|
1926 | namespace=self.user_ns, | |
1915 | global_namespace=self.user_global_ns, |
|
1927 | global_namespace=self.user_global_ns, | |
1916 | use_readline=self.has_readline, |
|
1928 | use_readline=self.has_readline, | |
1917 | parent=self, |
|
1929 | parent=self, | |
1918 | ) |
|
1930 | ) | |
1919 | self.configurables.append(self.Completer) |
|
1931 | self.configurables.append(self.Completer) | |
1920 |
|
1932 | |||
1921 | # Add custom completers to the basic ones built into IPCompleter |
|
1933 | # Add custom completers to the basic ones built into IPCompleter | |
1922 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1934 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1923 | self.strdispatchers['complete_command'] = sdisp |
|
1935 | self.strdispatchers['complete_command'] = sdisp | |
1924 | self.Completer.custom_completers = sdisp |
|
1936 | self.Completer.custom_completers = sdisp | |
1925 |
|
1937 | |||
1926 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1938 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1927 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1939 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1928 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
1940 | self.set_hook('complete_command', module_completer, str_key = '%aimport') | |
1929 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1941 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1930 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1942 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1931 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1943 | self.set_hook('complete_command', reset_completer, str_key = '%reset') | |
1932 |
|
1944 | |||
1933 |
|
1945 | |||
1934 | @skip_doctest_py2 |
|
1946 | @skip_doctest_py2 | |
1935 | def complete(self, text, line=None, cursor_pos=None): |
|
1947 | def complete(self, text, line=None, cursor_pos=None): | |
1936 | """Return the completed text and a list of completions. |
|
1948 | """Return the completed text and a list of completions. | |
1937 |
|
1949 | |||
1938 | Parameters |
|
1950 | Parameters | |
1939 | ---------- |
|
1951 | ---------- | |
1940 |
|
1952 | |||
1941 | text : string |
|
1953 | text : string | |
1942 | A string of text to be completed on. It can be given as empty and |
|
1954 | A string of text to be completed on. It can be given as empty and | |
1943 | instead a line/position pair are given. In this case, the |
|
1955 | instead a line/position pair are given. In this case, the | |
1944 | completer itself will split the line like readline does. |
|
1956 | completer itself will split the line like readline does. | |
1945 |
|
1957 | |||
1946 | line : string, optional |
|
1958 | line : string, optional | |
1947 | The complete line that text is part of. |
|
1959 | The complete line that text is part of. | |
1948 |
|
1960 | |||
1949 | cursor_pos : int, optional |
|
1961 | cursor_pos : int, optional | |
1950 | The position of the cursor on the input line. |
|
1962 | The position of the cursor on the input line. | |
1951 |
|
1963 | |||
1952 | Returns |
|
1964 | Returns | |
1953 | ------- |
|
1965 | ------- | |
1954 | text : string |
|
1966 | text : string | |
1955 | The actual text that was completed. |
|
1967 | The actual text that was completed. | |
1956 |
|
1968 | |||
1957 | matches : list |
|
1969 | matches : list | |
1958 | A sorted list with all possible completions. |
|
1970 | A sorted list with all possible completions. | |
1959 |
|
1971 | |||
1960 | The optional arguments allow the completion to take more context into |
|
1972 | The optional arguments allow the completion to take more context into | |
1961 | account, and are part of the low-level completion API. |
|
1973 | account, and are part of the low-level completion API. | |
1962 |
|
1974 | |||
1963 | This is a wrapper around the completion mechanism, similar to what |
|
1975 | This is a wrapper around the completion mechanism, similar to what | |
1964 | readline does at the command line when the TAB key is hit. By |
|
1976 | readline does at the command line when the TAB key is hit. By | |
1965 | exposing it as a method, it can be used by other non-readline |
|
1977 | exposing it as a method, it can be used by other non-readline | |
1966 | environments (such as GUIs) for text completion. |
|
1978 | environments (such as GUIs) for text completion. | |
1967 |
|
1979 | |||
1968 | Simple usage example: |
|
1980 | Simple usage example: | |
1969 |
|
1981 | |||
1970 | In [1]: x = 'hello' |
|
1982 | In [1]: x = 'hello' | |
1971 |
|
1983 | |||
1972 | In [2]: _ip.complete('x.l') |
|
1984 | In [2]: _ip.complete('x.l') | |
1973 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1985 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1974 | """ |
|
1986 | """ | |
1975 |
|
1987 | |||
1976 | # Inject names into __builtin__ so we can complete on the added names. |
|
1988 | # Inject names into __builtin__ so we can complete on the added names. | |
1977 | with self.builtin_trap: |
|
1989 | with self.builtin_trap: | |
1978 | return self.Completer.complete(text, line, cursor_pos) |
|
1990 | return self.Completer.complete(text, line, cursor_pos) | |
1979 |
|
1991 | |||
1980 | def set_custom_completer(self, completer, pos=0): |
|
1992 | def set_custom_completer(self, completer, pos=0): | |
1981 | """Adds a new custom completer function. |
|
1993 | """Adds a new custom completer function. | |
1982 |
|
1994 | |||
1983 | The position argument (defaults to 0) is the index in the completers |
|
1995 | The position argument (defaults to 0) is the index in the completers | |
1984 | list where you want the completer to be inserted.""" |
|
1996 | list where you want the completer to be inserted.""" | |
1985 |
|
1997 | |||
1986 | newcomp = types.MethodType(completer,self.Completer) |
|
1998 | newcomp = types.MethodType(completer,self.Completer) | |
1987 | self.Completer.matchers.insert(pos,newcomp) |
|
1999 | self.Completer.matchers.insert(pos,newcomp) | |
1988 |
|
2000 | |||
1989 | def set_completer_frame(self, frame=None): |
|
2001 | def set_completer_frame(self, frame=None): | |
1990 | """Set the frame of the completer.""" |
|
2002 | """Set the frame of the completer.""" | |
1991 | if frame: |
|
2003 | if frame: | |
1992 | self.Completer.namespace = frame.f_locals |
|
2004 | self.Completer.namespace = frame.f_locals | |
1993 | self.Completer.global_namespace = frame.f_globals |
|
2005 | self.Completer.global_namespace = frame.f_globals | |
1994 | else: |
|
2006 | else: | |
1995 | self.Completer.namespace = self.user_ns |
|
2007 | self.Completer.namespace = self.user_ns | |
1996 | self.Completer.global_namespace = self.user_global_ns |
|
2008 | self.Completer.global_namespace = self.user_global_ns | |
1997 |
|
2009 | |||
1998 | #------------------------------------------------------------------------- |
|
2010 | #------------------------------------------------------------------------- | |
1999 | # Things related to magics |
|
2011 | # Things related to magics | |
2000 | #------------------------------------------------------------------------- |
|
2012 | #------------------------------------------------------------------------- | |
2001 |
|
2013 | |||
2002 | def init_magics(self): |
|
2014 | def init_magics(self): | |
2003 | from IPython.core import magics as m |
|
2015 | from IPython.core import magics as m | |
2004 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2016 | self.magics_manager = magic.MagicsManager(shell=self, | |
2005 | parent=self, |
|
2017 | parent=self, | |
2006 | user_magics=m.UserMagics(self)) |
|
2018 | user_magics=m.UserMagics(self)) | |
2007 | self.configurables.append(self.magics_manager) |
|
2019 | self.configurables.append(self.magics_manager) | |
2008 |
|
2020 | |||
2009 | # Expose as public API from the magics manager |
|
2021 | # Expose as public API from the magics manager | |
2010 | self.register_magics = self.magics_manager.register |
|
2022 | self.register_magics = self.magics_manager.register | |
2011 |
|
2023 | |||
2012 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2024 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, | |
2013 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2025 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, | |
2014 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2026 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, | |
2015 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2027 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, | |
2016 | ) |
|
2028 | ) | |
2017 |
|
2029 | |||
2018 | # Register Magic Aliases |
|
2030 | # Register Magic Aliases | |
2019 | mman = self.magics_manager |
|
2031 | mman = self.magics_manager | |
2020 | # FIXME: magic aliases should be defined by the Magics classes |
|
2032 | # FIXME: magic aliases should be defined by the Magics classes | |
2021 | # or in MagicsManager, not here |
|
2033 | # or in MagicsManager, not here | |
2022 | mman.register_alias('ed', 'edit') |
|
2034 | mman.register_alias('ed', 'edit') | |
2023 | mman.register_alias('hist', 'history') |
|
2035 | mman.register_alias('hist', 'history') | |
2024 | mman.register_alias('rep', 'recall') |
|
2036 | mman.register_alias('rep', 'recall') | |
2025 | mman.register_alias('SVG', 'svg', 'cell') |
|
2037 | mman.register_alias('SVG', 'svg', 'cell') | |
2026 | mman.register_alias('HTML', 'html', 'cell') |
|
2038 | mman.register_alias('HTML', 'html', 'cell') | |
2027 | mman.register_alias('file', 'writefile', 'cell') |
|
2039 | mman.register_alias('file', 'writefile', 'cell') | |
2028 |
|
2040 | |||
2029 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2041 | # FIXME: Move the color initialization to the DisplayHook, which | |
2030 | # should be split into a prompt manager and displayhook. We probably |
|
2042 | # should be split into a prompt manager and displayhook. We probably | |
2031 | # even need a centralize colors management object. |
|
2043 | # even need a centralize colors management object. | |
2032 | self.magic('colors %s' % self.colors) |
|
2044 | self.magic('colors %s' % self.colors) | |
2033 |
|
2045 | |||
2034 | # Defined here so that it's included in the documentation |
|
2046 | # Defined here so that it's included in the documentation | |
2035 | @functools.wraps(magic.MagicsManager.register_function) |
|
2047 | @functools.wraps(magic.MagicsManager.register_function) | |
2036 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2048 | def register_magic_function(self, func, magic_kind='line', magic_name=None): | |
2037 | self.magics_manager.register_function(func, |
|
2049 | self.magics_manager.register_function(func, | |
2038 | magic_kind=magic_kind, magic_name=magic_name) |
|
2050 | magic_kind=magic_kind, magic_name=magic_name) | |
2039 |
|
2051 | |||
2040 | def run_line_magic(self, magic_name, line): |
|
2052 | def run_line_magic(self, magic_name, line): | |
2041 | """Execute the given line magic. |
|
2053 | """Execute the given line magic. | |
2042 |
|
2054 | |||
2043 | Parameters |
|
2055 | Parameters | |
2044 | ---------- |
|
2056 | ---------- | |
2045 | magic_name : str |
|
2057 | magic_name : str | |
2046 | Name of the desired magic function, without '%' prefix. |
|
2058 | Name of the desired magic function, without '%' prefix. | |
2047 |
|
2059 | |||
2048 | line : str |
|
2060 | line : str | |
2049 | The rest of the input line as a single string. |
|
2061 | The rest of the input line as a single string. | |
2050 | """ |
|
2062 | """ | |
2051 | fn = self.find_line_magic(magic_name) |
|
2063 | fn = self.find_line_magic(magic_name) | |
2052 | if fn is None: |
|
2064 | if fn is None: | |
2053 | cm = self.find_cell_magic(magic_name) |
|
2065 | cm = self.find_cell_magic(magic_name) | |
2054 | etpl = "Line magic function `%%%s` not found%s." |
|
2066 | etpl = "Line magic function `%%%s` not found%s." | |
2055 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2067 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' | |
2056 | 'did you mean that instead?)' % magic_name ) |
|
2068 | 'did you mean that instead?)' % magic_name ) | |
2057 | error(etpl % (magic_name, extra)) |
|
2069 | error(etpl % (magic_name, extra)) | |
2058 | else: |
|
2070 | else: | |
2059 | # Note: this is the distance in the stack to the user's frame. |
|
2071 | # Note: this is the distance in the stack to the user's frame. | |
2060 | # This will need to be updated if the internal calling logic gets |
|
2072 | # This will need to be updated if the internal calling logic gets | |
2061 | # refactored, or else we'll be expanding the wrong variables. |
|
2073 | # refactored, or else we'll be expanding the wrong variables. | |
2062 | stack_depth = 2 |
|
2074 | stack_depth = 2 | |
2063 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2075 | magic_arg_s = self.var_expand(line, stack_depth) | |
2064 | # Put magic args in a list so we can call with f(*a) syntax |
|
2076 | # Put magic args in a list so we can call with f(*a) syntax | |
2065 | args = [magic_arg_s] |
|
2077 | args = [magic_arg_s] | |
2066 | kwargs = {} |
|
2078 | kwargs = {} | |
2067 | # Grab local namespace if we need it: |
|
2079 | # Grab local namespace if we need it: | |
2068 | if getattr(fn, "needs_local_scope", False): |
|
2080 | if getattr(fn, "needs_local_scope", False): | |
2069 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2081 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals | |
2070 | with self.builtin_trap: |
|
2082 | with self.builtin_trap: | |
2071 | result = fn(*args,**kwargs) |
|
2083 | result = fn(*args,**kwargs) | |
2072 | return result |
|
2084 | return result | |
2073 |
|
2085 | |||
2074 | def run_cell_magic(self, magic_name, line, cell): |
|
2086 | def run_cell_magic(self, magic_name, line, cell): | |
2075 | """Execute the given cell magic. |
|
2087 | """Execute the given cell magic. | |
2076 |
|
2088 | |||
2077 | Parameters |
|
2089 | Parameters | |
2078 | ---------- |
|
2090 | ---------- | |
2079 | magic_name : str |
|
2091 | magic_name : str | |
2080 | Name of the desired magic function, without '%' prefix. |
|
2092 | Name of the desired magic function, without '%' prefix. | |
2081 |
|
2093 | |||
2082 | line : str |
|
2094 | line : str | |
2083 | The rest of the first input line as a single string. |
|
2095 | The rest of the first input line as a single string. | |
2084 |
|
2096 | |||
2085 | cell : str |
|
2097 | cell : str | |
2086 | The body of the cell as a (possibly multiline) string. |
|
2098 | The body of the cell as a (possibly multiline) string. | |
2087 | """ |
|
2099 | """ | |
2088 | fn = self.find_cell_magic(magic_name) |
|
2100 | fn = self.find_cell_magic(magic_name) | |
2089 | if fn is None: |
|
2101 | if fn is None: | |
2090 | lm = self.find_line_magic(magic_name) |
|
2102 | lm = self.find_line_magic(magic_name) | |
2091 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2103 | etpl = "Cell magic `%%{0}` not found{1}." | |
2092 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2104 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' | |
2093 | 'did you mean that instead?)'.format(magic_name)) |
|
2105 | 'did you mean that instead?)'.format(magic_name)) | |
2094 | error(etpl.format(magic_name, extra)) |
|
2106 | error(etpl.format(magic_name, extra)) | |
2095 | elif cell == '': |
|
2107 | elif cell == '': | |
2096 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2108 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) | |
2097 | if self.find_line_magic(magic_name) is not None: |
|
2109 | if self.find_line_magic(magic_name) is not None: | |
2098 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2110 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) | |
2099 | raise UsageError(message) |
|
2111 | raise UsageError(message) | |
2100 | else: |
|
2112 | else: | |
2101 | # Note: this is the distance in the stack to the user's frame. |
|
2113 | # Note: this is the distance in the stack to the user's frame. | |
2102 | # This will need to be updated if the internal calling logic gets |
|
2114 | # This will need to be updated if the internal calling logic gets | |
2103 | # refactored, or else we'll be expanding the wrong variables. |
|
2115 | # refactored, or else we'll be expanding the wrong variables. | |
2104 | stack_depth = 2 |
|
2116 | stack_depth = 2 | |
2105 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2117 | magic_arg_s = self.var_expand(line, stack_depth) | |
2106 | with self.builtin_trap: |
|
2118 | with self.builtin_trap: | |
2107 | result = fn(magic_arg_s, cell) |
|
2119 | result = fn(magic_arg_s, cell) | |
2108 | return result |
|
2120 | return result | |
2109 |
|
2121 | |||
2110 | def find_line_magic(self, magic_name): |
|
2122 | def find_line_magic(self, magic_name): | |
2111 | """Find and return a line magic by name. |
|
2123 | """Find and return a line magic by name. | |
2112 |
|
2124 | |||
2113 | Returns None if the magic isn't found.""" |
|
2125 | Returns None if the magic isn't found.""" | |
2114 | return self.magics_manager.magics['line'].get(magic_name) |
|
2126 | return self.magics_manager.magics['line'].get(magic_name) | |
2115 |
|
2127 | |||
2116 | def find_cell_magic(self, magic_name): |
|
2128 | def find_cell_magic(self, magic_name): | |
2117 | """Find and return a cell magic by name. |
|
2129 | """Find and return a cell magic by name. | |
2118 |
|
2130 | |||
2119 | Returns None if the magic isn't found.""" |
|
2131 | Returns None if the magic isn't found.""" | |
2120 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2132 | return self.magics_manager.magics['cell'].get(magic_name) | |
2121 |
|
2133 | |||
2122 | def find_magic(self, magic_name, magic_kind='line'): |
|
2134 | def find_magic(self, magic_name, magic_kind='line'): | |
2123 | """Find and return a magic of the given type by name. |
|
2135 | """Find and return a magic of the given type by name. | |
2124 |
|
2136 | |||
2125 | Returns None if the magic isn't found.""" |
|
2137 | Returns None if the magic isn't found.""" | |
2126 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2138 | return self.magics_manager.magics[magic_kind].get(magic_name) | |
2127 |
|
2139 | |||
2128 | def magic(self, arg_s): |
|
2140 | def magic(self, arg_s): | |
2129 | """DEPRECATED. Use run_line_magic() instead. |
|
2141 | """DEPRECATED. Use run_line_magic() instead. | |
2130 |
|
2142 | |||
2131 | Call a magic function by name. |
|
2143 | Call a magic function by name. | |
2132 |
|
2144 | |||
2133 | Input: a string containing the name of the magic function to call and |
|
2145 | Input: a string containing the name of the magic function to call and | |
2134 | any additional arguments to be passed to the magic. |
|
2146 | any additional arguments to be passed to the magic. | |
2135 |
|
2147 | |||
2136 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2148 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
2137 | prompt: |
|
2149 | prompt: | |
2138 |
|
2150 | |||
2139 | In[1]: %name -opt foo bar |
|
2151 | In[1]: %name -opt foo bar | |
2140 |
|
2152 | |||
2141 | To call a magic without arguments, simply use magic('name'). |
|
2153 | To call a magic without arguments, simply use magic('name'). | |
2142 |
|
2154 | |||
2143 | This provides a proper Python function to call IPython's magics in any |
|
2155 | This provides a proper Python function to call IPython's magics in any | |
2144 | valid Python code you can type at the interpreter, including loops and |
|
2156 | valid Python code you can type at the interpreter, including loops and | |
2145 | compound statements. |
|
2157 | compound statements. | |
2146 | """ |
|
2158 | """ | |
2147 | # TODO: should we issue a loud deprecation warning here? |
|
2159 | # TODO: should we issue a loud deprecation warning here? | |
2148 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2160 | magic_name, _, magic_arg_s = arg_s.partition(' ') | |
2149 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2161 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
2150 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2162 | return self.run_line_magic(magic_name, magic_arg_s) | |
2151 |
|
2163 | |||
2152 | #------------------------------------------------------------------------- |
|
2164 | #------------------------------------------------------------------------- | |
2153 | # Things related to macros |
|
2165 | # Things related to macros | |
2154 | #------------------------------------------------------------------------- |
|
2166 | #------------------------------------------------------------------------- | |
2155 |
|
2167 | |||
2156 | def define_macro(self, name, themacro): |
|
2168 | def define_macro(self, name, themacro): | |
2157 | """Define a new macro |
|
2169 | """Define a new macro | |
2158 |
|
2170 | |||
2159 | Parameters |
|
2171 | Parameters | |
2160 | ---------- |
|
2172 | ---------- | |
2161 | name : str |
|
2173 | name : str | |
2162 | The name of the macro. |
|
2174 | The name of the macro. | |
2163 | themacro : str or Macro |
|
2175 | themacro : str or Macro | |
2164 | The action to do upon invoking the macro. If a string, a new |
|
2176 | The action to do upon invoking the macro. If a string, a new | |
2165 | Macro object is created by passing the string to it. |
|
2177 | Macro object is created by passing the string to it. | |
2166 | """ |
|
2178 | """ | |
2167 |
|
2179 | |||
2168 | from IPython.core import macro |
|
2180 | from IPython.core import macro | |
2169 |
|
2181 | |||
2170 | if isinstance(themacro, string_types): |
|
2182 | if isinstance(themacro, string_types): | |
2171 | themacro = macro.Macro(themacro) |
|
2183 | themacro = macro.Macro(themacro) | |
2172 | if not isinstance(themacro, macro.Macro): |
|
2184 | if not isinstance(themacro, macro.Macro): | |
2173 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2185 | raise ValueError('A macro must be a string or a Macro instance.') | |
2174 | self.user_ns[name] = themacro |
|
2186 | self.user_ns[name] = themacro | |
2175 |
|
2187 | |||
2176 | #------------------------------------------------------------------------- |
|
2188 | #------------------------------------------------------------------------- | |
2177 | # Things related to the running of system commands |
|
2189 | # Things related to the running of system commands | |
2178 | #------------------------------------------------------------------------- |
|
2190 | #------------------------------------------------------------------------- | |
2179 |
|
2191 | |||
2180 | def system_piped(self, cmd): |
|
2192 | def system_piped(self, cmd): | |
2181 | """Call the given cmd in a subprocess, piping stdout/err |
|
2193 | """Call the given cmd in a subprocess, piping stdout/err | |
2182 |
|
2194 | |||
2183 | Parameters |
|
2195 | Parameters | |
2184 | ---------- |
|
2196 | ---------- | |
2185 | cmd : str |
|
2197 | cmd : str | |
2186 | Command to execute (can not end in '&', as background processes are |
|
2198 | Command to execute (can not end in '&', as background processes are | |
2187 | not supported. Should not be a command that expects input |
|
2199 | not supported. Should not be a command that expects input | |
2188 | other than simple text. |
|
2200 | other than simple text. | |
2189 | """ |
|
2201 | """ | |
2190 | if cmd.rstrip().endswith('&'): |
|
2202 | if cmd.rstrip().endswith('&'): | |
2191 | # this is *far* from a rigorous test |
|
2203 | # this is *far* from a rigorous test | |
2192 | # We do not support backgrounding processes because we either use |
|
2204 | # We do not support backgrounding processes because we either use | |
2193 | # pexpect or pipes to read from. Users can always just call |
|
2205 | # pexpect or pipes to read from. Users can always just call | |
2194 | # os.system() or use ip.system=ip.system_raw |
|
2206 | # os.system() or use ip.system=ip.system_raw | |
2195 | # if they really want a background process. |
|
2207 | # if they really want a background process. | |
2196 | raise OSError("Background processes not supported.") |
|
2208 | raise OSError("Background processes not supported.") | |
2197 |
|
2209 | |||
2198 | # we explicitly do NOT return the subprocess status code, because |
|
2210 | # we explicitly do NOT return the subprocess status code, because | |
2199 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2211 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2200 | # Instead, we store the exit_code in user_ns. |
|
2212 | # Instead, we store the exit_code in user_ns. | |
2201 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2213 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) | |
2202 |
|
2214 | |||
2203 | def system_raw(self, cmd): |
|
2215 | def system_raw(self, cmd): | |
2204 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2216 | """Call the given cmd in a subprocess using os.system on Windows or | |
2205 | subprocess.call using the system shell on other platforms. |
|
2217 | subprocess.call using the system shell on other platforms. | |
2206 |
|
2218 | |||
2207 | Parameters |
|
2219 | Parameters | |
2208 | ---------- |
|
2220 | ---------- | |
2209 | cmd : str |
|
2221 | cmd : str | |
2210 | Command to execute. |
|
2222 | Command to execute. | |
2211 | """ |
|
2223 | """ | |
2212 | cmd = self.var_expand(cmd, depth=1) |
|
2224 | cmd = self.var_expand(cmd, depth=1) | |
2213 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2225 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2214 | if sys.platform == 'win32': |
|
2226 | if sys.platform == 'win32': | |
2215 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2227 | from IPython.utils._process_win32 import AvoidUNCPath | |
2216 | with AvoidUNCPath() as path: |
|
2228 | with AvoidUNCPath() as path: | |
2217 | if path is not None: |
|
2229 | if path is not None: | |
2218 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2230 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2219 | cmd = py3compat.unicode_to_str(cmd) |
|
2231 | cmd = py3compat.unicode_to_str(cmd) | |
2220 | try: |
|
2232 | try: | |
2221 | ec = os.system(cmd) |
|
2233 | ec = os.system(cmd) | |
2222 | except KeyboardInterrupt: |
|
2234 | except KeyboardInterrupt: | |
2223 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2235 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
2224 | ec = -2 |
|
2236 | ec = -2 | |
2225 | else: |
|
2237 | else: | |
2226 | cmd = py3compat.unicode_to_str(cmd) |
|
2238 | cmd = py3compat.unicode_to_str(cmd) | |
2227 | # For posix the result of the subprocess.call() below is an exit |
|
2239 | # For posix the result of the subprocess.call() below is an exit | |
2228 | # code, which by convention is zero for success, positive for |
|
2240 | # code, which by convention is zero for success, positive for | |
2229 | # program failure. Exit codes above 128 are reserved for signals, |
|
2241 | # program failure. Exit codes above 128 are reserved for signals, | |
2230 | # and the formula for converting a signal to an exit code is usually |
|
2242 | # and the formula for converting a signal to an exit code is usually | |
2231 | # signal_number+128. To more easily differentiate between exit |
|
2243 | # signal_number+128. To more easily differentiate between exit | |
2232 | # codes and signals, ipython uses negative numbers. For instance |
|
2244 | # codes and signals, ipython uses negative numbers. For instance | |
2233 | # since control-c is signal 2 but exit code 130, ipython's |
|
2245 | # since control-c is signal 2 but exit code 130, ipython's | |
2234 | # _exit_code variable will read -2. Note that some shells like |
|
2246 | # _exit_code variable will read -2. Note that some shells like | |
2235 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2247 | # csh and fish don't follow sh/bash conventions for exit codes. | |
2236 | executable = os.environ.get('SHELL', None) |
|
2248 | executable = os.environ.get('SHELL', None) | |
2237 | try: |
|
2249 | try: | |
2238 | # Use env shell instead of default /bin/sh |
|
2250 | # Use env shell instead of default /bin/sh | |
2239 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2251 | ec = subprocess.call(cmd, shell=True, executable=executable) | |
2240 | except KeyboardInterrupt: |
|
2252 | except KeyboardInterrupt: | |
2241 | # intercept control-C; a long traceback is not useful here |
|
2253 | # intercept control-C; a long traceback is not useful here | |
2242 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2254 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
2243 | ec = 130 |
|
2255 | ec = 130 | |
2244 | if ec > 128: |
|
2256 | if ec > 128: | |
2245 | ec = -(ec - 128) |
|
2257 | ec = -(ec - 128) | |
2246 |
|
2258 | |||
2247 | # We explicitly do NOT return the subprocess status code, because |
|
2259 | # We explicitly do NOT return the subprocess status code, because | |
2248 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2260 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2249 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2261 | # Instead, we store the exit_code in user_ns. Note the semantics | |
2250 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2262 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, | |
2251 | # but raising SystemExit(_exit_code) will give status 254! |
|
2263 | # but raising SystemExit(_exit_code) will give status 254! | |
2252 | self.user_ns['_exit_code'] = ec |
|
2264 | self.user_ns['_exit_code'] = ec | |
2253 |
|
2265 | |||
2254 | # use piped system by default, because it is better behaved |
|
2266 | # use piped system by default, because it is better behaved | |
2255 | system = system_piped |
|
2267 | system = system_piped | |
2256 |
|
2268 | |||
2257 | def getoutput(self, cmd, split=True, depth=0): |
|
2269 | def getoutput(self, cmd, split=True, depth=0): | |
2258 | """Get output (possibly including stderr) from a subprocess. |
|
2270 | """Get output (possibly including stderr) from a subprocess. | |
2259 |
|
2271 | |||
2260 | Parameters |
|
2272 | Parameters | |
2261 | ---------- |
|
2273 | ---------- | |
2262 | cmd : str |
|
2274 | cmd : str | |
2263 | Command to execute (can not end in '&', as background processes are |
|
2275 | Command to execute (can not end in '&', as background processes are | |
2264 | not supported. |
|
2276 | not supported. | |
2265 | split : bool, optional |
|
2277 | split : bool, optional | |
2266 | If True, split the output into an IPython SList. Otherwise, an |
|
2278 | If True, split the output into an IPython SList. Otherwise, an | |
2267 | IPython LSString is returned. These are objects similar to normal |
|
2279 | IPython LSString is returned. These are objects similar to normal | |
2268 | lists and strings, with a few convenience attributes for easier |
|
2280 | lists and strings, with a few convenience attributes for easier | |
2269 | manipulation of line-based output. You can use '?' on them for |
|
2281 | manipulation of line-based output. You can use '?' on them for | |
2270 | details. |
|
2282 | details. | |
2271 | depth : int, optional |
|
2283 | depth : int, optional | |
2272 | How many frames above the caller are the local variables which should |
|
2284 | How many frames above the caller are the local variables which should | |
2273 | be expanded in the command string? The default (0) assumes that the |
|
2285 | be expanded in the command string? The default (0) assumes that the | |
2274 | expansion variables are in the stack frame calling this function. |
|
2286 | expansion variables are in the stack frame calling this function. | |
2275 | """ |
|
2287 | """ | |
2276 | if cmd.rstrip().endswith('&'): |
|
2288 | if cmd.rstrip().endswith('&'): | |
2277 | # this is *far* from a rigorous test |
|
2289 | # this is *far* from a rigorous test | |
2278 | raise OSError("Background processes not supported.") |
|
2290 | raise OSError("Background processes not supported.") | |
2279 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2291 | out = getoutput(self.var_expand(cmd, depth=depth+1)) | |
2280 | if split: |
|
2292 | if split: | |
2281 | out = SList(out.splitlines()) |
|
2293 | out = SList(out.splitlines()) | |
2282 | else: |
|
2294 | else: | |
2283 | out = LSString(out) |
|
2295 | out = LSString(out) | |
2284 | return out |
|
2296 | return out | |
2285 |
|
2297 | |||
2286 | #------------------------------------------------------------------------- |
|
2298 | #------------------------------------------------------------------------- | |
2287 | # Things related to aliases |
|
2299 | # Things related to aliases | |
2288 | #------------------------------------------------------------------------- |
|
2300 | #------------------------------------------------------------------------- | |
2289 |
|
2301 | |||
2290 | def init_alias(self): |
|
2302 | def init_alias(self): | |
2291 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2303 | self.alias_manager = AliasManager(shell=self, parent=self) | |
2292 | self.configurables.append(self.alias_manager) |
|
2304 | self.configurables.append(self.alias_manager) | |
2293 |
|
2305 | |||
2294 | #------------------------------------------------------------------------- |
|
2306 | #------------------------------------------------------------------------- | |
2295 | # Things related to extensions |
|
2307 | # Things related to extensions | |
2296 | #------------------------------------------------------------------------- |
|
2308 | #------------------------------------------------------------------------- | |
2297 |
|
2309 | |||
2298 | def init_extension_manager(self): |
|
2310 | def init_extension_manager(self): | |
2299 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2311 | self.extension_manager = ExtensionManager(shell=self, parent=self) | |
2300 | self.configurables.append(self.extension_manager) |
|
2312 | self.configurables.append(self.extension_manager) | |
2301 |
|
2313 | |||
2302 | #------------------------------------------------------------------------- |
|
2314 | #------------------------------------------------------------------------- | |
2303 | # Things related to payloads |
|
2315 | # Things related to payloads | |
2304 | #------------------------------------------------------------------------- |
|
2316 | #------------------------------------------------------------------------- | |
2305 |
|
2317 | |||
2306 | def init_payload(self): |
|
2318 | def init_payload(self): | |
2307 | self.payload_manager = PayloadManager(parent=self) |
|
2319 | self.payload_manager = PayloadManager(parent=self) | |
2308 | self.configurables.append(self.payload_manager) |
|
2320 | self.configurables.append(self.payload_manager) | |
2309 |
|
2321 | |||
2310 | #------------------------------------------------------------------------- |
|
2322 | #------------------------------------------------------------------------- | |
2311 | # Things related to the prefilter |
|
2323 | # Things related to the prefilter | |
2312 | #------------------------------------------------------------------------- |
|
2324 | #------------------------------------------------------------------------- | |
2313 |
|
2325 | |||
2314 | def init_prefilter(self): |
|
2326 | def init_prefilter(self): | |
2315 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2327 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) | |
2316 | self.configurables.append(self.prefilter_manager) |
|
2328 | self.configurables.append(self.prefilter_manager) | |
2317 | # Ultimately this will be refactored in the new interpreter code, but |
|
2329 | # Ultimately this will be refactored in the new interpreter code, but | |
2318 | # for now, we should expose the main prefilter method (there's legacy |
|
2330 | # for now, we should expose the main prefilter method (there's legacy | |
2319 | # code out there that may rely on this). |
|
2331 | # code out there that may rely on this). | |
2320 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2332 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2321 |
|
2333 | |||
2322 | def auto_rewrite_input(self, cmd): |
|
2334 | def auto_rewrite_input(self, cmd): | |
2323 | """Print to the screen the rewritten form of the user's command. |
|
2335 | """Print to the screen the rewritten form of the user's command. | |
2324 |
|
2336 | |||
2325 | This shows visual feedback by rewriting input lines that cause |
|
2337 | This shows visual feedback by rewriting input lines that cause | |
2326 | automatic calling to kick in, like:: |
|
2338 | automatic calling to kick in, like:: | |
2327 |
|
2339 | |||
2328 | /f x |
|
2340 | /f x | |
2329 |
|
2341 | |||
2330 | into:: |
|
2342 | into:: | |
2331 |
|
2343 | |||
2332 | ------> f(x) |
|
2344 | ------> f(x) | |
2333 |
|
2345 | |||
2334 | after the user's input prompt. This helps the user understand that the |
|
2346 | after the user's input prompt. This helps the user understand that the | |
2335 | input line was transformed automatically by IPython. |
|
2347 | input line was transformed automatically by IPython. | |
2336 | """ |
|
2348 | """ | |
2337 | if not self.show_rewritten_input: |
|
2349 | if not self.show_rewritten_input: | |
2338 | return |
|
2350 | return | |
2339 |
|
2351 | |||
2340 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2352 | # This is overridden in TerminalInteractiveShell to use fancy prompts | |
2341 | print("------> " + cmd) |
|
2353 | print("------> " + cmd) | |
2342 |
|
2354 | |||
2343 | #------------------------------------------------------------------------- |
|
2355 | #------------------------------------------------------------------------- | |
2344 | # Things related to extracting values/expressions from kernel and user_ns |
|
2356 | # Things related to extracting values/expressions from kernel and user_ns | |
2345 | #------------------------------------------------------------------------- |
|
2357 | #------------------------------------------------------------------------- | |
2346 |
|
2358 | |||
2347 | def _user_obj_error(self): |
|
2359 | def _user_obj_error(self): | |
2348 | """return simple exception dict |
|
2360 | """return simple exception dict | |
2349 |
|
2361 | |||
2350 | for use in user_expressions |
|
2362 | for use in user_expressions | |
2351 | """ |
|
2363 | """ | |
2352 |
|
2364 | |||
2353 | etype, evalue, tb = self._get_exc_info() |
|
2365 | etype, evalue, tb = self._get_exc_info() | |
2354 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2366 | stb = self.InteractiveTB.get_exception_only(etype, evalue) | |
2355 |
|
2367 | |||
2356 | exc_info = { |
|
2368 | exc_info = { | |
2357 | u'status' : 'error', |
|
2369 | u'status' : 'error', | |
2358 | u'traceback' : stb, |
|
2370 | u'traceback' : stb, | |
2359 | u'ename' : unicode_type(etype.__name__), |
|
2371 | u'ename' : unicode_type(etype.__name__), | |
2360 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2372 | u'evalue' : py3compat.safe_unicode(evalue), | |
2361 | } |
|
2373 | } | |
2362 |
|
2374 | |||
2363 | return exc_info |
|
2375 | return exc_info | |
2364 |
|
2376 | |||
2365 | def _format_user_obj(self, obj): |
|
2377 | def _format_user_obj(self, obj): | |
2366 | """format a user object to display dict |
|
2378 | """format a user object to display dict | |
2367 |
|
2379 | |||
2368 | for use in user_expressions |
|
2380 | for use in user_expressions | |
2369 | """ |
|
2381 | """ | |
2370 |
|
2382 | |||
2371 | data, md = self.display_formatter.format(obj) |
|
2383 | data, md = self.display_formatter.format(obj) | |
2372 | value = { |
|
2384 | value = { | |
2373 | 'status' : 'ok', |
|
2385 | 'status' : 'ok', | |
2374 | 'data' : data, |
|
2386 | 'data' : data, | |
2375 | 'metadata' : md, |
|
2387 | 'metadata' : md, | |
2376 | } |
|
2388 | } | |
2377 | return value |
|
2389 | return value | |
2378 |
|
2390 | |||
2379 | def user_expressions(self, expressions): |
|
2391 | def user_expressions(self, expressions): | |
2380 | """Evaluate a dict of expressions in the user's namespace. |
|
2392 | """Evaluate a dict of expressions in the user's namespace. | |
2381 |
|
2393 | |||
2382 | Parameters |
|
2394 | Parameters | |
2383 | ---------- |
|
2395 | ---------- | |
2384 | expressions : dict |
|
2396 | expressions : dict | |
2385 | A dict with string keys and string values. The expression values |
|
2397 | A dict with string keys and string values. The expression values | |
2386 | should be valid Python expressions, each of which will be evaluated |
|
2398 | should be valid Python expressions, each of which will be evaluated | |
2387 | in the user namespace. |
|
2399 | in the user namespace. | |
2388 |
|
2400 | |||
2389 | Returns |
|
2401 | Returns | |
2390 | ------- |
|
2402 | ------- | |
2391 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2403 | A dict, keyed like the input expressions dict, with the rich mime-typed | |
2392 | display_data of each value. |
|
2404 | display_data of each value. | |
2393 | """ |
|
2405 | """ | |
2394 | out = {} |
|
2406 | out = {} | |
2395 | user_ns = self.user_ns |
|
2407 | user_ns = self.user_ns | |
2396 | global_ns = self.user_global_ns |
|
2408 | global_ns = self.user_global_ns | |
2397 |
|
2409 | |||
2398 | for key, expr in iteritems(expressions): |
|
2410 | for key, expr in iteritems(expressions): | |
2399 | try: |
|
2411 | try: | |
2400 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2412 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) | |
2401 | except: |
|
2413 | except: | |
2402 | value = self._user_obj_error() |
|
2414 | value = self._user_obj_error() | |
2403 | out[key] = value |
|
2415 | out[key] = value | |
2404 | return out |
|
2416 | return out | |
2405 |
|
2417 | |||
2406 | #------------------------------------------------------------------------- |
|
2418 | #------------------------------------------------------------------------- | |
2407 | # Things related to the running of code |
|
2419 | # Things related to the running of code | |
2408 | #------------------------------------------------------------------------- |
|
2420 | #------------------------------------------------------------------------- | |
2409 |
|
2421 | |||
2410 | def ex(self, cmd): |
|
2422 | def ex(self, cmd): | |
2411 | """Execute a normal python statement in user namespace.""" |
|
2423 | """Execute a normal python statement in user namespace.""" | |
2412 | with self.builtin_trap: |
|
2424 | with self.builtin_trap: | |
2413 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2425 | exec(cmd, self.user_global_ns, self.user_ns) | |
2414 |
|
2426 | |||
2415 | def ev(self, expr): |
|
2427 | def ev(self, expr): | |
2416 | """Evaluate python expression expr in user namespace. |
|
2428 | """Evaluate python expression expr in user namespace. | |
2417 |
|
2429 | |||
2418 | Returns the result of evaluation |
|
2430 | Returns the result of evaluation | |
2419 | """ |
|
2431 | """ | |
2420 | with self.builtin_trap: |
|
2432 | with self.builtin_trap: | |
2421 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2433 | return eval(expr, self.user_global_ns, self.user_ns) | |
2422 |
|
2434 | |||
2423 | def safe_execfile(self, fname, *where, **kw): |
|
2435 | def safe_execfile(self, fname, *where, **kw): | |
2424 | """A safe version of the builtin execfile(). |
|
2436 | """A safe version of the builtin execfile(). | |
2425 |
|
2437 | |||
2426 | This version will never throw an exception, but instead print |
|
2438 | This version will never throw an exception, but instead print | |
2427 | helpful error messages to the screen. This only works on pure |
|
2439 | helpful error messages to the screen. This only works on pure | |
2428 | Python files with the .py extension. |
|
2440 | Python files with the .py extension. | |
2429 |
|
2441 | |||
2430 | Parameters |
|
2442 | Parameters | |
2431 | ---------- |
|
2443 | ---------- | |
2432 | fname : string |
|
2444 | fname : string | |
2433 | The name of the file to be executed. |
|
2445 | The name of the file to be executed. | |
2434 | where : tuple |
|
2446 | where : tuple | |
2435 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2447 | One or two namespaces, passed to execfile() as (globals,locals). | |
2436 | If only one is given, it is passed as both. |
|
2448 | If only one is given, it is passed as both. | |
2437 | exit_ignore : bool (False) |
|
2449 | exit_ignore : bool (False) | |
2438 | If True, then silence SystemExit for non-zero status (it is always |
|
2450 | If True, then silence SystemExit for non-zero status (it is always | |
2439 | silenced for zero status, as it is so common). |
|
2451 | silenced for zero status, as it is so common). | |
2440 | raise_exceptions : bool (False) |
|
2452 | raise_exceptions : bool (False) | |
2441 | If True raise exceptions everywhere. Meant for testing. |
|
2453 | If True raise exceptions everywhere. Meant for testing. | |
2442 | shell_futures : bool (False) |
|
2454 | shell_futures : bool (False) | |
2443 | If True, the code will share future statements with the interactive |
|
2455 | If True, the code will share future statements with the interactive | |
2444 | shell. It will both be affected by previous __future__ imports, and |
|
2456 | shell. It will both be affected by previous __future__ imports, and | |
2445 | any __future__ imports in the code will affect the shell. If False, |
|
2457 | any __future__ imports in the code will affect the shell. If False, | |
2446 | __future__ imports are not shared in either direction. |
|
2458 | __future__ imports are not shared in either direction. | |
2447 |
|
2459 | |||
2448 | """ |
|
2460 | """ | |
2449 | kw.setdefault('exit_ignore', False) |
|
2461 | kw.setdefault('exit_ignore', False) | |
2450 | kw.setdefault('raise_exceptions', False) |
|
2462 | kw.setdefault('raise_exceptions', False) | |
2451 | kw.setdefault('shell_futures', False) |
|
2463 | kw.setdefault('shell_futures', False) | |
2452 |
|
2464 | |||
2453 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2465 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2454 |
|
2466 | |||
2455 | # Make sure we can open the file |
|
2467 | # Make sure we can open the file | |
2456 | try: |
|
2468 | try: | |
2457 | with open(fname): |
|
2469 | with open(fname): | |
2458 | pass |
|
2470 | pass | |
2459 | except: |
|
2471 | except: | |
2460 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2472 | warn('Could not open file <%s> for safe execution.' % fname) | |
2461 | return |
|
2473 | return | |
2462 |
|
2474 | |||
2463 | # Find things also in current directory. This is needed to mimic the |
|
2475 | # Find things also in current directory. This is needed to mimic the | |
2464 | # behavior of running a script from the system command line, where |
|
2476 | # behavior of running a script from the system command line, where | |
2465 | # Python inserts the script's directory into sys.path |
|
2477 | # Python inserts the script's directory into sys.path | |
2466 | dname = os.path.dirname(fname) |
|
2478 | dname = os.path.dirname(fname) | |
2467 |
|
2479 | |||
2468 | with prepended_to_syspath(dname): |
|
2480 | with prepended_to_syspath(dname): | |
2469 | try: |
|
2481 | try: | |
2470 | glob, loc = (where + (None, ))[:2] |
|
2482 | glob, loc = (where + (None, ))[:2] | |
2471 | py3compat.execfile( |
|
2483 | py3compat.execfile( | |
2472 | fname, glob, loc, |
|
2484 | fname, glob, loc, | |
2473 | self.compile if kw['shell_futures'] else None) |
|
2485 | self.compile if kw['shell_futures'] else None) | |
2474 | except SystemExit as status: |
|
2486 | except SystemExit as status: | |
2475 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2487 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2476 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2488 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2477 | # these are considered normal by the OS: |
|
2489 | # these are considered normal by the OS: | |
2478 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2490 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2479 | # 0 |
|
2491 | # 0 | |
2480 | # > python -c'import sys;sys.exit()'; echo $? |
|
2492 | # > python -c'import sys;sys.exit()'; echo $? | |
2481 | # 0 |
|
2493 | # 0 | |
2482 | # For other exit status, we show the exception unless |
|
2494 | # For other exit status, we show the exception unless | |
2483 | # explicitly silenced, but only in short form. |
|
2495 | # explicitly silenced, but only in short form. | |
2484 | if status.code: |
|
2496 | if status.code: | |
2485 | if kw['raise_exceptions']: |
|
2497 | if kw['raise_exceptions']: | |
2486 | raise |
|
2498 | raise | |
2487 | if not kw['exit_ignore']: |
|
2499 | if not kw['exit_ignore']: | |
2488 | self.showtraceback(exception_only=True) |
|
2500 | self.showtraceback(exception_only=True) | |
2489 | except: |
|
2501 | except: | |
2490 | if kw['raise_exceptions']: |
|
2502 | if kw['raise_exceptions']: | |
2491 | raise |
|
2503 | raise | |
2492 | # tb offset is 2 because we wrap execfile |
|
2504 | # tb offset is 2 because we wrap execfile | |
2493 | self.showtraceback(tb_offset=2) |
|
2505 | self.showtraceback(tb_offset=2) | |
2494 |
|
2506 | |||
2495 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2507 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): | |
2496 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2508 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. | |
2497 |
|
2509 | |||
2498 | Parameters |
|
2510 | Parameters | |
2499 | ---------- |
|
2511 | ---------- | |
2500 | fname : str |
|
2512 | fname : str | |
2501 | The name of the file to execute. The filename must have a |
|
2513 | The name of the file to execute. The filename must have a | |
2502 | .ipy or .ipynb extension. |
|
2514 | .ipy or .ipynb extension. | |
2503 | shell_futures : bool (False) |
|
2515 | shell_futures : bool (False) | |
2504 | If True, the code will share future statements with the interactive |
|
2516 | If True, the code will share future statements with the interactive | |
2505 | shell. It will both be affected by previous __future__ imports, and |
|
2517 | shell. It will both be affected by previous __future__ imports, and | |
2506 | any __future__ imports in the code will affect the shell. If False, |
|
2518 | any __future__ imports in the code will affect the shell. If False, | |
2507 | __future__ imports are not shared in either direction. |
|
2519 | __future__ imports are not shared in either direction. | |
2508 | raise_exceptions : bool (False) |
|
2520 | raise_exceptions : bool (False) | |
2509 | If True raise exceptions everywhere. Meant for testing. |
|
2521 | If True raise exceptions everywhere. Meant for testing. | |
2510 | """ |
|
2522 | """ | |
2511 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2523 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2512 |
|
2524 | |||
2513 | # Make sure we can open the file |
|
2525 | # Make sure we can open the file | |
2514 | try: |
|
2526 | try: | |
2515 | with open(fname): |
|
2527 | with open(fname): | |
2516 | pass |
|
2528 | pass | |
2517 | except: |
|
2529 | except: | |
2518 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2530 | warn('Could not open file <%s> for safe execution.' % fname) | |
2519 | return |
|
2531 | return | |
2520 |
|
2532 | |||
2521 | # Find things also in current directory. This is needed to mimic the |
|
2533 | # Find things also in current directory. This is needed to mimic the | |
2522 | # behavior of running a script from the system command line, where |
|
2534 | # behavior of running a script from the system command line, where | |
2523 | # Python inserts the script's directory into sys.path |
|
2535 | # Python inserts the script's directory into sys.path | |
2524 | dname = os.path.dirname(fname) |
|
2536 | dname = os.path.dirname(fname) | |
2525 |
|
2537 | |||
2526 | def get_cells(): |
|
2538 | def get_cells(): | |
2527 | """generator for sequence of code blocks to run""" |
|
2539 | """generator for sequence of code blocks to run""" | |
2528 | if fname.endswith('.ipynb'): |
|
2540 | if fname.endswith('.ipynb'): | |
2529 | from nbformat import read |
|
2541 | from nbformat import read | |
2530 | with io_open(fname) as f: |
|
2542 | with io_open(fname) as f: | |
2531 | nb = read(f, as_version=4) |
|
2543 | nb = read(f, as_version=4) | |
2532 | if not nb.cells: |
|
2544 | if not nb.cells: | |
2533 | return |
|
2545 | return | |
2534 | for cell in nb.cells: |
|
2546 | for cell in nb.cells: | |
2535 | if cell.cell_type == 'code': |
|
2547 | if cell.cell_type == 'code': | |
2536 | yield cell.source |
|
2548 | yield cell.source | |
2537 | else: |
|
2549 | else: | |
2538 | with open(fname) as f: |
|
2550 | with open(fname) as f: | |
2539 | yield f.read() |
|
2551 | yield f.read() | |
2540 |
|
2552 | |||
2541 | with prepended_to_syspath(dname): |
|
2553 | with prepended_to_syspath(dname): | |
2542 | try: |
|
2554 | try: | |
2543 | for cell in get_cells(): |
|
2555 | for cell in get_cells(): | |
2544 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2556 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) | |
2545 | if raise_exceptions: |
|
2557 | if raise_exceptions: | |
2546 | result.raise_error() |
|
2558 | result.raise_error() | |
2547 | elif not result.success: |
|
2559 | elif not result.success: | |
2548 | break |
|
2560 | break | |
2549 | except: |
|
2561 | except: | |
2550 | if raise_exceptions: |
|
2562 | if raise_exceptions: | |
2551 | raise |
|
2563 | raise | |
2552 | self.showtraceback() |
|
2564 | self.showtraceback() | |
2553 | warn('Unknown failure executing file: <%s>' % fname) |
|
2565 | warn('Unknown failure executing file: <%s>' % fname) | |
2554 |
|
2566 | |||
2555 | def safe_run_module(self, mod_name, where): |
|
2567 | def safe_run_module(self, mod_name, where): | |
2556 | """A safe version of runpy.run_module(). |
|
2568 | """A safe version of runpy.run_module(). | |
2557 |
|
2569 | |||
2558 | This version will never throw an exception, but instead print |
|
2570 | This version will never throw an exception, but instead print | |
2559 | helpful error messages to the screen. |
|
2571 | helpful error messages to the screen. | |
2560 |
|
2572 | |||
2561 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2573 | `SystemExit` exceptions with status code 0 or None are ignored. | |
2562 |
|
2574 | |||
2563 | Parameters |
|
2575 | Parameters | |
2564 | ---------- |
|
2576 | ---------- | |
2565 | mod_name : string |
|
2577 | mod_name : string | |
2566 | The name of the module to be executed. |
|
2578 | The name of the module to be executed. | |
2567 | where : dict |
|
2579 | where : dict | |
2568 | The globals namespace. |
|
2580 | The globals namespace. | |
2569 | """ |
|
2581 | """ | |
2570 | try: |
|
2582 | try: | |
2571 | try: |
|
2583 | try: | |
2572 | where.update( |
|
2584 | where.update( | |
2573 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2585 | runpy.run_module(str(mod_name), run_name="__main__", | |
2574 | alter_sys=True) |
|
2586 | alter_sys=True) | |
2575 | ) |
|
2587 | ) | |
2576 | except SystemExit as status: |
|
2588 | except SystemExit as status: | |
2577 | if status.code: |
|
2589 | if status.code: | |
2578 | raise |
|
2590 | raise | |
2579 | except: |
|
2591 | except: | |
2580 | self.showtraceback() |
|
2592 | self.showtraceback() | |
2581 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2593 | warn('Unknown failure executing module: <%s>' % mod_name) | |
2582 |
|
2594 | |||
2583 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2595 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): | |
2584 | """Run a complete IPython cell. |
|
2596 | """Run a complete IPython cell. | |
2585 |
|
2597 | |||
2586 | Parameters |
|
2598 | Parameters | |
2587 | ---------- |
|
2599 | ---------- | |
2588 | raw_cell : str |
|
2600 | raw_cell : str | |
2589 | The code (including IPython code such as %magic functions) to run. |
|
2601 | The code (including IPython code such as %magic functions) to run. | |
2590 | store_history : bool |
|
2602 | store_history : bool | |
2591 | If True, the raw and translated cell will be stored in IPython's |
|
2603 | If True, the raw and translated cell will be stored in IPython's | |
2592 | history. For user code calling back into IPython's machinery, this |
|
2604 | history. For user code calling back into IPython's machinery, this | |
2593 | should be set to False. |
|
2605 | should be set to False. | |
2594 | silent : bool |
|
2606 | silent : bool | |
2595 | If True, avoid side-effects, such as implicit displayhooks and |
|
2607 | If True, avoid side-effects, such as implicit displayhooks and | |
2596 | and logging. silent=True forces store_history=False. |
|
2608 | and logging. silent=True forces store_history=False. | |
2597 | shell_futures : bool |
|
2609 | shell_futures : bool | |
2598 | If True, the code will share future statements with the interactive |
|
2610 | If True, the code will share future statements with the interactive | |
2599 | shell. It will both be affected by previous __future__ imports, and |
|
2611 | shell. It will both be affected by previous __future__ imports, and | |
2600 | any __future__ imports in the code will affect the shell. If False, |
|
2612 | any __future__ imports in the code will affect the shell. If False, | |
2601 | __future__ imports are not shared in either direction. |
|
2613 | __future__ imports are not shared in either direction. | |
2602 |
|
2614 | |||
2603 | Returns |
|
2615 | Returns | |
2604 | ------- |
|
2616 | ------- | |
2605 | result : :class:`ExecutionResult` |
|
2617 | result : :class:`ExecutionResult` | |
2606 | """ |
|
2618 | """ | |
2607 | result = ExecutionResult() |
|
2619 | result = ExecutionResult() | |
2608 |
|
2620 | |||
2609 | if (not raw_cell) or raw_cell.isspace(): |
|
2621 | if (not raw_cell) or raw_cell.isspace(): | |
2610 | self.last_execution_succeeded = True |
|
2622 | self.last_execution_succeeded = True | |
2611 | return result |
|
2623 | return result | |
2612 |
|
2624 | |||
2613 | if silent: |
|
2625 | if silent: | |
2614 | store_history = False |
|
2626 | store_history = False | |
2615 |
|
2627 | |||
2616 | if store_history: |
|
2628 | if store_history: | |
2617 | result.execution_count = self.execution_count |
|
2629 | result.execution_count = self.execution_count | |
2618 |
|
2630 | |||
2619 | def error_before_exec(value): |
|
2631 | def error_before_exec(value): | |
2620 | result.error_before_exec = value |
|
2632 | result.error_before_exec = value | |
2621 | self.last_execution_succeeded = False |
|
2633 | self.last_execution_succeeded = False | |
2622 | return result |
|
2634 | return result | |
2623 |
|
2635 | |||
2624 | self.events.trigger('pre_execute') |
|
2636 | self.events.trigger('pre_execute') | |
2625 | if not silent: |
|
2637 | if not silent: | |
2626 | self.events.trigger('pre_run_cell') |
|
2638 | self.events.trigger('pre_run_cell') | |
2627 |
|
2639 | |||
2628 | # If any of our input transformation (input_transformer_manager or |
|
2640 | # If any of our input transformation (input_transformer_manager or | |
2629 | # prefilter_manager) raises an exception, we store it in this variable |
|
2641 | # prefilter_manager) raises an exception, we store it in this variable | |
2630 | # so that we can display the error after logging the input and storing |
|
2642 | # so that we can display the error after logging the input and storing | |
2631 | # it in the history. |
|
2643 | # it in the history. | |
2632 | preprocessing_exc_tuple = None |
|
2644 | preprocessing_exc_tuple = None | |
2633 | try: |
|
2645 | try: | |
2634 | # Static input transformations |
|
2646 | # Static input transformations | |
2635 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2647 | cell = self.input_transformer_manager.transform_cell(raw_cell) | |
2636 | except SyntaxError: |
|
2648 | except SyntaxError: | |
2637 | preprocessing_exc_tuple = sys.exc_info() |
|
2649 | preprocessing_exc_tuple = sys.exc_info() | |
2638 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2650 | cell = raw_cell # cell has to exist so it can be stored/logged | |
2639 | else: |
|
2651 | else: | |
2640 | if len(cell.splitlines()) == 1: |
|
2652 | if len(cell.splitlines()) == 1: | |
2641 | # Dynamic transformations - only applied for single line commands |
|
2653 | # Dynamic transformations - only applied for single line commands | |
2642 | with self.builtin_trap: |
|
2654 | with self.builtin_trap: | |
2643 | try: |
|
2655 | try: | |
2644 | # use prefilter_lines to handle trailing newlines |
|
2656 | # use prefilter_lines to handle trailing newlines | |
2645 | # restore trailing newline for ast.parse |
|
2657 | # restore trailing newline for ast.parse | |
2646 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2658 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2647 | except Exception: |
|
2659 | except Exception: | |
2648 | # don't allow prefilter errors to crash IPython |
|
2660 | # don't allow prefilter errors to crash IPython | |
2649 | preprocessing_exc_tuple = sys.exc_info() |
|
2661 | preprocessing_exc_tuple = sys.exc_info() | |
2650 |
|
2662 | |||
2651 | # Store raw and processed history |
|
2663 | # Store raw and processed history | |
2652 | if store_history: |
|
2664 | if store_history: | |
2653 | self.history_manager.store_inputs(self.execution_count, |
|
2665 | self.history_manager.store_inputs(self.execution_count, | |
2654 | cell, raw_cell) |
|
2666 | cell, raw_cell) | |
2655 | if not silent: |
|
2667 | if not silent: | |
2656 | self.logger.log(cell, raw_cell) |
|
2668 | self.logger.log(cell, raw_cell) | |
2657 |
|
2669 | |||
2658 | # Display the exception if input processing failed. |
|
2670 | # Display the exception if input processing failed. | |
2659 | if preprocessing_exc_tuple is not None: |
|
2671 | if preprocessing_exc_tuple is not None: | |
2660 | self.showtraceback(preprocessing_exc_tuple) |
|
2672 | self.showtraceback(preprocessing_exc_tuple) | |
2661 | if store_history: |
|
2673 | if store_history: | |
2662 | self.execution_count += 1 |
|
2674 | self.execution_count += 1 | |
2663 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2675 | return error_before_exec(preprocessing_exc_tuple[2]) | |
2664 |
|
2676 | |||
2665 | # Our own compiler remembers the __future__ environment. If we want to |
|
2677 | # Our own compiler remembers the __future__ environment. If we want to | |
2666 | # run code with a separate __future__ environment, use the default |
|
2678 | # run code with a separate __future__ environment, use the default | |
2667 | # compiler |
|
2679 | # compiler | |
2668 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2680 | compiler = self.compile if shell_futures else CachingCompiler() | |
2669 |
|
2681 | |||
2670 | with self.builtin_trap: |
|
2682 | with self.builtin_trap: | |
2671 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2683 | cell_name = self.compile.cache(cell, self.execution_count) | |
2672 |
|
2684 | |||
2673 | with self.display_trap: |
|
2685 | with self.display_trap: | |
2674 | # Compile to bytecode |
|
2686 | # Compile to bytecode | |
2675 | try: |
|
2687 | try: | |
2676 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2688 | code_ast = compiler.ast_parse(cell, filename=cell_name) | |
2677 | except self.custom_exceptions as e: |
|
2689 | except self.custom_exceptions as e: | |
2678 | etype, value, tb = sys.exc_info() |
|
2690 | etype, value, tb = sys.exc_info() | |
2679 | self.CustomTB(etype, value, tb) |
|
2691 | self.CustomTB(etype, value, tb) | |
2680 | return error_before_exec(e) |
|
2692 | return error_before_exec(e) | |
2681 | except IndentationError as e: |
|
2693 | except IndentationError as e: | |
2682 | self.showindentationerror() |
|
2694 | self.showindentationerror() | |
2683 | if store_history: |
|
2695 | if store_history: | |
2684 | self.execution_count += 1 |
|
2696 | self.execution_count += 1 | |
2685 | return error_before_exec(e) |
|
2697 | return error_before_exec(e) | |
2686 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2698 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2687 | MemoryError) as e: |
|
2699 | MemoryError) as e: | |
2688 | self.showsyntaxerror() |
|
2700 | self.showsyntaxerror() | |
2689 | if store_history: |
|
2701 | if store_history: | |
2690 | self.execution_count += 1 |
|
2702 | self.execution_count += 1 | |
2691 | return error_before_exec(e) |
|
2703 | return error_before_exec(e) | |
2692 |
|
2704 | |||
2693 | # Apply AST transformations |
|
2705 | # Apply AST transformations | |
2694 | try: |
|
2706 | try: | |
2695 | code_ast = self.transform_ast(code_ast) |
|
2707 | code_ast = self.transform_ast(code_ast) | |
2696 | except InputRejected as e: |
|
2708 | except InputRejected as e: | |
2697 | self.showtraceback() |
|
2709 | self.showtraceback() | |
2698 | if store_history: |
|
2710 | if store_history: | |
2699 | self.execution_count += 1 |
|
2711 | self.execution_count += 1 | |
2700 | return error_before_exec(e) |
|
2712 | return error_before_exec(e) | |
2701 |
|
2713 | |||
2702 | # Give the displayhook a reference to our ExecutionResult so it |
|
2714 | # Give the displayhook a reference to our ExecutionResult so it | |
2703 | # can fill in the output value. |
|
2715 | # can fill in the output value. | |
2704 | self.displayhook.exec_result = result |
|
2716 | self.displayhook.exec_result = result | |
2705 |
|
2717 | |||
2706 | # Execute the user code |
|
2718 | # Execute the user code | |
2707 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2719 | interactivity = "none" if silent else self.ast_node_interactivity | |
2708 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, |
|
2720 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, | |
2709 | interactivity=interactivity, compiler=compiler, result=result) |
|
2721 | interactivity=interactivity, compiler=compiler, result=result) | |
2710 |
|
2722 | |||
2711 | self.last_execution_succeeded = not has_raised |
|
2723 | self.last_execution_succeeded = not has_raised | |
2712 |
|
2724 | |||
2713 | # Reset this so later displayed values do not modify the |
|
2725 | # Reset this so later displayed values do not modify the | |
2714 | # ExecutionResult |
|
2726 | # ExecutionResult | |
2715 | self.displayhook.exec_result = None |
|
2727 | self.displayhook.exec_result = None | |
2716 |
|
2728 | |||
2717 | self.events.trigger('post_execute') |
|
2729 | self.events.trigger('post_execute') | |
2718 | if not silent: |
|
2730 | if not silent: | |
2719 | self.events.trigger('post_run_cell') |
|
2731 | self.events.trigger('post_run_cell') | |
2720 |
|
2732 | |||
2721 | if store_history: |
|
2733 | if store_history: | |
2722 | # Write output to the database. Does nothing unless |
|
2734 | # Write output to the database. Does nothing unless | |
2723 | # history output logging is enabled. |
|
2735 | # history output logging is enabled. | |
2724 | self.history_manager.store_output(self.execution_count) |
|
2736 | self.history_manager.store_output(self.execution_count) | |
2725 | # Each cell is a *single* input, regardless of how many lines it has |
|
2737 | # Each cell is a *single* input, regardless of how many lines it has | |
2726 | self.execution_count += 1 |
|
2738 | self.execution_count += 1 | |
2727 |
|
2739 | |||
2728 | return result |
|
2740 | return result | |
2729 |
|
2741 | |||
2730 | def transform_ast(self, node): |
|
2742 | def transform_ast(self, node): | |
2731 | """Apply the AST transformations from self.ast_transformers |
|
2743 | """Apply the AST transformations from self.ast_transformers | |
2732 |
|
2744 | |||
2733 | Parameters |
|
2745 | Parameters | |
2734 | ---------- |
|
2746 | ---------- | |
2735 | node : ast.Node |
|
2747 | node : ast.Node | |
2736 | The root node to be transformed. Typically called with the ast.Module |
|
2748 | The root node to be transformed. Typically called with the ast.Module | |
2737 | produced by parsing user input. |
|
2749 | produced by parsing user input. | |
2738 |
|
2750 | |||
2739 | Returns |
|
2751 | Returns | |
2740 | ------- |
|
2752 | ------- | |
2741 | An ast.Node corresponding to the node it was called with. Note that it |
|
2753 | An ast.Node corresponding to the node it was called with. Note that it | |
2742 | may also modify the passed object, so don't rely on references to the |
|
2754 | may also modify the passed object, so don't rely on references to the | |
2743 | original AST. |
|
2755 | original AST. | |
2744 | """ |
|
2756 | """ | |
2745 | for transformer in self.ast_transformers: |
|
2757 | for transformer in self.ast_transformers: | |
2746 | try: |
|
2758 | try: | |
2747 | node = transformer.visit(node) |
|
2759 | node = transformer.visit(node) | |
2748 | except InputRejected: |
|
2760 | except InputRejected: | |
2749 | # User-supplied AST transformers can reject an input by raising |
|
2761 | # User-supplied AST transformers can reject an input by raising | |
2750 | # an InputRejected. Short-circuit in this case so that we |
|
2762 | # an InputRejected. Short-circuit in this case so that we | |
2751 | # don't unregister the transform. |
|
2763 | # don't unregister the transform. | |
2752 | raise |
|
2764 | raise | |
2753 | except Exception: |
|
2765 | except Exception: | |
2754 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2766 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) | |
2755 | self.ast_transformers.remove(transformer) |
|
2767 | self.ast_transformers.remove(transformer) | |
2756 |
|
2768 | |||
2757 | if self.ast_transformers: |
|
2769 | if self.ast_transformers: | |
2758 | ast.fix_missing_locations(node) |
|
2770 | ast.fix_missing_locations(node) | |
2759 | return node |
|
2771 | return node | |
2760 |
|
2772 | |||
2761 |
|
2773 | |||
2762 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2774 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', | |
2763 | compiler=compile, result=None): |
|
2775 | compiler=compile, result=None): | |
2764 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2776 | """Run a sequence of AST nodes. The execution mode depends on the | |
2765 | interactivity parameter. |
|
2777 | interactivity parameter. | |
2766 |
|
2778 | |||
2767 | Parameters |
|
2779 | Parameters | |
2768 | ---------- |
|
2780 | ---------- | |
2769 | nodelist : list |
|
2781 | nodelist : list | |
2770 | A sequence of AST nodes to run. |
|
2782 | A sequence of AST nodes to run. | |
2771 | cell_name : str |
|
2783 | cell_name : str | |
2772 | Will be passed to the compiler as the filename of the cell. Typically |
|
2784 | Will be passed to the compiler as the filename of the cell. Typically | |
2773 | the value returned by ip.compile.cache(cell). |
|
2785 | the value returned by ip.compile.cache(cell). | |
2774 | interactivity : str |
|
2786 | interactivity : str | |
2775 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2787 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2776 | run interactively (displaying output from expressions). 'last_expr' |
|
2788 | run interactively (displaying output from expressions). 'last_expr' | |
2777 | will run the last node interactively only if it is an expression (i.e. |
|
2789 | will run the last node interactively only if it is an expression (i.e. | |
2778 | expressions in loops or other blocks are not displayed. Other values |
|
2790 | expressions in loops or other blocks are not displayed. Other values | |
2779 | for this parameter will raise a ValueError. |
|
2791 | for this parameter will raise a ValueError. | |
2780 | compiler : callable |
|
2792 | compiler : callable | |
2781 | A function with the same interface as the built-in compile(), to turn |
|
2793 | A function with the same interface as the built-in compile(), to turn | |
2782 | the AST nodes into code objects. Default is the built-in compile(). |
|
2794 | the AST nodes into code objects. Default is the built-in compile(). | |
2783 | result : ExecutionResult, optional |
|
2795 | result : ExecutionResult, optional | |
2784 | An object to store exceptions that occur during execution. |
|
2796 | An object to store exceptions that occur during execution. | |
2785 |
|
2797 | |||
2786 | Returns |
|
2798 | Returns | |
2787 | ------- |
|
2799 | ------- | |
2788 | True if an exception occurred while running code, False if it finished |
|
2800 | True if an exception occurred while running code, False if it finished | |
2789 | running. |
|
2801 | running. | |
2790 | """ |
|
2802 | """ | |
2791 | if not nodelist: |
|
2803 | if not nodelist: | |
2792 | return |
|
2804 | return | |
2793 |
|
2805 | |||
2794 | if interactivity == 'last_expr': |
|
2806 | if interactivity == 'last_expr': | |
2795 | if isinstance(nodelist[-1], ast.Expr): |
|
2807 | if isinstance(nodelist[-1], ast.Expr): | |
2796 | interactivity = "last" |
|
2808 | interactivity = "last" | |
2797 | else: |
|
2809 | else: | |
2798 | interactivity = "none" |
|
2810 | interactivity = "none" | |
2799 |
|
2811 | |||
2800 | if interactivity == 'none': |
|
2812 | if interactivity == 'none': | |
2801 | to_run_exec, to_run_interactive = nodelist, [] |
|
2813 | to_run_exec, to_run_interactive = nodelist, [] | |
2802 | elif interactivity == 'last': |
|
2814 | elif interactivity == 'last': | |
2803 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2815 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2804 | elif interactivity == 'all': |
|
2816 | elif interactivity == 'all': | |
2805 | to_run_exec, to_run_interactive = [], nodelist |
|
2817 | to_run_exec, to_run_interactive = [], nodelist | |
2806 | else: |
|
2818 | else: | |
2807 | raise ValueError("Interactivity was %r" % interactivity) |
|
2819 | raise ValueError("Interactivity was %r" % interactivity) | |
2808 |
|
2820 | |||
2809 | try: |
|
2821 | try: | |
2810 | for i, node in enumerate(to_run_exec): |
|
2822 | for i, node in enumerate(to_run_exec): | |
2811 | mod = ast.Module([node]) |
|
2823 | mod = ast.Module([node]) | |
2812 | code = compiler(mod, cell_name, "exec") |
|
2824 | code = compiler(mod, cell_name, "exec") | |
2813 | if self.run_code(code, result): |
|
2825 | if self.run_code(code, result): | |
2814 | return True |
|
2826 | return True | |
2815 |
|
2827 | |||
2816 | for i, node in enumerate(to_run_interactive): |
|
2828 | for i, node in enumerate(to_run_interactive): | |
2817 | mod = ast.Interactive([node]) |
|
2829 | mod = ast.Interactive([node]) | |
2818 | code = compiler(mod, cell_name, "single") |
|
2830 | code = compiler(mod, cell_name, "single") | |
2819 | if self.run_code(code, result): |
|
2831 | if self.run_code(code, result): | |
2820 | return True |
|
2832 | return True | |
2821 |
|
2833 | |||
2822 | # Flush softspace |
|
2834 | # Flush softspace | |
2823 | if softspace(sys.stdout, 0): |
|
2835 | if softspace(sys.stdout, 0): | |
2824 | print() |
|
2836 | print() | |
2825 |
|
2837 | |||
2826 | except: |
|
2838 | except: | |
2827 | # It's possible to have exceptions raised here, typically by |
|
2839 | # It's possible to have exceptions raised here, typically by | |
2828 | # compilation of odd code (such as a naked 'return' outside a |
|
2840 | # compilation of odd code (such as a naked 'return' outside a | |
2829 | # function) that did parse but isn't valid. Typically the exception |
|
2841 | # function) that did parse but isn't valid. Typically the exception | |
2830 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2842 | # is a SyntaxError, but it's safest just to catch anything and show | |
2831 | # the user a traceback. |
|
2843 | # the user a traceback. | |
2832 |
|
2844 | |||
2833 | # We do only one try/except outside the loop to minimize the impact |
|
2845 | # We do only one try/except outside the loop to minimize the impact | |
2834 | # on runtime, and also because if any node in the node list is |
|
2846 | # on runtime, and also because if any node in the node list is | |
2835 | # broken, we should stop execution completely. |
|
2847 | # broken, we should stop execution completely. | |
2836 | if result: |
|
2848 | if result: | |
2837 | result.error_before_exec = sys.exc_info()[1] |
|
2849 | result.error_before_exec = sys.exc_info()[1] | |
2838 | self.showtraceback() |
|
2850 | self.showtraceback() | |
2839 | return True |
|
2851 | return True | |
2840 |
|
2852 | |||
2841 | return False |
|
2853 | return False | |
2842 |
|
2854 | |||
2843 | def run_code(self, code_obj, result=None): |
|
2855 | def run_code(self, code_obj, result=None): | |
2844 | """Execute a code object. |
|
2856 | """Execute a code object. | |
2845 |
|
2857 | |||
2846 | When an exception occurs, self.showtraceback() is called to display a |
|
2858 | When an exception occurs, self.showtraceback() is called to display a | |
2847 | traceback. |
|
2859 | traceback. | |
2848 |
|
2860 | |||
2849 | Parameters |
|
2861 | Parameters | |
2850 | ---------- |
|
2862 | ---------- | |
2851 | code_obj : code object |
|
2863 | code_obj : code object | |
2852 | A compiled code object, to be executed |
|
2864 | A compiled code object, to be executed | |
2853 | result : ExecutionResult, optional |
|
2865 | result : ExecutionResult, optional | |
2854 | An object to store exceptions that occur during execution. |
|
2866 | An object to store exceptions that occur during execution. | |
2855 |
|
2867 | |||
2856 | Returns |
|
2868 | Returns | |
2857 | ------- |
|
2869 | ------- | |
2858 | False : successful execution. |
|
2870 | False : successful execution. | |
2859 | True : an error occurred. |
|
2871 | True : an error occurred. | |
2860 | """ |
|
2872 | """ | |
2861 | # Set our own excepthook in case the user code tries to call it |
|
2873 | # Set our own excepthook in case the user code tries to call it | |
2862 | # directly, so that the IPython crash handler doesn't get triggered |
|
2874 | # directly, so that the IPython crash handler doesn't get triggered | |
2863 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
2875 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook | |
2864 |
|
2876 | |||
2865 | # we save the original sys.excepthook in the instance, in case config |
|
2877 | # we save the original sys.excepthook in the instance, in case config | |
2866 | # code (such as magics) needs access to it. |
|
2878 | # code (such as magics) needs access to it. | |
2867 | self.sys_excepthook = old_excepthook |
|
2879 | self.sys_excepthook = old_excepthook | |
2868 | outflag = 1 # happens in more places, so it's easier as default |
|
2880 | outflag = 1 # happens in more places, so it's easier as default | |
2869 | try: |
|
2881 | try: | |
2870 | try: |
|
2882 | try: | |
2871 | self.hooks.pre_run_code_hook() |
|
2883 | self.hooks.pre_run_code_hook() | |
2872 | #rprint('Running code', repr(code_obj)) # dbg |
|
2884 | #rprint('Running code', repr(code_obj)) # dbg | |
2873 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2885 | exec(code_obj, self.user_global_ns, self.user_ns) | |
2874 | finally: |
|
2886 | finally: | |
2875 | # Reset our crash handler in place |
|
2887 | # Reset our crash handler in place | |
2876 | sys.excepthook = old_excepthook |
|
2888 | sys.excepthook = old_excepthook | |
2877 | except SystemExit as e: |
|
2889 | except SystemExit as e: | |
2878 | if result is not None: |
|
2890 | if result is not None: | |
2879 | result.error_in_exec = e |
|
2891 | result.error_in_exec = e | |
2880 | self.showtraceback(exception_only=True) |
|
2892 | self.showtraceback(exception_only=True) | |
2881 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2893 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) | |
2882 | except self.custom_exceptions: |
|
2894 | except self.custom_exceptions: | |
2883 | etype, value, tb = sys.exc_info() |
|
2895 | etype, value, tb = sys.exc_info() | |
2884 | if result is not None: |
|
2896 | if result is not None: | |
2885 | result.error_in_exec = value |
|
2897 | result.error_in_exec = value | |
2886 | self.CustomTB(etype, value, tb) |
|
2898 | self.CustomTB(etype, value, tb) | |
2887 | except: |
|
2899 | except: | |
2888 | if result is not None: |
|
2900 | if result is not None: | |
2889 | result.error_in_exec = sys.exc_info()[1] |
|
2901 | result.error_in_exec = sys.exc_info()[1] | |
2890 | self.showtraceback() |
|
2902 | self.showtraceback() | |
2891 | else: |
|
2903 | else: | |
2892 | outflag = 0 |
|
2904 | outflag = 0 | |
2893 | return outflag |
|
2905 | return outflag | |
2894 |
|
2906 | |||
2895 | # For backwards compatibility |
|
2907 | # For backwards compatibility | |
2896 | runcode = run_code |
|
2908 | runcode = run_code | |
2897 |
|
2909 | |||
2898 | #------------------------------------------------------------------------- |
|
2910 | #------------------------------------------------------------------------- | |
2899 | # Things related to GUI support and pylab |
|
2911 | # Things related to GUI support and pylab | |
2900 | #------------------------------------------------------------------------- |
|
2912 | #------------------------------------------------------------------------- | |
2901 |
|
2913 | |||
2902 | def enable_gui(self, gui=None): |
|
2914 | def enable_gui(self, gui=None): | |
2903 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2915 | raise NotImplementedError('Implement enable_gui in a subclass') | |
2904 |
|
2916 | |||
2905 | def enable_matplotlib(self, gui=None): |
|
2917 | def enable_matplotlib(self, gui=None): | |
2906 | """Enable interactive matplotlib and inline figure support. |
|
2918 | """Enable interactive matplotlib and inline figure support. | |
2907 |
|
2919 | |||
2908 | This takes the following steps: |
|
2920 | This takes the following steps: | |
2909 |
|
2921 | |||
2910 | 1. select the appropriate eventloop and matplotlib backend |
|
2922 | 1. select the appropriate eventloop and matplotlib backend | |
2911 | 2. set up matplotlib for interactive use with that backend |
|
2923 | 2. set up matplotlib for interactive use with that backend | |
2912 | 3. configure formatters for inline figure display |
|
2924 | 3. configure formatters for inline figure display | |
2913 | 4. enable the selected gui eventloop |
|
2925 | 4. enable the selected gui eventloop | |
2914 |
|
2926 | |||
2915 | Parameters |
|
2927 | Parameters | |
2916 | ---------- |
|
2928 | ---------- | |
2917 | gui : optional, string |
|
2929 | gui : optional, string | |
2918 | If given, dictates the choice of matplotlib GUI backend to use |
|
2930 | If given, dictates the choice of matplotlib GUI backend to use | |
2919 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2931 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2920 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2932 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2921 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2933 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2922 | user's matplotlibrc configuration file). Note that not all backends |
|
2934 | user's matplotlibrc configuration file). Note that not all backends | |
2923 | make sense in all contexts, for example a terminal ipython can't |
|
2935 | make sense in all contexts, for example a terminal ipython can't | |
2924 | display figures inline. |
|
2936 | display figures inline. | |
2925 | """ |
|
2937 | """ | |
2926 | from IPython.core import pylabtools as pt |
|
2938 | from IPython.core import pylabtools as pt | |
2927 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2939 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) | |
2928 |
|
2940 | |||
2929 | if gui != 'inline': |
|
2941 | if gui != 'inline': | |
2930 | # If we have our first gui selection, store it |
|
2942 | # If we have our first gui selection, store it | |
2931 | if self.pylab_gui_select is None: |
|
2943 | if self.pylab_gui_select is None: | |
2932 | self.pylab_gui_select = gui |
|
2944 | self.pylab_gui_select = gui | |
2933 | # Otherwise if they are different |
|
2945 | # Otherwise if they are different | |
2934 | elif gui != self.pylab_gui_select: |
|
2946 | elif gui != self.pylab_gui_select: | |
2935 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2947 | print ('Warning: Cannot change to a different GUI toolkit: %s.' | |
2936 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2948 | ' Using %s instead.' % (gui, self.pylab_gui_select)) | |
2937 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2949 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) | |
2938 |
|
2950 | |||
2939 | pt.activate_matplotlib(backend) |
|
2951 | pt.activate_matplotlib(backend) | |
2940 | pt.configure_inline_support(self, backend) |
|
2952 | pt.configure_inline_support(self, backend) | |
2941 |
|
2953 | |||
2942 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2954 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
2943 | # plot updates into account |
|
2955 | # plot updates into account | |
2944 | self.enable_gui(gui) |
|
2956 | self.enable_gui(gui) | |
2945 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2957 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ | |
2946 | pt.mpl_runner(self.safe_execfile) |
|
2958 | pt.mpl_runner(self.safe_execfile) | |
2947 |
|
2959 | |||
2948 | return gui, backend |
|
2960 | return gui, backend | |
2949 |
|
2961 | |||
2950 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2962 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): | |
2951 | """Activate pylab support at runtime. |
|
2963 | """Activate pylab support at runtime. | |
2952 |
|
2964 | |||
2953 | This turns on support for matplotlib, preloads into the interactive |
|
2965 | This turns on support for matplotlib, preloads into the interactive | |
2954 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2966 | namespace all of numpy and pylab, and configures IPython to correctly | |
2955 | interact with the GUI event loop. The GUI backend to be used can be |
|
2967 | interact with the GUI event loop. The GUI backend to be used can be | |
2956 | optionally selected with the optional ``gui`` argument. |
|
2968 | optionally selected with the optional ``gui`` argument. | |
2957 |
|
2969 | |||
2958 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
2970 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. | |
2959 |
|
2971 | |||
2960 | Parameters |
|
2972 | Parameters | |
2961 | ---------- |
|
2973 | ---------- | |
2962 | gui : optional, string |
|
2974 | gui : optional, string | |
2963 | If given, dictates the choice of matplotlib GUI backend to use |
|
2975 | If given, dictates the choice of matplotlib GUI backend to use | |
2964 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2976 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2965 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2977 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2966 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2978 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2967 | user's matplotlibrc configuration file). Note that not all backends |
|
2979 | user's matplotlibrc configuration file). Note that not all backends | |
2968 | make sense in all contexts, for example a terminal ipython can't |
|
2980 | make sense in all contexts, for example a terminal ipython can't | |
2969 | display figures inline. |
|
2981 | display figures inline. | |
2970 | import_all : optional, bool, default: True |
|
2982 | import_all : optional, bool, default: True | |
2971 | Whether to do `from numpy import *` and `from pylab import *` |
|
2983 | Whether to do `from numpy import *` and `from pylab import *` | |
2972 | in addition to module imports. |
|
2984 | in addition to module imports. | |
2973 | welcome_message : deprecated |
|
2985 | welcome_message : deprecated | |
2974 | This argument is ignored, no welcome message will be displayed. |
|
2986 | This argument is ignored, no welcome message will be displayed. | |
2975 | """ |
|
2987 | """ | |
2976 | from IPython.core.pylabtools import import_pylab |
|
2988 | from IPython.core.pylabtools import import_pylab | |
2977 |
|
2989 | |||
2978 | gui, backend = self.enable_matplotlib(gui) |
|
2990 | gui, backend = self.enable_matplotlib(gui) | |
2979 |
|
2991 | |||
2980 | # We want to prevent the loading of pylab to pollute the user's |
|
2992 | # We want to prevent the loading of pylab to pollute the user's | |
2981 | # namespace as shown by the %who* magics, so we execute the activation |
|
2993 | # namespace as shown by the %who* magics, so we execute the activation | |
2982 | # code in an empty namespace, and we update *both* user_ns and |
|
2994 | # code in an empty namespace, and we update *both* user_ns and | |
2983 | # user_ns_hidden with this information. |
|
2995 | # user_ns_hidden with this information. | |
2984 | ns = {} |
|
2996 | ns = {} | |
2985 | import_pylab(ns, import_all) |
|
2997 | import_pylab(ns, import_all) | |
2986 | # warn about clobbered names |
|
2998 | # warn about clobbered names | |
2987 | ignored = {"__builtins__"} |
|
2999 | ignored = {"__builtins__"} | |
2988 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
3000 | both = set(ns).intersection(self.user_ns).difference(ignored) | |
2989 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
3001 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] | |
2990 | self.user_ns.update(ns) |
|
3002 | self.user_ns.update(ns) | |
2991 | self.user_ns_hidden.update(ns) |
|
3003 | self.user_ns_hidden.update(ns) | |
2992 | return gui, backend, clobbered |
|
3004 | return gui, backend, clobbered | |
2993 |
|
3005 | |||
2994 | #------------------------------------------------------------------------- |
|
3006 | #------------------------------------------------------------------------- | |
2995 | # Utilities |
|
3007 | # Utilities | |
2996 | #------------------------------------------------------------------------- |
|
3008 | #------------------------------------------------------------------------- | |
2997 |
|
3009 | |||
2998 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3010 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
2999 | """Expand python variables in a string. |
|
3011 | """Expand python variables in a string. | |
3000 |
|
3012 | |||
3001 | The depth argument indicates how many frames above the caller should |
|
3013 | The depth argument indicates how many frames above the caller should | |
3002 | be walked to look for the local namespace where to expand variables. |
|
3014 | be walked to look for the local namespace where to expand variables. | |
3003 |
|
3015 | |||
3004 | The global namespace for expansion is always the user's interactive |
|
3016 | The global namespace for expansion is always the user's interactive | |
3005 | namespace. |
|
3017 | namespace. | |
3006 | """ |
|
3018 | """ | |
3007 | ns = self.user_ns.copy() |
|
3019 | ns = self.user_ns.copy() | |
3008 | try: |
|
3020 | try: | |
3009 | frame = sys._getframe(depth+1) |
|
3021 | frame = sys._getframe(depth+1) | |
3010 | except ValueError: |
|
3022 | except ValueError: | |
3011 | # This is thrown if there aren't that many frames on the stack, |
|
3023 | # This is thrown if there aren't that many frames on the stack, | |
3012 | # e.g. if a script called run_line_magic() directly. |
|
3024 | # e.g. if a script called run_line_magic() directly. | |
3013 | pass |
|
3025 | pass | |
3014 | else: |
|
3026 | else: | |
3015 | ns.update(frame.f_locals) |
|
3027 | ns.update(frame.f_locals) | |
3016 |
|
3028 | |||
3017 | try: |
|
3029 | try: | |
3018 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3030 | # We have to use .vformat() here, because 'self' is a valid and common | |
3019 | # name, and expanding **ns for .format() would make it collide with |
|
3031 | # name, and expanding **ns for .format() would make it collide with | |
3020 | # the 'self' argument of the method. |
|
3032 | # the 'self' argument of the method. | |
3021 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3033 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) | |
3022 | except Exception: |
|
3034 | except Exception: | |
3023 | # if formatter couldn't format, just let it go untransformed |
|
3035 | # if formatter couldn't format, just let it go untransformed | |
3024 | pass |
|
3036 | pass | |
3025 | return cmd |
|
3037 | return cmd | |
3026 |
|
3038 | |||
3027 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3039 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
3028 | """Make a new tempfile and return its filename. |
|
3040 | """Make a new tempfile and return its filename. | |
3029 |
|
3041 | |||
3030 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3042 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), | |
3031 | but it registers the created filename internally so ipython cleans it up |
|
3043 | but it registers the created filename internally so ipython cleans it up | |
3032 | at exit time. |
|
3044 | at exit time. | |
3033 |
|
3045 | |||
3034 | Optional inputs: |
|
3046 | Optional inputs: | |
3035 |
|
3047 | |||
3036 | - data(None): if data is given, it gets written out to the temp file |
|
3048 | - data(None): if data is given, it gets written out to the temp file | |
3037 | immediately, and the file is closed again.""" |
|
3049 | immediately, and the file is closed again.""" | |
3038 |
|
3050 | |||
3039 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3051 | dirname = tempfile.mkdtemp(prefix=prefix) | |
3040 | self.tempdirs.append(dirname) |
|
3052 | self.tempdirs.append(dirname) | |
3041 |
|
3053 | |||
3042 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3054 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) | |
3043 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3055 | os.close(handle) # On Windows, there can only be one open handle on a file | |
3044 | self.tempfiles.append(filename) |
|
3056 | self.tempfiles.append(filename) | |
3045 |
|
3057 | |||
3046 | if data: |
|
3058 | if data: | |
3047 | tmp_file = open(filename,'w') |
|
3059 | tmp_file = open(filename,'w') | |
3048 | tmp_file.write(data) |
|
3060 | tmp_file.write(data) | |
3049 | tmp_file.close() |
|
3061 | tmp_file.close() | |
3050 | return filename |
|
3062 | return filename | |
3051 |
|
3063 | |||
3052 | @undoc |
|
3064 | @undoc | |
3053 | def write(self,data): |
|
3065 | def write(self,data): | |
3054 | """DEPRECATED: Write a string to the default output""" |
|
3066 | """DEPRECATED: Write a string to the default output""" | |
3055 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3067 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', | |
3056 | DeprecationWarning, stacklevel=2) |
|
3068 | DeprecationWarning, stacklevel=2) | |
3057 | sys.stdout.write(data) |
|
3069 | sys.stdout.write(data) | |
3058 |
|
3070 | |||
3059 | @undoc |
|
3071 | @undoc | |
3060 | def write_err(self,data): |
|
3072 | def write_err(self,data): | |
3061 | """DEPRECATED: Write a string to the default error output""" |
|
3073 | """DEPRECATED: Write a string to the default error output""" | |
3062 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3074 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', | |
3063 | DeprecationWarning, stacklevel=2) |
|
3075 | DeprecationWarning, stacklevel=2) | |
3064 | sys.stderr.write(data) |
|
3076 | sys.stderr.write(data) | |
3065 |
|
3077 | |||
3066 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3078 | def ask_yes_no(self, prompt, default=None, interrupt=None): | |
3067 | if self.quiet: |
|
3079 | if self.quiet: | |
3068 | return True |
|
3080 | return True | |
3069 | return ask_yes_no(prompt,default,interrupt) |
|
3081 | return ask_yes_no(prompt,default,interrupt) | |
3070 |
|
3082 | |||
3071 | def show_usage(self): |
|
3083 | def show_usage(self): | |
3072 | """Show a usage message""" |
|
3084 | """Show a usage message""" | |
3073 | page.page(IPython.core.usage.interactive_usage) |
|
3085 | page.page(IPython.core.usage.interactive_usage) | |
3074 |
|
3086 | |||
3075 | def extract_input_lines(self, range_str, raw=False): |
|
3087 | def extract_input_lines(self, range_str, raw=False): | |
3076 | """Return as a string a set of input history slices. |
|
3088 | """Return as a string a set of input history slices. | |
3077 |
|
3089 | |||
3078 | Parameters |
|
3090 | Parameters | |
3079 | ---------- |
|
3091 | ---------- | |
3080 | range_str : string |
|
3092 | range_str : string | |
3081 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3093 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
3082 | since this function is for use by magic functions which get their |
|
3094 | since this function is for use by magic functions which get their | |
3083 | arguments as strings. The number before the / is the session |
|
3095 | arguments as strings. The number before the / is the session | |
3084 | number: ~n goes n back from the current session. |
|
3096 | number: ~n goes n back from the current session. | |
3085 |
|
3097 | |||
3086 | raw : bool, optional |
|
3098 | raw : bool, optional | |
3087 | By default, the processed input is used. If this is true, the raw |
|
3099 | By default, the processed input is used. If this is true, the raw | |
3088 | input history is used instead. |
|
3100 | input history is used instead. | |
3089 |
|
3101 | |||
3090 | Notes |
|
3102 | Notes | |
3091 | ----- |
|
3103 | ----- | |
3092 |
|
3104 | |||
3093 | Slices can be described with two notations: |
|
3105 | Slices can be described with two notations: | |
3094 |
|
3106 | |||
3095 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3107 | * ``N:M`` -> standard python form, means including items N...(M-1). | |
3096 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3108 | * ``N-M`` -> include items N..M (closed endpoint). | |
3097 | """ |
|
3109 | """ | |
3098 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3110 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) | |
3099 | return "\n".join(x for _, _, x in lines) |
|
3111 | return "\n".join(x for _, _, x in lines) | |
3100 |
|
3112 | |||
3101 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3113 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): | |
3102 | """Get a code string from history, file, url, or a string or macro. |
|
3114 | """Get a code string from history, file, url, or a string or macro. | |
3103 |
|
3115 | |||
3104 | This is mainly used by magic functions. |
|
3116 | This is mainly used by magic functions. | |
3105 |
|
3117 | |||
3106 | Parameters |
|
3118 | Parameters | |
3107 | ---------- |
|
3119 | ---------- | |
3108 |
|
3120 | |||
3109 | target : str |
|
3121 | target : str | |
3110 |
|
3122 | |||
3111 | A string specifying code to retrieve. This will be tried respectively |
|
3123 | A string specifying code to retrieve. This will be tried respectively | |
3112 | as: ranges of input history (see %history for syntax), url, |
|
3124 | as: ranges of input history (see %history for syntax), url, | |
3113 | corresponding .py file, filename, or an expression evaluating to a |
|
3125 | corresponding .py file, filename, or an expression evaluating to a | |
3114 | string or Macro in the user namespace. |
|
3126 | string or Macro in the user namespace. | |
3115 |
|
3127 | |||
3116 | raw : bool |
|
3128 | raw : bool | |
3117 | If true (default), retrieve raw history. Has no effect on the other |
|
3129 | If true (default), retrieve raw history. Has no effect on the other | |
3118 | retrieval mechanisms. |
|
3130 | retrieval mechanisms. | |
3119 |
|
3131 | |||
3120 | py_only : bool (default False) |
|
3132 | py_only : bool (default False) | |
3121 | Only try to fetch python code, do not try alternative methods to decode file |
|
3133 | Only try to fetch python code, do not try alternative methods to decode file | |
3122 | if unicode fails. |
|
3134 | if unicode fails. | |
3123 |
|
3135 | |||
3124 | Returns |
|
3136 | Returns | |
3125 | ------- |
|
3137 | ------- | |
3126 | A string of code. |
|
3138 | A string of code. | |
3127 |
|
3139 | |||
3128 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3140 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
3129 | to an object of another type. In each case, .args[0] is a printable |
|
3141 | to an object of another type. In each case, .args[0] is a printable | |
3130 | message. |
|
3142 | message. | |
3131 | """ |
|
3143 | """ | |
3132 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3144 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
3133 | if code: |
|
3145 | if code: | |
3134 | return code |
|
3146 | return code | |
3135 | try: |
|
3147 | try: | |
3136 | if target.startswith(('http://', 'https://')): |
|
3148 | if target.startswith(('http://', 'https://')): | |
3137 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3149 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) | |
3138 | except UnicodeDecodeError: |
|
3150 | except UnicodeDecodeError: | |
3139 | if not py_only : |
|
3151 | if not py_only : | |
3140 | # Deferred import |
|
3152 | # Deferred import | |
3141 | try: |
|
3153 | try: | |
3142 | from urllib.request import urlopen # Py3 |
|
3154 | from urllib.request import urlopen # Py3 | |
3143 | except ImportError: |
|
3155 | except ImportError: | |
3144 | from urllib import urlopen |
|
3156 | from urllib import urlopen | |
3145 | response = urlopen(target) |
|
3157 | response = urlopen(target) | |
3146 | return response.read().decode('latin1') |
|
3158 | return response.read().decode('latin1') | |
3147 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3159 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3148 |
|
3160 | |||
3149 | potential_target = [target] |
|
3161 | potential_target = [target] | |
3150 | try : |
|
3162 | try : | |
3151 | potential_target.insert(0,get_py_filename(target)) |
|
3163 | potential_target.insert(0,get_py_filename(target)) | |
3152 | except IOError: |
|
3164 | except IOError: | |
3153 | pass |
|
3165 | pass | |
3154 |
|
3166 | |||
3155 | for tgt in potential_target : |
|
3167 | for tgt in potential_target : | |
3156 | if os.path.isfile(tgt): # Read file |
|
3168 | if os.path.isfile(tgt): # Read file | |
3157 | try : |
|
3169 | try : | |
3158 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3170 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) | |
3159 | except UnicodeDecodeError : |
|
3171 | except UnicodeDecodeError : | |
3160 | if not py_only : |
|
3172 | if not py_only : | |
3161 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3173 | with io_open(tgt,'r', encoding='latin1') as f : | |
3162 | return f.read() |
|
3174 | return f.read() | |
3163 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3175 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3164 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3176 | elif os.path.isdir(os.path.expanduser(tgt)): | |
3165 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3177 | raise ValueError("'%s' is a directory, not a regular file." % target) | |
3166 |
|
3178 | |||
3167 | if search_ns: |
|
3179 | if search_ns: | |
3168 | # Inspect namespace to load object source |
|
3180 | # Inspect namespace to load object source | |
3169 | object_info = self.object_inspect(target, detail_level=1) |
|
3181 | object_info = self.object_inspect(target, detail_level=1) | |
3170 | if object_info['found'] and object_info['source']: |
|
3182 | if object_info['found'] and object_info['source']: | |
3171 | return object_info['source'] |
|
3183 | return object_info['source'] | |
3172 |
|
3184 | |||
3173 | try: # User namespace |
|
3185 | try: # User namespace | |
3174 | codeobj = eval(target, self.user_ns) |
|
3186 | codeobj = eval(target, self.user_ns) | |
3175 | except Exception: |
|
3187 | except Exception: | |
3176 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3188 | raise ValueError(("'%s' was not found in history, as a file, url, " | |
3177 | "nor in the user namespace.") % target) |
|
3189 | "nor in the user namespace.") % target) | |
3178 |
|
3190 | |||
3179 | if isinstance(codeobj, string_types): |
|
3191 | if isinstance(codeobj, string_types): | |
3180 | return codeobj |
|
3192 | return codeobj | |
3181 | elif isinstance(codeobj, Macro): |
|
3193 | elif isinstance(codeobj, Macro): | |
3182 | return codeobj.value |
|
3194 | return codeobj.value | |
3183 |
|
3195 | |||
3184 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3196 | raise TypeError("%s is neither a string nor a macro." % target, | |
3185 | codeobj) |
|
3197 | codeobj) | |
3186 |
|
3198 | |||
3187 | #------------------------------------------------------------------------- |
|
3199 | #------------------------------------------------------------------------- | |
3188 | # Things related to IPython exiting |
|
3200 | # Things related to IPython exiting | |
3189 | #------------------------------------------------------------------------- |
|
3201 | #------------------------------------------------------------------------- | |
3190 | def atexit_operations(self): |
|
3202 | def atexit_operations(self): | |
3191 | """This will be executed at the time of exit. |
|
3203 | """This will be executed at the time of exit. | |
3192 |
|
3204 | |||
3193 | Cleanup operations and saving of persistent data that is done |
|
3205 | Cleanup operations and saving of persistent data that is done | |
3194 | unconditionally by IPython should be performed here. |
|
3206 | unconditionally by IPython should be performed here. | |
3195 |
|
3207 | |||
3196 | For things that may depend on startup flags or platform specifics (such |
|
3208 | For things that may depend on startup flags or platform specifics (such | |
3197 | as having readline or not), register a separate atexit function in the |
|
3209 | as having readline or not), register a separate atexit function in the | |
3198 | code that has the appropriate information, rather than trying to |
|
3210 | code that has the appropriate information, rather than trying to | |
3199 | clutter |
|
3211 | clutter | |
3200 | """ |
|
3212 | """ | |
3201 | # Close the history session (this stores the end time and line count) |
|
3213 | # Close the history session (this stores the end time and line count) | |
3202 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3214 | # this must be *before* the tempfile cleanup, in case of temporary | |
3203 | # history db |
|
3215 | # history db | |
3204 | self.history_manager.end_session() |
|
3216 | self.history_manager.end_session() | |
3205 |
|
3217 | |||
3206 | # Cleanup all tempfiles and folders left around |
|
3218 | # Cleanup all tempfiles and folders left around | |
3207 | for tfile in self.tempfiles: |
|
3219 | for tfile in self.tempfiles: | |
3208 | try: |
|
3220 | try: | |
3209 | os.unlink(tfile) |
|
3221 | os.unlink(tfile) | |
3210 | except OSError: |
|
3222 | except OSError: | |
3211 | pass |
|
3223 | pass | |
3212 |
|
3224 | |||
3213 | for tdir in self.tempdirs: |
|
3225 | for tdir in self.tempdirs: | |
3214 | try: |
|
3226 | try: | |
3215 | os.rmdir(tdir) |
|
3227 | os.rmdir(tdir) | |
3216 | except OSError: |
|
3228 | except OSError: | |
3217 | pass |
|
3229 | pass | |
3218 |
|
3230 | |||
3219 | # Clear all user namespaces to release all references cleanly. |
|
3231 | # Clear all user namespaces to release all references cleanly. | |
3220 | self.reset(new_session=False) |
|
3232 | self.reset(new_session=False) | |
3221 |
|
3233 | |||
3222 | # Run user hooks |
|
3234 | # Run user hooks | |
3223 | self.hooks.shutdown_hook() |
|
3235 | self.hooks.shutdown_hook() | |
3224 |
|
3236 | |||
3225 | def cleanup(self): |
|
3237 | def cleanup(self): | |
3226 | self.restore_sys_module_state() |
|
3238 | self.restore_sys_module_state() | |
3227 |
|
3239 | |||
3228 |
|
3240 | |||
3229 | # Overridden in terminal subclass to change prompts |
|
3241 | # Overridden in terminal subclass to change prompts | |
3230 | def switch_doctest_mode(self, mode): |
|
3242 | def switch_doctest_mode(self, mode): | |
3231 | pass |
|
3243 | pass | |
3232 |
|
3244 | |||
3233 |
|
3245 | |||
3234 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): |
|
3246 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): | |
3235 | """An abstract base class for InteractiveShell.""" |
|
3247 | """An abstract base class for InteractiveShell.""" | |
3236 |
|
3248 | |||
3237 | InteractiveShellABC.register(InteractiveShell) |
|
3249 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,928 +1,933 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tools for inspecting Python objects. |
|
2 | """Tools for inspecting Python objects. | |
3 |
|
3 | |||
4 | Uses syntax highlighting for presenting the various information elements. |
|
4 | Uses syntax highlighting for presenting the various information elements. | |
5 |
|
5 | |||
6 | Similar in spirit to the inspect module, but all calls take a name argument to |
|
6 | Similar in spirit to the inspect module, but all calls take a name argument to | |
7 | reference the name under which an object is being read. |
|
7 | reference the name under which an object is being read. | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | # Copyright (c) IPython Development Team. |
|
10 | # Copyright (c) IPython Development Team. | |
11 | # Distributed under the terms of the Modified BSD License. |
|
11 | # Distributed under the terms of the Modified BSD License. | |
12 |
|
12 | |||
13 | from __future__ import print_function |
|
13 | from __future__ import print_function | |
14 |
|
14 | |||
15 | __all__ = ['Inspector','InspectColors'] |
|
15 | __all__ = ['Inspector','InspectColors'] | |
16 |
|
16 | |||
17 | # stdlib modules |
|
17 | # stdlib modules | |
18 | import inspect |
|
18 | import inspect | |
19 | import linecache |
|
19 | import linecache | |
20 | import os |
|
20 | import os | |
21 | from textwrap import dedent |
|
21 | from textwrap import dedent | |
22 | import types |
|
22 | import types | |
23 | import io as stdlib_io |
|
23 | import io as stdlib_io | |
24 |
|
24 | |||
25 | try: |
|
25 | try: | |
26 | from itertools import izip_longest |
|
26 | from itertools import izip_longest | |
27 | except ImportError: |
|
27 | except ImportError: | |
28 | from itertools import zip_longest as izip_longest |
|
28 | from itertools import zip_longest as izip_longest | |
29 |
|
29 | |||
30 | # IPython's own |
|
30 | # IPython's own | |
31 | from IPython.core import page |
|
31 | from IPython.core import page | |
32 | from IPython.lib.pretty import pretty |
|
32 | from IPython.lib.pretty import pretty | |
33 | from IPython.testing.skipdoctest import skip_doctest_py3 |
|
33 | from IPython.testing.skipdoctest import skip_doctest_py3 | |
34 | from IPython.utils import PyColorize |
|
34 | from IPython.utils import PyColorize | |
35 | from IPython.utils import openpy |
|
35 | from IPython.utils import openpy | |
36 | from IPython.utils import py3compat |
|
36 | from IPython.utils import py3compat | |
37 | from IPython.utils.dir2 import safe_hasattr |
|
37 | from IPython.utils.dir2 import safe_hasattr | |
38 | from IPython.utils.path import compress_user |
|
38 | from IPython.utils.path import compress_user | |
39 | from IPython.utils.text import indent |
|
39 | from IPython.utils.text import indent | |
40 | from IPython.utils.wildcard import list_namespace |
|
40 | from IPython.utils.wildcard import list_namespace | |
41 | from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable |
|
41 | from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable | |
42 | from IPython.utils.py3compat import cast_unicode, string_types, PY3 |
|
42 | from IPython.utils.py3compat import cast_unicode, string_types, PY3 | |
43 | from IPython.utils.signatures import signature |
|
43 | from IPython.utils.signatures import signature | |
44 | from IPython.utils.colorable import Colorable |
|
44 | from IPython.utils.colorable import Colorable | |
45 |
|
45 | |||
46 | # builtin docstrings to ignore |
|
46 | # builtin docstrings to ignore | |
47 | _func_call_docstring = types.FunctionType.__call__.__doc__ |
|
47 | _func_call_docstring = types.FunctionType.__call__.__doc__ | |
48 | _object_init_docstring = object.__init__.__doc__ |
|
48 | _object_init_docstring = object.__init__.__doc__ | |
49 | _builtin_type_docstrings = { |
|
49 | _builtin_type_docstrings = { | |
50 | inspect.getdoc(t) for t in (types.ModuleType, types.MethodType, |
|
50 | inspect.getdoc(t) for t in (types.ModuleType, types.MethodType, | |
51 | types.FunctionType, property) |
|
51 | types.FunctionType, property) | |
52 | } |
|
52 | } | |
53 |
|
53 | |||
54 | _builtin_func_type = type(all) |
|
54 | _builtin_func_type = type(all) | |
55 | _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions |
|
55 | _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions | |
56 | #**************************************************************************** |
|
56 | #**************************************************************************** | |
57 | # Builtin color schemes |
|
57 | # Builtin color schemes | |
58 |
|
58 | |||
59 | Colors = TermColors # just a shorthand |
|
59 | Colors = TermColors # just a shorthand | |
60 |
|
60 | |||
61 | InspectColors = PyColorize.ANSICodeColors |
|
61 | InspectColors = PyColorize.ANSICodeColors | |
62 |
|
62 | |||
63 | #**************************************************************************** |
|
63 | #**************************************************************************** | |
64 | # Auxiliary functions and objects |
|
64 | # Auxiliary functions and objects | |
65 |
|
65 | |||
66 | # See the messaging spec for the definition of all these fields. This list |
|
66 | # See the messaging spec for the definition of all these fields. This list | |
67 | # effectively defines the order of display |
|
67 | # effectively defines the order of display | |
68 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', |
|
68 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', | |
69 | 'length', 'file', 'definition', 'docstring', 'source', |
|
69 | 'length', 'file', 'definition', 'docstring', 'source', | |
70 | 'init_definition', 'class_docstring', 'init_docstring', |
|
70 | 'init_definition', 'class_docstring', 'init_docstring', | |
71 | 'call_def', 'call_docstring', |
|
71 | 'call_def', 'call_docstring', | |
72 | # These won't be printed but will be used to determine how to |
|
72 | # These won't be printed but will be used to determine how to | |
73 | # format the object |
|
73 | # format the object | |
74 | 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name' |
|
74 | 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name' | |
75 | ] |
|
75 | ] | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | def object_info(**kw): |
|
78 | def object_info(**kw): | |
79 | """Make an object info dict with all fields present.""" |
|
79 | """Make an object info dict with all fields present.""" | |
80 | infodict = dict(izip_longest(info_fields, [None])) |
|
80 | infodict = dict(izip_longest(info_fields, [None])) | |
81 | infodict.update(kw) |
|
81 | infodict.update(kw) | |
82 | return infodict |
|
82 | return infodict | |
83 |
|
83 | |||
84 |
|
84 | |||
85 | def get_encoding(obj): |
|
85 | def get_encoding(obj): | |
86 | """Get encoding for python source file defining obj |
|
86 | """Get encoding for python source file defining obj | |
87 |
|
87 | |||
88 | Returns None if obj is not defined in a sourcefile. |
|
88 | Returns None if obj is not defined in a sourcefile. | |
89 | """ |
|
89 | """ | |
90 | ofile = find_file(obj) |
|
90 | ofile = find_file(obj) | |
91 | # run contents of file through pager starting at line where the object |
|
91 | # run contents of file through pager starting at line where the object | |
92 | # is defined, as long as the file isn't binary and is actually on the |
|
92 | # is defined, as long as the file isn't binary and is actually on the | |
93 | # filesystem. |
|
93 | # filesystem. | |
94 | if ofile is None: |
|
94 | if ofile is None: | |
95 | return None |
|
95 | return None | |
96 | elif ofile.endswith(('.so', '.dll', '.pyd')): |
|
96 | elif ofile.endswith(('.so', '.dll', '.pyd')): | |
97 | return None |
|
97 | return None | |
98 | elif not os.path.isfile(ofile): |
|
98 | elif not os.path.isfile(ofile): | |
99 | return None |
|
99 | return None | |
100 | else: |
|
100 | else: | |
101 | # Print only text files, not extension binaries. Note that |
|
101 | # Print only text files, not extension binaries. Note that | |
102 | # getsourcelines returns lineno with 1-offset and page() uses |
|
102 | # getsourcelines returns lineno with 1-offset and page() uses | |
103 | # 0-offset, so we must adjust. |
|
103 | # 0-offset, so we must adjust. | |
104 | with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2 |
|
104 | with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2 | |
105 | encoding, lines = openpy.detect_encoding(buffer.readline) |
|
105 | encoding, lines = openpy.detect_encoding(buffer.readline) | |
106 | return encoding |
|
106 | return encoding | |
107 |
|
107 | |||
108 | def getdoc(obj): |
|
108 | def getdoc(obj): | |
109 | """Stable wrapper around inspect.getdoc. |
|
109 | """Stable wrapper around inspect.getdoc. | |
110 |
|
110 | |||
111 | This can't crash because of attribute problems. |
|
111 | This can't crash because of attribute problems. | |
112 |
|
112 | |||
113 | It also attempts to call a getdoc() method on the given object. This |
|
113 | It also attempts to call a getdoc() method on the given object. This | |
114 | allows objects which provide their docstrings via non-standard mechanisms |
|
114 | allows objects which provide their docstrings via non-standard mechanisms | |
115 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
115 | (like Pyro proxies) to still be inspected by ipython's ? system.""" | |
116 | # Allow objects to offer customized documentation via a getdoc method: |
|
116 | # Allow objects to offer customized documentation via a getdoc method: | |
117 | try: |
|
117 | try: | |
118 | ds = obj.getdoc() |
|
118 | ds = obj.getdoc() | |
119 | except Exception: |
|
119 | except Exception: | |
120 | pass |
|
120 | pass | |
121 | else: |
|
121 | else: | |
122 | # if we get extra info, we add it to the normal docstring. |
|
122 | # if we get extra info, we add it to the normal docstring. | |
123 | if isinstance(ds, string_types): |
|
123 | if isinstance(ds, string_types): | |
124 | return inspect.cleandoc(ds) |
|
124 | return inspect.cleandoc(ds) | |
125 |
|
125 | |||
126 | try: |
|
126 | try: | |
127 | docstr = inspect.getdoc(obj) |
|
127 | docstr = inspect.getdoc(obj) | |
128 | encoding = get_encoding(obj) |
|
128 | encoding = get_encoding(obj) | |
129 | return py3compat.cast_unicode(docstr, encoding=encoding) |
|
129 | return py3compat.cast_unicode(docstr, encoding=encoding) | |
130 | except Exception: |
|
130 | except Exception: | |
131 | # Harden against an inspect failure, which can occur with |
|
131 | # Harden against an inspect failure, which can occur with | |
132 | # SWIG-wrapped extensions. |
|
132 | # SWIG-wrapped extensions. | |
133 | raise |
|
133 | raise | |
134 | return None |
|
134 | return None | |
135 |
|
135 | |||
136 |
|
136 | |||
137 | def getsource(obj, oname=''): |
|
137 | def getsource(obj, oname=''): | |
138 | """Wrapper around inspect.getsource. |
|
138 | """Wrapper around inspect.getsource. | |
139 |
|
139 | |||
140 | This can be modified by other projects to provide customized source |
|
140 | This can be modified by other projects to provide customized source | |
141 | extraction. |
|
141 | extraction. | |
142 |
|
142 | |||
143 | Parameters |
|
143 | Parameters | |
144 | ---------- |
|
144 | ---------- | |
145 | obj : object |
|
145 | obj : object | |
146 | an object whose source code we will attempt to extract |
|
146 | an object whose source code we will attempt to extract | |
147 | oname : str |
|
147 | oname : str | |
148 | (optional) a name under which the object is known |
|
148 | (optional) a name under which the object is known | |
149 |
|
149 | |||
150 | Returns |
|
150 | Returns | |
151 | ------- |
|
151 | ------- | |
152 | src : unicode or None |
|
152 | src : unicode or None | |
153 |
|
153 | |||
154 | """ |
|
154 | """ | |
155 |
|
155 | |||
156 | if isinstance(obj, property): |
|
156 | if isinstance(obj, property): | |
157 | sources = [] |
|
157 | sources = [] | |
158 | for attrname in ['fget', 'fset', 'fdel']: |
|
158 | for attrname in ['fget', 'fset', 'fdel']: | |
159 | fn = getattr(obj, attrname) |
|
159 | fn = getattr(obj, attrname) | |
160 | if fn is not None: |
|
160 | if fn is not None: | |
161 | encoding = get_encoding(fn) |
|
161 | encoding = get_encoding(fn) | |
162 | oname_prefix = ('%s.' % oname) if oname else '' |
|
162 | oname_prefix = ('%s.' % oname) if oname else '' | |
163 | sources.append(cast_unicode( |
|
163 | sources.append(cast_unicode( | |
164 | ''.join(('# ', oname_prefix, attrname)), |
|
164 | ''.join(('# ', oname_prefix, attrname)), | |
165 | encoding=encoding)) |
|
165 | encoding=encoding)) | |
166 | if inspect.isfunction(fn): |
|
166 | if inspect.isfunction(fn): | |
167 | sources.append(dedent(getsource(fn))) |
|
167 | sources.append(dedent(getsource(fn))) | |
168 | else: |
|
168 | else: | |
169 | # Default str/repr only prints function name, |
|
169 | # Default str/repr only prints function name, | |
170 | # pretty.pretty prints module name too. |
|
170 | # pretty.pretty prints module name too. | |
171 | sources.append(cast_unicode( |
|
171 | sources.append(cast_unicode( | |
172 | '%s%s = %s\n' % ( |
|
172 | '%s%s = %s\n' % ( | |
173 | oname_prefix, attrname, pretty(fn)), |
|
173 | oname_prefix, attrname, pretty(fn)), | |
174 | encoding=encoding)) |
|
174 | encoding=encoding)) | |
175 | if sources: |
|
175 | if sources: | |
176 | return '\n'.join(sources) |
|
176 | return '\n'.join(sources) | |
177 | else: |
|
177 | else: | |
178 | return None |
|
178 | return None | |
179 |
|
179 | |||
180 | else: |
|
180 | else: | |
181 | # Get source for non-property objects. |
|
181 | # Get source for non-property objects. | |
182 |
|
182 | |||
183 | obj = _get_wrapped(obj) |
|
183 | obj = _get_wrapped(obj) | |
184 |
|
184 | |||
185 | try: |
|
185 | try: | |
186 | src = inspect.getsource(obj) |
|
186 | src = inspect.getsource(obj) | |
187 | except TypeError: |
|
187 | except TypeError: | |
188 | # The object itself provided no meaningful source, try looking for |
|
188 | # The object itself provided no meaningful source, try looking for | |
189 | # its class definition instead. |
|
189 | # its class definition instead. | |
190 | if hasattr(obj, '__class__'): |
|
190 | if hasattr(obj, '__class__'): | |
191 | try: |
|
191 | try: | |
192 | src = inspect.getsource(obj.__class__) |
|
192 | src = inspect.getsource(obj.__class__) | |
193 | except TypeError: |
|
193 | except TypeError: | |
194 | return None |
|
194 | return None | |
195 |
|
195 | |||
196 | encoding = get_encoding(obj) |
|
196 | encoding = get_encoding(obj) | |
197 | return cast_unicode(src, encoding=encoding) |
|
197 | return cast_unicode(src, encoding=encoding) | |
198 |
|
198 | |||
199 |
|
199 | |||
200 | def is_simple_callable(obj): |
|
200 | def is_simple_callable(obj): | |
201 | """True if obj is a function ()""" |
|
201 | """True if obj is a function ()""" | |
202 | return (inspect.isfunction(obj) or inspect.ismethod(obj) or \ |
|
202 | return (inspect.isfunction(obj) or inspect.ismethod(obj) or \ | |
203 | isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type)) |
|
203 | isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type)) | |
204 |
|
204 | |||
205 |
|
205 | |||
206 | def getargspec(obj): |
|
206 | def getargspec(obj): | |
207 | """Wrapper around :func:`inspect.getfullargspec` on Python 3, and |
|
207 | """Wrapper around :func:`inspect.getfullargspec` on Python 3, and | |
208 | :func:inspect.getargspec` on Python 2. |
|
208 | :func:inspect.getargspec` on Python 2. | |
209 |
|
209 | |||
210 | In addition to functions and methods, this can also handle objects with a |
|
210 | In addition to functions and methods, this can also handle objects with a | |
211 | ``__call__`` attribute. |
|
211 | ``__call__`` attribute. | |
212 | """ |
|
212 | """ | |
213 | if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): |
|
213 | if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): | |
214 | obj = obj.__call__ |
|
214 | obj = obj.__call__ | |
215 |
|
215 | |||
216 | return inspect.getfullargspec(obj) if PY3 else inspect.getargspec(obj) |
|
216 | return inspect.getfullargspec(obj) if PY3 else inspect.getargspec(obj) | |
217 |
|
217 | |||
218 |
|
218 | |||
219 | def format_argspec(argspec): |
|
219 | def format_argspec(argspec): | |
220 | """Format argspect, convenience wrapper around inspect's. |
|
220 | """Format argspect, convenience wrapper around inspect's. | |
221 |
|
221 | |||
222 | This takes a dict instead of ordered arguments and calls |
|
222 | This takes a dict instead of ordered arguments and calls | |
223 | inspect.format_argspec with the arguments in the necessary order. |
|
223 | inspect.format_argspec with the arguments in the necessary order. | |
224 | """ |
|
224 | """ | |
225 | return inspect.formatargspec(argspec['args'], argspec['varargs'], |
|
225 | return inspect.formatargspec(argspec['args'], argspec['varargs'], | |
226 | argspec['varkw'], argspec['defaults']) |
|
226 | argspec['varkw'], argspec['defaults']) | |
227 |
|
227 | |||
228 |
|
228 | |||
229 | def call_tip(oinfo, format_call=True): |
|
229 | def call_tip(oinfo, format_call=True): | |
230 | """Extract call tip data from an oinfo dict. |
|
230 | """Extract call tip data from an oinfo dict. | |
231 |
|
231 | |||
232 | Parameters |
|
232 | Parameters | |
233 | ---------- |
|
233 | ---------- | |
234 | oinfo : dict |
|
234 | oinfo : dict | |
235 |
|
235 | |||
236 | format_call : bool, optional |
|
236 | format_call : bool, optional | |
237 | If True, the call line is formatted and returned as a string. If not, a |
|
237 | If True, the call line is formatted and returned as a string. If not, a | |
238 | tuple of (name, argspec) is returned. |
|
238 | tuple of (name, argspec) is returned. | |
239 |
|
239 | |||
240 | Returns |
|
240 | Returns | |
241 | ------- |
|
241 | ------- | |
242 | call_info : None, str or (str, dict) tuple. |
|
242 | call_info : None, str or (str, dict) tuple. | |
243 | When format_call is True, the whole call information is formattted as a |
|
243 | When format_call is True, the whole call information is formattted as a | |
244 | single string. Otherwise, the object's name and its argspec dict are |
|
244 | single string. Otherwise, the object's name and its argspec dict are | |
245 | returned. If no call information is available, None is returned. |
|
245 | returned. If no call information is available, None is returned. | |
246 |
|
246 | |||
247 | docstring : str or None |
|
247 | docstring : str or None | |
248 | The most relevant docstring for calling purposes is returned, if |
|
248 | The most relevant docstring for calling purposes is returned, if | |
249 | available. The priority is: call docstring for callable instances, then |
|
249 | available. The priority is: call docstring for callable instances, then | |
250 | constructor docstring for classes, then main object's docstring otherwise |
|
250 | constructor docstring for classes, then main object's docstring otherwise | |
251 | (regular functions). |
|
251 | (regular functions). | |
252 | """ |
|
252 | """ | |
253 | # Get call definition |
|
253 | # Get call definition | |
254 | argspec = oinfo.get('argspec') |
|
254 | argspec = oinfo.get('argspec') | |
255 | if argspec is None: |
|
255 | if argspec is None: | |
256 | call_line = None |
|
256 | call_line = None | |
257 | else: |
|
257 | else: | |
258 | # Callable objects will have 'self' as their first argument, prune |
|
258 | # Callable objects will have 'self' as their first argument, prune | |
259 | # it out if it's there for clarity (since users do *not* pass an |
|
259 | # it out if it's there for clarity (since users do *not* pass an | |
260 | # extra first argument explicitly). |
|
260 | # extra first argument explicitly). | |
261 | try: |
|
261 | try: | |
262 | has_self = argspec['args'][0] == 'self' |
|
262 | has_self = argspec['args'][0] == 'self' | |
263 | except (KeyError, IndexError): |
|
263 | except (KeyError, IndexError): | |
264 | pass |
|
264 | pass | |
265 | else: |
|
265 | else: | |
266 | if has_self: |
|
266 | if has_self: | |
267 | argspec['args'] = argspec['args'][1:] |
|
267 | argspec['args'] = argspec['args'][1:] | |
268 |
|
268 | |||
269 | call_line = oinfo['name']+format_argspec(argspec) |
|
269 | call_line = oinfo['name']+format_argspec(argspec) | |
270 |
|
270 | |||
271 | # Now get docstring. |
|
271 | # Now get docstring. | |
272 | # The priority is: call docstring, constructor docstring, main one. |
|
272 | # The priority is: call docstring, constructor docstring, main one. | |
273 | doc = oinfo.get('call_docstring') |
|
273 | doc = oinfo.get('call_docstring') | |
274 | if doc is None: |
|
274 | if doc is None: | |
275 | doc = oinfo.get('init_docstring') |
|
275 | doc = oinfo.get('init_docstring') | |
276 | if doc is None: |
|
276 | if doc is None: | |
277 | doc = oinfo.get('docstring','') |
|
277 | doc = oinfo.get('docstring','') | |
278 |
|
278 | |||
279 | return call_line, doc |
|
279 | return call_line, doc | |
280 |
|
280 | |||
281 |
|
281 | |||
282 | def _get_wrapped(obj): |
|
282 | def _get_wrapped(obj): | |
283 | """Get the original object if wrapped in one or more @decorators |
|
283 | """Get the original object if wrapped in one or more @decorators | |
284 |
|
284 | |||
285 | Some objects automatically construct similar objects on any unrecognised |
|
285 | Some objects automatically construct similar objects on any unrecognised | |
286 | attribute access (e.g. unittest.mock.call). To protect against infinite loops, |
|
286 | attribute access (e.g. unittest.mock.call). To protect against infinite loops, | |
287 | this will arbitrarily cut off after 100 levels of obj.__wrapped__ |
|
287 | this will arbitrarily cut off after 100 levels of obj.__wrapped__ | |
288 | attribute access. --TK, Jan 2016 |
|
288 | attribute access. --TK, Jan 2016 | |
289 | """ |
|
289 | """ | |
290 | orig_obj = obj |
|
290 | orig_obj = obj | |
291 | i = 0 |
|
291 | i = 0 | |
292 | while safe_hasattr(obj, '__wrapped__'): |
|
292 | while safe_hasattr(obj, '__wrapped__'): | |
293 | obj = obj.__wrapped__ |
|
293 | obj = obj.__wrapped__ | |
294 | i += 1 |
|
294 | i += 1 | |
295 | if i > 100: |
|
295 | if i > 100: | |
296 | # __wrapped__ is probably a lie, so return the thing we started with |
|
296 | # __wrapped__ is probably a lie, so return the thing we started with | |
297 | return orig_obj |
|
297 | return orig_obj | |
298 | return obj |
|
298 | return obj | |
299 |
|
299 | |||
300 | def find_file(obj): |
|
300 | def find_file(obj): | |
301 | """Find the absolute path to the file where an object was defined. |
|
301 | """Find the absolute path to the file where an object was defined. | |
302 |
|
302 | |||
303 | This is essentially a robust wrapper around `inspect.getabsfile`. |
|
303 | This is essentially a robust wrapper around `inspect.getabsfile`. | |
304 |
|
304 | |||
305 | Returns None if no file can be found. |
|
305 | Returns None if no file can be found. | |
306 |
|
306 | |||
307 | Parameters |
|
307 | Parameters | |
308 | ---------- |
|
308 | ---------- | |
309 | obj : any Python object |
|
309 | obj : any Python object | |
310 |
|
310 | |||
311 | Returns |
|
311 | Returns | |
312 | ------- |
|
312 | ------- | |
313 | fname : str |
|
313 | fname : str | |
314 | The absolute path to the file where the object was defined. |
|
314 | The absolute path to the file where the object was defined. | |
315 | """ |
|
315 | """ | |
316 | obj = _get_wrapped(obj) |
|
316 | obj = _get_wrapped(obj) | |
317 |
|
317 | |||
318 | fname = None |
|
318 | fname = None | |
319 | try: |
|
319 | try: | |
320 | fname = inspect.getabsfile(obj) |
|
320 | fname = inspect.getabsfile(obj) | |
321 | except TypeError: |
|
321 | except TypeError: | |
322 | # For an instance, the file that matters is where its class was |
|
322 | # For an instance, the file that matters is where its class was | |
323 | # declared. |
|
323 | # declared. | |
324 | if hasattr(obj, '__class__'): |
|
324 | if hasattr(obj, '__class__'): | |
325 | try: |
|
325 | try: | |
326 | fname = inspect.getabsfile(obj.__class__) |
|
326 | fname = inspect.getabsfile(obj.__class__) | |
327 | except TypeError: |
|
327 | except TypeError: | |
328 | # Can happen for builtins |
|
328 | # Can happen for builtins | |
329 | pass |
|
329 | pass | |
330 | except: |
|
330 | except: | |
331 | pass |
|
331 | pass | |
332 | return cast_unicode(fname) |
|
332 | return cast_unicode(fname) | |
333 |
|
333 | |||
334 |
|
334 | |||
335 | def find_source_lines(obj): |
|
335 | def find_source_lines(obj): | |
336 | """Find the line number in a file where an object was defined. |
|
336 | """Find the line number in a file where an object was defined. | |
337 |
|
337 | |||
338 | This is essentially a robust wrapper around `inspect.getsourcelines`. |
|
338 | This is essentially a robust wrapper around `inspect.getsourcelines`. | |
339 |
|
339 | |||
340 | Returns None if no file can be found. |
|
340 | Returns None if no file can be found. | |
341 |
|
341 | |||
342 | Parameters |
|
342 | Parameters | |
343 | ---------- |
|
343 | ---------- | |
344 | obj : any Python object |
|
344 | obj : any Python object | |
345 |
|
345 | |||
346 | Returns |
|
346 | Returns | |
347 | ------- |
|
347 | ------- | |
348 | lineno : int |
|
348 | lineno : int | |
349 | The line number where the object definition starts. |
|
349 | The line number where the object definition starts. | |
350 | """ |
|
350 | """ | |
351 | obj = _get_wrapped(obj) |
|
351 | obj = _get_wrapped(obj) | |
352 |
|
352 | |||
353 | try: |
|
353 | try: | |
354 | try: |
|
354 | try: | |
355 | lineno = inspect.getsourcelines(obj)[1] |
|
355 | lineno = inspect.getsourcelines(obj)[1] | |
356 | except TypeError: |
|
356 | except TypeError: | |
357 | # For instances, try the class object like getsource() does |
|
357 | # For instances, try the class object like getsource() does | |
358 | if hasattr(obj, '__class__'): |
|
358 | if hasattr(obj, '__class__'): | |
359 | lineno = inspect.getsourcelines(obj.__class__)[1] |
|
359 | lineno = inspect.getsourcelines(obj.__class__)[1] | |
360 | else: |
|
360 | else: | |
361 | lineno = None |
|
361 | lineno = None | |
362 | except: |
|
362 | except: | |
363 | return None |
|
363 | return None | |
364 |
|
364 | |||
365 | return lineno |
|
365 | return lineno | |
366 |
|
366 | |||
367 |
|
367 | |||
368 | class Inspector(Colorable): |
|
368 | class Inspector(Colorable): | |
369 | def __init__(self, color_table=InspectColors, |
|
369 | def __init__(self, color_table=InspectColors, | |
370 | code_color_table=PyColorize.ANSICodeColors, |
|
370 | code_color_table=PyColorize.ANSICodeColors, | |
371 | scheme='NoColor', |
|
371 | scheme='NoColor', | |
372 | str_detail_level=0, |
|
372 | str_detail_level=0, | |
373 | parent=None, config=None): |
|
373 | parent=None, config=None): | |
374 | super(Inspector, self).__init__(parent=parent, config=config) |
|
374 | super(Inspector, self).__init__(parent=parent, config=config) | |
375 | self.color_table = color_table |
|
375 | self.color_table = color_table | |
376 | self.parser = PyColorize.Parser(out='str', parent=self, style=scheme) |
|
376 | self.parser = PyColorize.Parser(out='str', parent=self, style=scheme) | |
377 | self.format = self.parser.format |
|
377 | self.format = self.parser.format | |
378 | self.str_detail_level = str_detail_level |
|
378 | self.str_detail_level = str_detail_level | |
379 | self.set_active_scheme(scheme) |
|
379 | self.set_active_scheme(scheme) | |
380 |
|
380 | |||
381 | def _getdef(self,obj,oname=''): |
|
381 | def _getdef(self,obj,oname=''): | |
382 | """Return the call signature for any callable object. |
|
382 | """Return the call signature for any callable object. | |
383 |
|
383 | |||
384 | If any exception is generated, None is returned instead and the |
|
384 | If any exception is generated, None is returned instead and the | |
385 | exception is suppressed.""" |
|
385 | exception is suppressed.""" | |
386 | try: |
|
386 | try: | |
387 | hdef = oname + str(signature(obj)) |
|
387 | hdef = oname + str(signature(obj)) | |
388 | return cast_unicode(hdef) |
|
388 | return cast_unicode(hdef) | |
389 | except: |
|
389 | except: | |
390 | return None |
|
390 | return None | |
391 |
|
391 | |||
392 | def __head(self,h): |
|
392 | def __head(self,h): | |
393 | """Return a header string with proper colors.""" |
|
393 | """Return a header string with proper colors.""" | |
394 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
394 | return '%s%s%s' % (self.color_table.active_colors.header,h, | |
395 | self.color_table.active_colors.normal) |
|
395 | self.color_table.active_colors.normal) | |
396 |
|
396 | |||
397 | def set_active_scheme(self, scheme): |
|
397 | def set_active_scheme(self, scheme): | |
398 | self.color_table.set_active_scheme(scheme) |
|
398 | self.color_table.set_active_scheme(scheme) | |
399 | self.parser.color_table.set_active_scheme(scheme) |
|
399 | self.parser.color_table.set_active_scheme(scheme) | |
400 |
|
400 | |||
401 | def noinfo(self, msg, oname): |
|
401 | def noinfo(self, msg, oname): | |
402 | """Generic message when no information is found.""" |
|
402 | """Generic message when no information is found.""" | |
403 | print('No %s found' % msg, end=' ') |
|
403 | print('No %s found' % msg, end=' ') | |
404 | if oname: |
|
404 | if oname: | |
405 | print('for %s' % oname) |
|
405 | print('for %s' % oname) | |
406 | else: |
|
406 | else: | |
407 | print() |
|
407 | print() | |
408 |
|
408 | |||
409 | def pdef(self, obj, oname=''): |
|
409 | def pdef(self, obj, oname=''): | |
410 | """Print the call signature for any callable object. |
|
410 | """Print the call signature for any callable object. | |
411 |
|
411 | |||
412 | If the object is a class, print the constructor information.""" |
|
412 | If the object is a class, print the constructor information.""" | |
413 |
|
413 | |||
414 | if not callable(obj): |
|
414 | if not callable(obj): | |
415 | print('Object is not callable.') |
|
415 | print('Object is not callable.') | |
416 | return |
|
416 | return | |
417 |
|
417 | |||
418 | header = '' |
|
418 | header = '' | |
419 |
|
419 | |||
420 | if inspect.isclass(obj): |
|
420 | if inspect.isclass(obj): | |
421 | header = self.__head('Class constructor information:\n') |
|
421 | header = self.__head('Class constructor information:\n') | |
422 | elif (not py3compat.PY3) and type(obj) is types.InstanceType: |
|
422 | elif (not py3compat.PY3) and type(obj) is types.InstanceType: | |
423 | obj = obj.__call__ |
|
423 | obj = obj.__call__ | |
424 |
|
424 | |||
425 | output = self._getdef(obj,oname) |
|
425 | output = self._getdef(obj,oname) | |
426 | if output is None: |
|
426 | if output is None: | |
427 | self.noinfo('definition header',oname) |
|
427 | self.noinfo('definition header',oname) | |
428 | else: |
|
428 | else: | |
429 | print(header,self.format(output), end=' ') |
|
429 | print(header,self.format(output), end=' ') | |
430 |
|
430 | |||
431 | # In Python 3, all classes are new-style, so they all have __init__. |
|
431 | # In Python 3, all classes are new-style, so they all have __init__. | |
432 | @skip_doctest_py3 |
|
432 | @skip_doctest_py3 | |
433 | def pdoc(self,obj,oname='',formatter = None): |
|
433 | def pdoc(self,obj,oname='',formatter = None): | |
434 | """Print the docstring for any object. |
|
434 | """Print the docstring for any object. | |
435 |
|
435 | |||
436 | Optional: |
|
436 | Optional: | |
437 | -formatter: a function to run the docstring through for specially |
|
437 | -formatter: a function to run the docstring through for specially | |
438 | formatted docstrings. |
|
438 | formatted docstrings. | |
439 |
|
439 | |||
440 | Examples |
|
440 | Examples | |
441 | -------- |
|
441 | -------- | |
442 |
|
442 | |||
443 | In [1]: class NoInit: |
|
443 | In [1]: class NoInit: | |
444 | ...: pass |
|
444 | ...: pass | |
445 |
|
445 | |||
446 | In [2]: class NoDoc: |
|
446 | In [2]: class NoDoc: | |
447 | ...: def __init__(self): |
|
447 | ...: def __init__(self): | |
448 | ...: pass |
|
448 | ...: pass | |
449 |
|
449 | |||
450 | In [3]: %pdoc NoDoc |
|
450 | In [3]: %pdoc NoDoc | |
451 | No documentation found for NoDoc |
|
451 | No documentation found for NoDoc | |
452 |
|
452 | |||
453 | In [4]: %pdoc NoInit |
|
453 | In [4]: %pdoc NoInit | |
454 | No documentation found for NoInit |
|
454 | No documentation found for NoInit | |
455 |
|
455 | |||
456 | In [5]: obj = NoInit() |
|
456 | In [5]: obj = NoInit() | |
457 |
|
457 | |||
458 | In [6]: %pdoc obj |
|
458 | In [6]: %pdoc obj | |
459 | No documentation found for obj |
|
459 | No documentation found for obj | |
460 |
|
460 | |||
461 | In [5]: obj2 = NoDoc() |
|
461 | In [5]: obj2 = NoDoc() | |
462 |
|
462 | |||
463 | In [6]: %pdoc obj2 |
|
463 | In [6]: %pdoc obj2 | |
464 | No documentation found for obj2 |
|
464 | No documentation found for obj2 | |
465 | """ |
|
465 | """ | |
466 |
|
466 | |||
467 | head = self.__head # For convenience |
|
467 | head = self.__head # For convenience | |
468 | lines = [] |
|
468 | lines = [] | |
469 | ds = getdoc(obj) |
|
469 | ds = getdoc(obj) | |
470 | if formatter: |
|
470 | if formatter: | |
471 | ds = formatter(ds) |
|
471 | ds = formatter(ds) | |
472 | if ds: |
|
472 | if ds: | |
473 | lines.append(head("Class docstring:")) |
|
473 | lines.append(head("Class docstring:")) | |
474 | lines.append(indent(ds)) |
|
474 | lines.append(indent(ds)) | |
475 | if inspect.isclass(obj) and hasattr(obj, '__init__'): |
|
475 | if inspect.isclass(obj) and hasattr(obj, '__init__'): | |
476 | init_ds = getdoc(obj.__init__) |
|
476 | init_ds = getdoc(obj.__init__) | |
477 | if init_ds is not None: |
|
477 | if init_ds is not None: | |
478 | lines.append(head("Init docstring:")) |
|
478 | lines.append(head("Init docstring:")) | |
479 | lines.append(indent(init_ds)) |
|
479 | lines.append(indent(init_ds)) | |
480 | elif hasattr(obj,'__call__'): |
|
480 | elif hasattr(obj,'__call__'): | |
481 | call_ds = getdoc(obj.__call__) |
|
481 | call_ds = getdoc(obj.__call__) | |
482 | if call_ds: |
|
482 | if call_ds: | |
483 | lines.append(head("Call docstring:")) |
|
483 | lines.append(head("Call docstring:")) | |
484 | lines.append(indent(call_ds)) |
|
484 | lines.append(indent(call_ds)) | |
485 |
|
485 | |||
486 | if not lines: |
|
486 | if not lines: | |
487 | self.noinfo('documentation',oname) |
|
487 | self.noinfo('documentation',oname) | |
488 | else: |
|
488 | else: | |
489 | page.page('\n'.join(lines)) |
|
489 | page.page('\n'.join(lines)) | |
490 |
|
490 | |||
491 | def psource(self, obj, oname=''): |
|
491 | def psource(self, obj, oname=''): | |
492 | """Print the source code for an object.""" |
|
492 | """Print the source code for an object.""" | |
493 |
|
493 | |||
494 | # Flush the source cache because inspect can return out-of-date source |
|
494 | # Flush the source cache because inspect can return out-of-date source | |
495 | linecache.checkcache() |
|
495 | linecache.checkcache() | |
496 | try: |
|
496 | try: | |
497 | src = getsource(obj, oname=oname) |
|
497 | src = getsource(obj, oname=oname) | |
498 | except Exception: |
|
498 | except Exception: | |
499 | src = None |
|
499 | src = None | |
500 |
|
500 | |||
501 | if src is None: |
|
501 | if src is None: | |
502 | self.noinfo('source', oname) |
|
502 | self.noinfo('source', oname) | |
503 | else: |
|
503 | else: | |
504 | page.page(self.format(src)) |
|
504 | page.page(self.format(src)) | |
505 |
|
505 | |||
506 | def pfile(self, obj, oname=''): |
|
506 | def pfile(self, obj, oname=''): | |
507 | """Show the whole file where an object was defined.""" |
|
507 | """Show the whole file where an object was defined.""" | |
508 |
|
508 | |||
509 | lineno = find_source_lines(obj) |
|
509 | lineno = find_source_lines(obj) | |
510 | if lineno is None: |
|
510 | if lineno is None: | |
511 | self.noinfo('file', oname) |
|
511 | self.noinfo('file', oname) | |
512 | return |
|
512 | return | |
513 |
|
513 | |||
514 | ofile = find_file(obj) |
|
514 | ofile = find_file(obj) | |
515 | # run contents of file through pager starting at line where the object |
|
515 | # run contents of file through pager starting at line where the object | |
516 | # is defined, as long as the file isn't binary and is actually on the |
|
516 | # is defined, as long as the file isn't binary and is actually on the | |
517 | # filesystem. |
|
517 | # filesystem. | |
518 | if ofile.endswith(('.so', '.dll', '.pyd')): |
|
518 | if ofile.endswith(('.so', '.dll', '.pyd')): | |
519 | print('File %r is binary, not printing.' % ofile) |
|
519 | print('File %r is binary, not printing.' % ofile) | |
520 | elif not os.path.isfile(ofile): |
|
520 | elif not os.path.isfile(ofile): | |
521 | print('File %r does not exist, not printing.' % ofile) |
|
521 | print('File %r does not exist, not printing.' % ofile) | |
522 | else: |
|
522 | else: | |
523 | # Print only text files, not extension binaries. Note that |
|
523 | # Print only text files, not extension binaries. Note that | |
524 | # getsourcelines returns lineno with 1-offset and page() uses |
|
524 | # getsourcelines returns lineno with 1-offset and page() uses | |
525 | # 0-offset, so we must adjust. |
|
525 | # 0-offset, so we must adjust. | |
526 | page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1) |
|
526 | page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1) | |
527 |
|
527 | |||
528 | def _format_fields(self, fields, title_width=0): |
|
528 | def _format_fields(self, fields, title_width=0): | |
529 | """Formats a list of fields for display. |
|
529 | """Formats a list of fields for display. | |
530 |
|
530 | |||
531 | Parameters |
|
531 | Parameters | |
532 | ---------- |
|
532 | ---------- | |
533 | fields : list |
|
533 | fields : list | |
534 | A list of 2-tuples: (field_title, field_content) |
|
534 | A list of 2-tuples: (field_title, field_content) | |
535 | title_width : int |
|
535 | title_width : int | |
536 | How many characters to pad titles to. Default to longest title. |
|
536 | How many characters to pad titles to. Default to longest title. | |
537 | """ |
|
537 | """ | |
538 | out = [] |
|
538 | out = [] | |
539 | header = self.__head |
|
539 | header = self.__head | |
540 | if title_width == 0: |
|
540 | if title_width == 0: | |
541 | title_width = max(len(title) + 2 for title, _ in fields) |
|
541 | title_width = max(len(title) + 2 for title, _ in fields) | |
542 | for title, content in fields: |
|
542 | for title, content in fields: | |
543 | if len(content.splitlines()) > 1: |
|
543 | if len(content.splitlines()) > 1: | |
544 | title = header(title + ":") + "\n" |
|
544 | title = header(title + ":") + "\n" | |
545 | else: |
|
545 | else: | |
546 | title = header((title+":").ljust(title_width)) |
|
546 | title = header((title+":").ljust(title_width)) | |
547 | out.append(cast_unicode(title) + cast_unicode(content)) |
|
547 | out.append(cast_unicode(title) + cast_unicode(content)) | |
548 | return "\n".join(out) |
|
548 | return "\n".join(out) | |
549 |
|
549 | |||
550 | def _format_info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
550 | def _format_info(self, obj, oname='', formatter=None, info=None, detail_level=0): | |
551 | """Format an info dict as text""" |
|
551 | """Format an info dict as text""" | |
552 | info = self.info(obj, oname=oname, formatter=formatter, |
|
552 | ||
|
553 | # hack docstring rendering | |||
|
554 | info = self.info(obj, oname=oname, formatter=None, | |||
553 | info=info, detail_level=detail_level) |
|
555 | info=info, detail_level=detail_level) | |
|
556 | if formatter: | |||
|
557 | return formatter(info["docstring"]) | |||
|
558 | ||||
554 | displayfields = [] |
|
559 | displayfields = [] | |
555 | def add_fields(fields): |
|
560 | def add_fields(fields): | |
556 | for title, key in fields: |
|
561 | for title, key in fields: | |
557 | field = info[key] |
|
562 | field = info[key] | |
558 | if field is not None: |
|
563 | if field is not None: | |
559 | if key == "source": |
|
564 | if key == "source": | |
560 | displayfields.append((title, self.format(cast_unicode(field.rstrip())))) |
|
565 | displayfields.append((title, self.format(cast_unicode(field.rstrip())))) | |
561 | else: |
|
566 | else: | |
562 | displayfields.append((title, field.rstrip())) |
|
567 | displayfields.append((title, field.rstrip())) | |
563 |
|
568 | |||
564 | if info['isalias']: |
|
569 | if info['isalias']: | |
565 | add_fields([('Repr', "string_form")]) |
|
570 | add_fields([('Repr', "string_form")]) | |
566 |
|
571 | |||
567 | elif info['ismagic']: |
|
572 | elif info['ismagic']: | |
568 | if detail_level > 0 and info['source'] is not None: |
|
573 | if detail_level > 0 and info['source'] is not None: | |
569 | add_fields([("Source", "source")]) |
|
574 | add_fields([("Source", "source")]) | |
570 | else: |
|
575 | else: | |
571 | add_fields([("Docstring", "docstring")]) |
|
576 | add_fields([("Docstring", "docstring")]) | |
572 |
|
577 | |||
573 | add_fields([("File", "file"), |
|
578 | add_fields([("File", "file"), | |
574 | ]) |
|
579 | ]) | |
575 |
|
580 | |||
576 | elif info['isclass'] or is_simple_callable(obj): |
|
581 | elif info['isclass'] or is_simple_callable(obj): | |
577 | # Functions, methods, classes |
|
582 | # Functions, methods, classes | |
578 | add_fields([("Signature", "definition"), |
|
583 | add_fields([("Signature", "definition"), | |
579 | ("Init signature", "init_definition"), |
|
584 | ("Init signature", "init_definition"), | |
580 | ]) |
|
585 | ]) | |
581 | if detail_level > 0 and info['source'] is not None: |
|
586 | if detail_level > 0 and info['source'] is not None: | |
582 | add_fields([("Source", "source")]) |
|
587 | add_fields([("Source", "source")]) | |
583 | else: |
|
588 | else: | |
584 | add_fields([("Docstring", "docstring"), |
|
589 | add_fields([("Docstring", "docstring"), | |
585 | ("Init docstring", "init_docstring"), |
|
590 | ("Init docstring", "init_docstring"), | |
586 | ]) |
|
591 | ]) | |
587 |
|
592 | |||
588 | add_fields([('File', 'file'), |
|
593 | add_fields([('File', 'file'), | |
589 | ('Type', 'type_name'), |
|
594 | ('Type', 'type_name'), | |
590 | ]) |
|
595 | ]) | |
591 |
|
596 | |||
592 | else: |
|
597 | else: | |
593 | # General Python objects |
|
598 | # General Python objects | |
594 | add_fields([("Type", "type_name")]) |
|
599 | add_fields([("Type", "type_name")]) | |
595 |
|
600 | |||
596 | # Base class for old-style instances |
|
601 | # Base class for old-style instances | |
597 | if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']: |
|
602 | if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']: | |
598 | displayfields.append(("Base Class", info['base_class'].rstrip())) |
|
603 | displayfields.append(("Base Class", info['base_class'].rstrip())) | |
599 |
|
604 | |||
600 | add_fields([("String form", "string_form")]) |
|
605 | add_fields([("String form", "string_form")]) | |
601 |
|
606 | |||
602 | # Namespace |
|
607 | # Namespace | |
603 | if info['namespace'] != 'Interactive': |
|
608 | if info['namespace'] != 'Interactive': | |
604 | displayfields.append(("Namespace", info['namespace'].rstrip())) |
|
609 | displayfields.append(("Namespace", info['namespace'].rstrip())) | |
605 |
|
610 | |||
606 | add_fields([("Length", "length"), |
|
611 | add_fields([("Length", "length"), | |
607 | ("File", "file"), |
|
612 | ("File", "file"), | |
608 | ("Signature", "definition"), |
|
613 | ("Signature", "definition"), | |
609 | ]) |
|
614 | ]) | |
610 |
|
615 | |||
611 | # Source or docstring, depending on detail level and whether |
|
616 | # Source or docstring, depending on detail level and whether | |
612 | # source found. |
|
617 | # source found. | |
613 | if detail_level > 0 and info['source'] is not None: |
|
618 | if detail_level > 0 and info['source'] is not None: | |
614 | displayfields.append(("Source", |
|
619 | displayfields.append(("Source", | |
615 | self.format(cast_unicode(info['source'])))) |
|
620 | self.format(cast_unicode(info['source'])))) | |
616 | elif info['docstring'] is not None: |
|
621 | elif info['docstring'] is not None: | |
617 | displayfields.append(("Docstring", info["docstring"])) |
|
622 | displayfields.append(("Docstring", info["docstring"])) | |
618 |
|
623 | |||
619 | add_fields([("Class docstring", "class_docstring"), |
|
624 | add_fields([("Class docstring", "class_docstring"), | |
620 | ("Init docstring", "init_docstring"), |
|
625 | ("Init docstring", "init_docstring"), | |
621 | ("Call signature", "call_def"), |
|
626 | ("Call signature", "call_def"), | |
622 | ("Call docstring", "call_docstring")]) |
|
627 | ("Call docstring", "call_docstring")]) | |
623 |
|
628 | |||
624 | if displayfields: |
|
629 | if displayfields: | |
625 | return self._format_fields(displayfields) |
|
630 | return self._format_fields(displayfields) | |
626 | else: |
|
631 | else: | |
627 | return u'' |
|
632 | return u'' | |
628 |
|
633 | |||
629 | def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
634 | def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0): | |
630 | """Show detailed information about an object. |
|
635 | """Show detailed information about an object. | |
631 |
|
636 | |||
632 | Optional arguments: |
|
637 | Optional arguments: | |
633 |
|
638 | |||
634 | - oname: name of the variable pointing to the object. |
|
639 | - oname: name of the variable pointing to the object. | |
635 |
|
640 | |||
636 | - formatter: special formatter for docstrings (see pdoc) |
|
641 | - formatter: special formatter for docstrings (see pdoc) | |
637 |
|
642 | |||
638 | - info: a structure with some information fields which may have been |
|
643 | - info: a structure with some information fields which may have been | |
639 | precomputed already. |
|
644 | precomputed already. | |
640 |
|
645 | |||
641 | - detail_level: if set to 1, more information is given. |
|
646 | - detail_level: if set to 1, more information is given. | |
642 | """ |
|
647 | """ | |
643 | text = self._format_info(obj, oname, formatter, info, detail_level) |
|
648 | text = self._format_info(obj, oname, formatter, info, detail_level) | |
644 | if text: |
|
649 | if text: | |
645 | page.page(text) |
|
650 | page.page(text) | |
646 |
|
651 | |||
647 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
652 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): | |
648 | """Compute a dict with detailed information about an object. |
|
653 | """Compute a dict with detailed information about an object. | |
649 |
|
654 | |||
650 | Optional arguments: |
|
655 | Optional arguments: | |
651 |
|
656 | |||
652 | - oname: name of the variable pointing to the object. |
|
657 | - oname: name of the variable pointing to the object. | |
653 |
|
658 | |||
654 | - formatter: special formatter for docstrings (see pdoc) |
|
659 | - formatter: special formatter for docstrings (see pdoc) | |
655 |
|
660 | |||
656 | - info: a structure with some information fields which may have been |
|
661 | - info: a structure with some information fields which may have been | |
657 | precomputed already. |
|
662 | precomputed already. | |
658 |
|
663 | |||
659 | - detail_level: if set to 1, more information is given. |
|
664 | - detail_level: if set to 1, more information is given. | |
660 | """ |
|
665 | """ | |
661 |
|
666 | |||
662 | obj_type = type(obj) |
|
667 | obj_type = type(obj) | |
663 |
|
668 | |||
664 | if info is None: |
|
669 | if info is None: | |
665 | ismagic = 0 |
|
670 | ismagic = 0 | |
666 | isalias = 0 |
|
671 | isalias = 0 | |
667 | ospace = '' |
|
672 | ospace = '' | |
668 | else: |
|
673 | else: | |
669 | ismagic = info.ismagic |
|
674 | ismagic = info.ismagic | |
670 | isalias = info.isalias |
|
675 | isalias = info.isalias | |
671 | ospace = info.namespace |
|
676 | ospace = info.namespace | |
672 |
|
677 | |||
673 | # Get docstring, special-casing aliases: |
|
678 | # Get docstring, special-casing aliases: | |
674 | if isalias: |
|
679 | if isalias: | |
675 | if not callable(obj): |
|
680 | if not callable(obj): | |
676 | try: |
|
681 | try: | |
677 | ds = "Alias to the system command:\n %s" % obj[1] |
|
682 | ds = "Alias to the system command:\n %s" % obj[1] | |
678 | except: |
|
683 | except: | |
679 | ds = "Alias: " + str(obj) |
|
684 | ds = "Alias: " + str(obj) | |
680 | else: |
|
685 | else: | |
681 | ds = "Alias to " + str(obj) |
|
686 | ds = "Alias to " + str(obj) | |
682 | if obj.__doc__: |
|
687 | if obj.__doc__: | |
683 | ds += "\nDocstring:\n" + obj.__doc__ |
|
688 | ds += "\nDocstring:\n" + obj.__doc__ | |
684 | else: |
|
689 | else: | |
685 | ds = getdoc(obj) |
|
690 | ds = getdoc(obj) | |
686 | if ds is None: |
|
691 | if ds is None: | |
687 | ds = '<no docstring>' |
|
692 | ds = '<no docstring>' | |
688 | if formatter is not None: |
|
693 | if formatter is not None: | |
689 | ds = formatter(ds) |
|
694 | ds = formatter(ds) | |
690 |
|
695 | |||
691 | # store output in a dict, we initialize it here and fill it as we go |
|
696 | # store output in a dict, we initialize it here and fill it as we go | |
692 | out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) |
|
697 | out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) | |
693 |
|
698 | |||
694 | string_max = 200 # max size of strings to show (snipped if longer) |
|
699 | string_max = 200 # max size of strings to show (snipped if longer) | |
695 | shalf = int((string_max -5)/2) |
|
700 | shalf = int((string_max -5)/2) | |
696 |
|
701 | |||
697 | if ismagic: |
|
702 | if ismagic: | |
698 | obj_type_name = 'Magic function' |
|
703 | obj_type_name = 'Magic function' | |
699 | elif isalias: |
|
704 | elif isalias: | |
700 | obj_type_name = 'System alias' |
|
705 | obj_type_name = 'System alias' | |
701 | else: |
|
706 | else: | |
702 | obj_type_name = obj_type.__name__ |
|
707 | obj_type_name = obj_type.__name__ | |
703 | out['type_name'] = obj_type_name |
|
708 | out['type_name'] = obj_type_name | |
704 |
|
709 | |||
705 | try: |
|
710 | try: | |
706 | bclass = obj.__class__ |
|
711 | bclass = obj.__class__ | |
707 | out['base_class'] = str(bclass) |
|
712 | out['base_class'] = str(bclass) | |
708 | except: pass |
|
713 | except: pass | |
709 |
|
714 | |||
710 | # String form, but snip if too long in ? form (full in ??) |
|
715 | # String form, but snip if too long in ? form (full in ??) | |
711 | if detail_level >= self.str_detail_level: |
|
716 | if detail_level >= self.str_detail_level: | |
712 | try: |
|
717 | try: | |
713 | ostr = str(obj) |
|
718 | ostr = str(obj) | |
714 | str_head = 'string_form' |
|
719 | str_head = 'string_form' | |
715 | if not detail_level and len(ostr)>string_max: |
|
720 | if not detail_level and len(ostr)>string_max: | |
716 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
721 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
717 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
722 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
718 | join(q.strip() for q in ostr.split("\n")) |
|
723 | join(q.strip() for q in ostr.split("\n")) | |
719 | out[str_head] = ostr |
|
724 | out[str_head] = ostr | |
720 | except: |
|
725 | except: | |
721 | pass |
|
726 | pass | |
722 |
|
727 | |||
723 | if ospace: |
|
728 | if ospace: | |
724 | out['namespace'] = ospace |
|
729 | out['namespace'] = ospace | |
725 |
|
730 | |||
726 | # Length (for strings and lists) |
|
731 | # Length (for strings and lists) | |
727 | try: |
|
732 | try: | |
728 | out['length'] = str(len(obj)) |
|
733 | out['length'] = str(len(obj)) | |
729 | except: pass |
|
734 | except: pass | |
730 |
|
735 | |||
731 | # Filename where object was defined |
|
736 | # Filename where object was defined | |
732 | binary_file = False |
|
737 | binary_file = False | |
733 | fname = find_file(obj) |
|
738 | fname = find_file(obj) | |
734 | if fname is None: |
|
739 | if fname is None: | |
735 | # if anything goes wrong, we don't want to show source, so it's as |
|
740 | # if anything goes wrong, we don't want to show source, so it's as | |
736 | # if the file was binary |
|
741 | # if the file was binary | |
737 | binary_file = True |
|
742 | binary_file = True | |
738 | else: |
|
743 | else: | |
739 | if fname.endswith(('.so', '.dll', '.pyd')): |
|
744 | if fname.endswith(('.so', '.dll', '.pyd')): | |
740 | binary_file = True |
|
745 | binary_file = True | |
741 | elif fname.endswith('<string>'): |
|
746 | elif fname.endswith('<string>'): | |
742 | fname = 'Dynamically generated function. No source code available.' |
|
747 | fname = 'Dynamically generated function. No source code available.' | |
743 | out['file'] = compress_user(fname) |
|
748 | out['file'] = compress_user(fname) | |
744 |
|
749 | |||
745 | # Original source code for a callable, class or property. |
|
750 | # Original source code for a callable, class or property. | |
746 | if detail_level: |
|
751 | if detail_level: | |
747 | # Flush the source cache because inspect can return out-of-date |
|
752 | # Flush the source cache because inspect can return out-of-date | |
748 | # source |
|
753 | # source | |
749 | linecache.checkcache() |
|
754 | linecache.checkcache() | |
750 | try: |
|
755 | try: | |
751 | if isinstance(obj, property) or not binary_file: |
|
756 | if isinstance(obj, property) or not binary_file: | |
752 | src = getsource(obj, oname) |
|
757 | src = getsource(obj, oname) | |
753 | if src is not None: |
|
758 | if src is not None: | |
754 | src = src.rstrip() |
|
759 | src = src.rstrip() | |
755 | out['source'] = src |
|
760 | out['source'] = src | |
756 |
|
761 | |||
757 | except Exception: |
|
762 | except Exception: | |
758 | pass |
|
763 | pass | |
759 |
|
764 | |||
760 | # Add docstring only if no source is to be shown (avoid repetitions). |
|
765 | # Add docstring only if no source is to be shown (avoid repetitions). | |
761 | if ds and out.get('source', None) is None: |
|
766 | if ds and out.get('source', None) is None: | |
762 | out['docstring'] = ds |
|
767 | out['docstring'] = ds | |
763 |
|
768 | |||
764 | # Constructor docstring for classes |
|
769 | # Constructor docstring for classes | |
765 | if inspect.isclass(obj): |
|
770 | if inspect.isclass(obj): | |
766 | out['isclass'] = True |
|
771 | out['isclass'] = True | |
767 |
|
772 | |||
768 | # get the init signature: |
|
773 | # get the init signature: | |
769 | try: |
|
774 | try: | |
770 | init_def = self._getdef(obj, oname) |
|
775 | init_def = self._getdef(obj, oname) | |
771 | except AttributeError: |
|
776 | except AttributeError: | |
772 | init_def = None |
|
777 | init_def = None | |
773 |
|
778 | |||
774 | if init_def: |
|
779 | if init_def: | |
775 | out['init_definition'] = self.format(init_def) |
|
780 | out['init_definition'] = self.format(init_def) | |
776 |
|
781 | |||
777 | # get the __init__ docstring |
|
782 | # get the __init__ docstring | |
778 | try: |
|
783 | try: | |
779 | obj_init = obj.__init__ |
|
784 | obj_init = obj.__init__ | |
780 | except AttributeError: |
|
785 | except AttributeError: | |
781 | init_ds = None |
|
786 | init_ds = None | |
782 | else: |
|
787 | else: | |
783 | init_ds = getdoc(obj_init) |
|
788 | init_ds = getdoc(obj_init) | |
784 | # Skip Python's auto-generated docstrings |
|
789 | # Skip Python's auto-generated docstrings | |
785 | if init_ds == _object_init_docstring: |
|
790 | if init_ds == _object_init_docstring: | |
786 | init_ds = None |
|
791 | init_ds = None | |
787 |
|
792 | |||
788 | if init_ds: |
|
793 | if init_ds: | |
789 | out['init_docstring'] = init_ds |
|
794 | out['init_docstring'] = init_ds | |
790 |
|
795 | |||
791 | # and class docstring for instances: |
|
796 | # and class docstring for instances: | |
792 | else: |
|
797 | else: | |
793 | # reconstruct the function definition and print it: |
|
798 | # reconstruct the function definition and print it: | |
794 | defln = self._getdef(obj, oname) |
|
799 | defln = self._getdef(obj, oname) | |
795 | if defln: |
|
800 | if defln: | |
796 | out['definition'] = self.format(defln) |
|
801 | out['definition'] = self.format(defln) | |
797 |
|
802 | |||
798 | # First, check whether the instance docstring is identical to the |
|
803 | # First, check whether the instance docstring is identical to the | |
799 | # class one, and print it separately if they don't coincide. In |
|
804 | # class one, and print it separately if they don't coincide. In | |
800 | # most cases they will, but it's nice to print all the info for |
|
805 | # most cases they will, but it's nice to print all the info for | |
801 | # objects which use instance-customized docstrings. |
|
806 | # objects which use instance-customized docstrings. | |
802 | if ds: |
|
807 | if ds: | |
803 | try: |
|
808 | try: | |
804 | cls = getattr(obj,'__class__') |
|
809 | cls = getattr(obj,'__class__') | |
805 | except: |
|
810 | except: | |
806 | class_ds = None |
|
811 | class_ds = None | |
807 | else: |
|
812 | else: | |
808 | class_ds = getdoc(cls) |
|
813 | class_ds = getdoc(cls) | |
809 | # Skip Python's auto-generated docstrings |
|
814 | # Skip Python's auto-generated docstrings | |
810 | if class_ds in _builtin_type_docstrings: |
|
815 | if class_ds in _builtin_type_docstrings: | |
811 | class_ds = None |
|
816 | class_ds = None | |
812 | if class_ds and ds != class_ds: |
|
817 | if class_ds and ds != class_ds: | |
813 | out['class_docstring'] = class_ds |
|
818 | out['class_docstring'] = class_ds | |
814 |
|
819 | |||
815 | # Next, try to show constructor docstrings |
|
820 | # Next, try to show constructor docstrings | |
816 | try: |
|
821 | try: | |
817 | init_ds = getdoc(obj.__init__) |
|
822 | init_ds = getdoc(obj.__init__) | |
818 | # Skip Python's auto-generated docstrings |
|
823 | # Skip Python's auto-generated docstrings | |
819 | if init_ds == _object_init_docstring: |
|
824 | if init_ds == _object_init_docstring: | |
820 | init_ds = None |
|
825 | init_ds = None | |
821 | except AttributeError: |
|
826 | except AttributeError: | |
822 | init_ds = None |
|
827 | init_ds = None | |
823 | if init_ds: |
|
828 | if init_ds: | |
824 | out['init_docstring'] = init_ds |
|
829 | out['init_docstring'] = init_ds | |
825 |
|
830 | |||
826 | # Call form docstring for callable instances |
|
831 | # Call form docstring for callable instances | |
827 | if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): |
|
832 | if safe_hasattr(obj, '__call__') and not is_simple_callable(obj): | |
828 | call_def = self._getdef(obj.__call__, oname) |
|
833 | call_def = self._getdef(obj.__call__, oname) | |
829 | if call_def: |
|
834 | if call_def: | |
830 | call_def = self.format(call_def) |
|
835 | call_def = self.format(call_def) | |
831 | # it may never be the case that call def and definition differ, |
|
836 | # it may never be the case that call def and definition differ, | |
832 | # but don't include the same signature twice |
|
837 | # but don't include the same signature twice | |
833 | if call_def != out.get('definition'): |
|
838 | if call_def != out.get('definition'): | |
834 | out['call_def'] = call_def |
|
839 | out['call_def'] = call_def | |
835 | call_ds = getdoc(obj.__call__) |
|
840 | call_ds = getdoc(obj.__call__) | |
836 | # Skip Python's auto-generated docstrings |
|
841 | # Skip Python's auto-generated docstrings | |
837 | if call_ds == _func_call_docstring: |
|
842 | if call_ds == _func_call_docstring: | |
838 | call_ds = None |
|
843 | call_ds = None | |
839 | if call_ds: |
|
844 | if call_ds: | |
840 | out['call_docstring'] = call_ds |
|
845 | out['call_docstring'] = call_ds | |
841 |
|
846 | |||
842 | # Compute the object's argspec as a callable. The key is to decide |
|
847 | # Compute the object's argspec as a callable. The key is to decide | |
843 | # whether to pull it from the object itself, from its __init__ or |
|
848 | # whether to pull it from the object itself, from its __init__ or | |
844 | # from its __call__ method. |
|
849 | # from its __call__ method. | |
845 |
|
850 | |||
846 | if inspect.isclass(obj): |
|
851 | if inspect.isclass(obj): | |
847 | # Old-style classes need not have an __init__ |
|
852 | # Old-style classes need not have an __init__ | |
848 | callable_obj = getattr(obj, "__init__", None) |
|
853 | callable_obj = getattr(obj, "__init__", None) | |
849 | elif callable(obj): |
|
854 | elif callable(obj): | |
850 | callable_obj = obj |
|
855 | callable_obj = obj | |
851 | else: |
|
856 | else: | |
852 | callable_obj = None |
|
857 | callable_obj = None | |
853 |
|
858 | |||
854 | if callable_obj is not None: |
|
859 | if callable_obj is not None: | |
855 | try: |
|
860 | try: | |
856 | argspec = getargspec(callable_obj) |
|
861 | argspec = getargspec(callable_obj) | |
857 | except (TypeError, AttributeError): |
|
862 | except (TypeError, AttributeError): | |
858 | # For extensions/builtins we can't retrieve the argspec |
|
863 | # For extensions/builtins we can't retrieve the argspec | |
859 | pass |
|
864 | pass | |
860 | else: |
|
865 | else: | |
861 | # named tuples' _asdict() method returns an OrderedDict, but we |
|
866 | # named tuples' _asdict() method returns an OrderedDict, but we | |
862 | # we want a normal |
|
867 | # we want a normal | |
863 | out['argspec'] = argspec_dict = dict(argspec._asdict()) |
|
868 | out['argspec'] = argspec_dict = dict(argspec._asdict()) | |
864 | # We called this varkw before argspec became a named tuple. |
|
869 | # We called this varkw before argspec became a named tuple. | |
865 | # With getfullargspec it's also called varkw. |
|
870 | # With getfullargspec it's also called varkw. | |
866 | if 'varkw' not in argspec_dict: |
|
871 | if 'varkw' not in argspec_dict: | |
867 | argspec_dict['varkw'] = argspec_dict.pop('keywords') |
|
872 | argspec_dict['varkw'] = argspec_dict.pop('keywords') | |
868 |
|
873 | |||
869 | return object_info(**out) |
|
874 | return object_info(**out) | |
870 |
|
875 | |||
871 | def psearch(self,pattern,ns_table,ns_search=[], |
|
876 | def psearch(self,pattern,ns_table,ns_search=[], | |
872 | ignore_case=False,show_all=False): |
|
877 | ignore_case=False,show_all=False): | |
873 | """Search namespaces with wildcards for objects. |
|
878 | """Search namespaces with wildcards for objects. | |
874 |
|
879 | |||
875 | Arguments: |
|
880 | Arguments: | |
876 |
|
881 | |||
877 | - pattern: string containing shell-like wildcards to use in namespace |
|
882 | - pattern: string containing shell-like wildcards to use in namespace | |
878 | searches and optionally a type specification to narrow the search to |
|
883 | searches and optionally a type specification to narrow the search to | |
879 | objects of that type. |
|
884 | objects of that type. | |
880 |
|
885 | |||
881 | - ns_table: dict of name->namespaces for search. |
|
886 | - ns_table: dict of name->namespaces for search. | |
882 |
|
887 | |||
883 | Optional arguments: |
|
888 | Optional arguments: | |
884 |
|
889 | |||
885 | - ns_search: list of namespace names to include in search. |
|
890 | - ns_search: list of namespace names to include in search. | |
886 |
|
891 | |||
887 | - ignore_case(False): make the search case-insensitive. |
|
892 | - ignore_case(False): make the search case-insensitive. | |
888 |
|
893 | |||
889 | - show_all(False): show all names, including those starting with |
|
894 | - show_all(False): show all names, including those starting with | |
890 | underscores. |
|
895 | underscores. | |
891 | """ |
|
896 | """ | |
892 | #print 'ps pattern:<%r>' % pattern # dbg |
|
897 | #print 'ps pattern:<%r>' % pattern # dbg | |
893 |
|
898 | |||
894 | # defaults |
|
899 | # defaults | |
895 | type_pattern = 'all' |
|
900 | type_pattern = 'all' | |
896 | filter = '' |
|
901 | filter = '' | |
897 |
|
902 | |||
898 | cmds = pattern.split() |
|
903 | cmds = pattern.split() | |
899 | len_cmds = len(cmds) |
|
904 | len_cmds = len(cmds) | |
900 | if len_cmds == 1: |
|
905 | if len_cmds == 1: | |
901 | # Only filter pattern given |
|
906 | # Only filter pattern given | |
902 | filter = cmds[0] |
|
907 | filter = cmds[0] | |
903 | elif len_cmds == 2: |
|
908 | elif len_cmds == 2: | |
904 | # Both filter and type specified |
|
909 | # Both filter and type specified | |
905 | filter,type_pattern = cmds |
|
910 | filter,type_pattern = cmds | |
906 | else: |
|
911 | else: | |
907 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
912 | raise ValueError('invalid argument string for psearch: <%s>' % | |
908 | pattern) |
|
913 | pattern) | |
909 |
|
914 | |||
910 | # filter search namespaces |
|
915 | # filter search namespaces | |
911 | for name in ns_search: |
|
916 | for name in ns_search: | |
912 | if name not in ns_table: |
|
917 | if name not in ns_table: | |
913 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
918 | raise ValueError('invalid namespace <%s>. Valid names: %s' % | |
914 | (name,ns_table.keys())) |
|
919 | (name,ns_table.keys())) | |
915 |
|
920 | |||
916 | #print 'type_pattern:',type_pattern # dbg |
|
921 | #print 'type_pattern:',type_pattern # dbg | |
917 | search_result, namespaces_seen = set(), set() |
|
922 | search_result, namespaces_seen = set(), set() | |
918 | for ns_name in ns_search: |
|
923 | for ns_name in ns_search: | |
919 | ns = ns_table[ns_name] |
|
924 | ns = ns_table[ns_name] | |
920 | # Normally, locals and globals are the same, so we just check one. |
|
925 | # Normally, locals and globals are the same, so we just check one. | |
921 | if id(ns) in namespaces_seen: |
|
926 | if id(ns) in namespaces_seen: | |
922 | continue |
|
927 | continue | |
923 | namespaces_seen.add(id(ns)) |
|
928 | namespaces_seen.add(id(ns)) | |
924 | tmp_res = list_namespace(ns, type_pattern, filter, |
|
929 | tmp_res = list_namespace(ns, type_pattern, filter, | |
925 | ignore_case=ignore_case, show_all=show_all) |
|
930 | ignore_case=ignore_case, show_all=show_all) | |
926 | search_result.update(tmp_res) |
|
931 | search_result.update(tmp_res) | |
927 |
|
932 | |||
928 | page.page('\n'.join(sorted(search_result))) |
|
933 | page.page('\n'.join(sorted(search_result))) |
General Comments 0
You need to be logged in to leave comments.
Login now