Show More
@@ -1,2340 +1,2340 | |||||
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-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import codeop |
|
23 | import codeop | |
24 | import exceptions |
|
24 | import exceptions | |
25 | import new |
|
25 | import new | |
26 | import os |
|
26 | import os | |
27 | import re |
|
27 | import re | |
28 | import string |
|
28 | import string | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | from contextlib import nested |
|
31 | from contextlib import nested | |
32 |
|
32 | |||
33 | from IPython.config.configurable import Configurable |
|
33 | from IPython.config.configurable import Configurable | |
34 | from IPython.core import debugger, oinspect |
|
34 | from IPython.core import debugger, oinspect | |
35 | from IPython.core import history as ipcorehist |
|
35 | from IPython.core import history as ipcorehist | |
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 AliasManager |
|
40 | from IPython.core.alias import AliasManager | |
41 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | from IPython.core.builtin_trap import BuiltinTrap | |
42 | from IPython.core.display_trap import DisplayTrap |
|
42 | from IPython.core.display_trap import DisplayTrap | |
43 | from IPython.core.displayhook import DisplayHook |
|
43 | from IPython.core.displayhook import DisplayHook | |
44 | from IPython.core.error import TryNext, UsageError |
|
44 | from IPython.core.error import TryNext, UsageError | |
45 | from IPython.core.extensions import ExtensionManager |
|
45 | from IPython.core.extensions import ExtensionManager | |
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
47 | from IPython.core.inputlist import InputList |
|
47 | from IPython.core.inputlist import InputList | |
48 | from IPython.core.logger import Logger |
|
48 | from IPython.core.logger import Logger | |
49 | from IPython.core.magic import Magic |
|
49 | from IPython.core.magic import Magic | |
50 | from IPython.core.payload import PayloadManager |
|
50 | from IPython.core.payload import PayloadManager | |
51 | from IPython.core.plugin import PluginManager |
|
51 | from IPython.core.plugin import PluginManager | |
52 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
52 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
53 | from IPython.external.Itpl import ItplNS |
|
53 | from IPython.external.Itpl import ItplNS | |
54 | from IPython.utils import PyColorize |
|
54 | from IPython.utils import PyColorize | |
55 | from IPython.utils import io |
|
55 | from IPython.utils import io | |
56 | from IPython.utils import pickleshare |
|
56 | from IPython.utils import pickleshare | |
57 | from IPython.utils.doctestreload import doctest_reload |
|
57 | from IPython.utils.doctestreload import doctest_reload | |
58 | from IPython.utils.io import ask_yes_no, rprint |
|
58 | from IPython.utils.io import ask_yes_no, rprint | |
59 | from IPython.utils.ipstruct import Struct |
|
59 | from IPython.utils.ipstruct import Struct | |
60 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
60 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
61 | from IPython.utils.process import system, getoutput |
|
61 | from IPython.utils.process import system, getoutput | |
62 | from IPython.utils.strdispatch import StrDispatch |
|
62 | from IPython.utils.strdispatch import StrDispatch | |
63 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
63 | from IPython.utils.syspathcontext import prepended_to_syspath | |
64 | from IPython.utils.text import num_ini_spaces, format_screen |
|
64 | from IPython.utils.text import num_ini_spaces, format_screen | |
65 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
65 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
66 | List, Unicode, Instance, Type) |
|
66 | List, Unicode, Instance, Type) | |
67 | from IPython.utils.warn import warn, error, fatal |
|
67 | from IPython.utils.warn import warn, error, fatal | |
68 | import IPython.core.hooks |
|
68 | import IPython.core.hooks | |
69 |
|
69 | |||
70 | # from IPython.utils import growl |
|
70 | # from IPython.utils import growl | |
71 | # growl.start("IPython") |
|
71 | # growl.start("IPython") | |
72 |
|
72 | |||
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 | # Globals |
|
74 | # Globals | |
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Utilities |
|
81 | # Utilities | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | # store the builtin raw_input globally, and use this always, in case user code | |
85 | # overwrites it (like wx.py.PyShell does) |
|
85 | # overwrites it (like wx.py.PyShell does) | |
86 | raw_input_original = raw_input |
|
86 | raw_input_original = raw_input | |
87 |
|
87 | |||
88 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
89 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
90 |
|
90 | |||
91 | oldvalue = 0 |
|
91 | oldvalue = 0 | |
92 | try: |
|
92 | try: | |
93 | oldvalue = file.softspace |
|
93 | oldvalue = file.softspace | |
94 | except AttributeError: |
|
94 | except AttributeError: | |
95 | pass |
|
95 | pass | |
96 | try: |
|
96 | try: | |
97 | file.softspace = newvalue |
|
97 | file.softspace = newvalue | |
98 | except (AttributeError, TypeError): |
|
98 | except (AttributeError, TypeError): | |
99 | # "attribute-less object" or "read-only attributes" |
|
99 | # "attribute-less object" or "read-only attributes" | |
100 | pass |
|
100 | pass | |
101 | return oldvalue |
|
101 | return oldvalue | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def no_op(*a, **kw): pass |
|
104 | def no_op(*a, **kw): pass | |
105 |
|
105 | |||
106 | class SpaceInInput(exceptions.Exception): pass |
|
106 | class SpaceInInput(exceptions.Exception): pass | |
107 |
|
107 | |||
108 | class Bunch: pass |
|
108 | class Bunch: pass | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | def get_default_colors(): |
|
111 | def get_default_colors(): | |
112 | if sys.platform=='darwin': |
|
112 | if sys.platform=='darwin': | |
113 | return "LightBG" |
|
113 | return "LightBG" | |
114 | elif os.name=='nt': |
|
114 | elif os.name=='nt': | |
115 | return 'Linux' |
|
115 | return 'Linux' | |
116 | else: |
|
116 | else: | |
117 | return 'Linux' |
|
117 | return 'Linux' | |
118 |
|
118 | |||
119 |
|
119 | |||
120 | class SeparateStr(Str): |
|
120 | class SeparateStr(Str): | |
121 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | """A Str subclass to validate separate_in, separate_out, etc. | |
122 |
|
122 | |||
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
124 | """ |
|
124 | """ | |
125 |
|
125 | |||
126 | def validate(self, obj, value): |
|
126 | def validate(self, obj, value): | |
127 | if value == '0': value = '' |
|
127 | if value == '0': value = '' | |
128 | value = value.replace('\\n','\n') |
|
128 | value = value.replace('\\n','\n') | |
129 | return super(SeparateStr, self).validate(obj, value) |
|
129 | return super(SeparateStr, self).validate(obj, value) | |
130 |
|
130 | |||
131 | class MultipleInstanceError(Exception): |
|
131 | class MultipleInstanceError(Exception): | |
132 | pass |
|
132 | pass | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
136 | # Main IPython class |
|
136 | # Main IPython class | |
137 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | class InteractiveShell(Configurable, Magic): |
|
140 | class InteractiveShell(Configurable, Magic): | |
141 | """An enhanced, interactive shell for Python.""" |
|
141 | """An enhanced, interactive shell for Python.""" | |
142 |
|
142 | |||
143 | _instance = None |
|
143 | _instance = None | |
144 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
144 | autocall = Enum((0,1,2), default_value=1, config=True) | |
145 | # TODO: remove all autoindent logic and put into frontends. |
|
145 | # TODO: remove all autoindent logic and put into frontends. | |
146 | # We can't do this yet because even runlines uses the autoindent. |
|
146 | # We can't do this yet because even runlines uses the autoindent. | |
147 | autoindent = CBool(True, config=True) |
|
147 | autoindent = CBool(True, config=True) | |
148 | automagic = CBool(True, config=True) |
|
148 | automagic = CBool(True, config=True) | |
149 | cache_size = Int(1000, config=True) |
|
149 | cache_size = Int(1000, config=True) | |
150 | color_info = CBool(True, config=True) |
|
150 | color_info = CBool(True, config=True) | |
151 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
151 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
152 | default_value=get_default_colors(), config=True) |
|
152 | default_value=get_default_colors(), config=True) | |
153 | debug = CBool(False, config=True) |
|
153 | debug = CBool(False, config=True) | |
154 | deep_reload = CBool(False, config=True) |
|
154 | deep_reload = CBool(False, config=True) | |
155 | displayhook_class = Type(DisplayHook) |
|
155 | displayhook_class = Type(DisplayHook) | |
156 | filename = Str("<ipython console>") |
|
156 | filename = Str("<ipython console>") | |
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
158 | logstart = CBool(False, config=True) |
|
158 | logstart = CBool(False, config=True) | |
159 | logfile = Str('', config=True) |
|
159 | logfile = Str('', config=True) | |
160 | logappend = Str('', config=True) |
|
160 | logappend = Str('', config=True) | |
161 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
161 | object_info_string_level = Enum((0,1,2), default_value=0, | |
162 | config=True) |
|
162 | config=True) | |
163 | pdb = CBool(False, config=True) |
|
163 | pdb = CBool(False, config=True) | |
164 | pprint = CBool(True, config=True) |
|
164 | pprint = CBool(True, config=True) | |
165 | profile = Str('', config=True) |
|
165 | profile = Str('', config=True) | |
166 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
166 | prompt_in1 = Str('In [\\#]: ', config=True) | |
167 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
167 | prompt_in2 = Str(' .\\D.: ', config=True) | |
168 | prompt_out = Str('Out[\\#]: ', config=True) |
|
168 | prompt_out = Str('Out[\\#]: ', config=True) | |
169 | prompts_pad_left = CBool(True, config=True) |
|
169 | prompts_pad_left = CBool(True, config=True) | |
170 | quiet = CBool(False, config=True) |
|
170 | quiet = CBool(False, config=True) | |
171 |
|
171 | |||
172 | # The readline stuff will eventually be moved to the terminal subclass |
|
172 | # The readline stuff will eventually be moved to the terminal subclass | |
173 | # but for now, we can't do that as readline is welded in everywhere. |
|
173 | # but for now, we can't do that as readline is welded in everywhere. | |
174 | readline_use = CBool(True, config=True) |
|
174 | readline_use = CBool(True, config=True) | |
175 | readline_merge_completions = CBool(True, config=True) |
|
175 | readline_merge_completions = CBool(True, config=True) | |
176 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
176 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
177 | readline_remove_delims = Str('-/~', config=True) |
|
177 | readline_remove_delims = Str('-/~', config=True) | |
178 | readline_parse_and_bind = List([ |
|
178 | readline_parse_and_bind = List([ | |
179 | 'tab: complete', |
|
179 | 'tab: complete', | |
180 | '"\C-l": clear-screen', |
|
180 | '"\C-l": clear-screen', | |
181 | 'set show-all-if-ambiguous on', |
|
181 | 'set show-all-if-ambiguous on', | |
182 | '"\C-o": tab-insert', |
|
182 | '"\C-o": tab-insert', | |
183 | '"\M-i": " "', |
|
183 | '"\M-i": " "', | |
184 | '"\M-o": "\d\d\d\d"', |
|
184 | '"\M-o": "\d\d\d\d"', | |
185 | '"\M-I": "\d\d\d\d"', |
|
185 | '"\M-I": "\d\d\d\d"', | |
186 | '"\C-r": reverse-search-history', |
|
186 | '"\C-r": reverse-search-history', | |
187 | '"\C-s": forward-search-history', |
|
187 | '"\C-s": forward-search-history', | |
188 | '"\C-p": history-search-backward', |
|
188 | '"\C-p": history-search-backward', | |
189 | '"\C-n": history-search-forward', |
|
189 | '"\C-n": history-search-forward', | |
190 | '"\e[A": history-search-backward', |
|
190 | '"\e[A": history-search-backward', | |
191 | '"\e[B": history-search-forward', |
|
191 | '"\e[B": history-search-forward', | |
192 | '"\C-k": kill-line', |
|
192 | '"\C-k": kill-line', | |
193 | '"\C-u": unix-line-discard', |
|
193 | '"\C-u": unix-line-discard', | |
194 | ], allow_none=False, config=True) |
|
194 | ], allow_none=False, config=True) | |
195 |
|
195 | |||
196 | # TODO: this part of prompt management should be moved to the frontends. |
|
196 | # TODO: this part of prompt management should be moved to the frontends. | |
197 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
197 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
198 | separate_in = SeparateStr('\n', config=True) |
|
198 | separate_in = SeparateStr('\n', config=True) | |
199 | separate_out = SeparateStr('', config=True) |
|
199 | separate_out = SeparateStr('', config=True) | |
200 | separate_out2 = SeparateStr('', config=True) |
|
200 | separate_out2 = SeparateStr('', config=True) | |
201 | wildcards_case_sensitive = CBool(True, config=True) |
|
201 | wildcards_case_sensitive = CBool(True, config=True) | |
202 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
202 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
203 | default_value='Context', config=True) |
|
203 | default_value='Context', config=True) | |
204 |
|
204 | |||
205 | # Subcomponents of InteractiveShell |
|
205 | # Subcomponents of InteractiveShell | |
206 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
206 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
207 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
207 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
208 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
208 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
209 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
209 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
210 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
210 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
211 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
211 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
212 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
212 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
213 |
|
213 | |||
214 | def __init__(self, config=None, ipython_dir=None, |
|
214 | def __init__(self, config=None, ipython_dir=None, | |
215 | user_ns=None, user_global_ns=None, |
|
215 | user_ns=None, user_global_ns=None, | |
216 | custom_exceptions=((),None)): |
|
216 | custom_exceptions=((),None)): | |
217 |
|
217 | |||
218 | # This is where traits with a config_key argument are updated |
|
218 | # This is where traits with a config_key argument are updated | |
219 | # from the values on config. |
|
219 | # from the values on config. | |
220 | super(InteractiveShell, self).__init__(config=config) |
|
220 | super(InteractiveShell, self).__init__(config=config) | |
221 |
|
221 | |||
222 | # These are relatively independent and stateless |
|
222 | # These are relatively independent and stateless | |
223 | self.init_ipython_dir(ipython_dir) |
|
223 | self.init_ipython_dir(ipython_dir) | |
224 | self.init_instance_attrs() |
|
224 | self.init_instance_attrs() | |
225 |
|
225 | |||
226 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
226 | # Create namespaces (user_ns, user_global_ns, etc.) | |
227 | self.init_create_namespaces(user_ns, user_global_ns) |
|
227 | self.init_create_namespaces(user_ns, user_global_ns) | |
228 | # This has to be done after init_create_namespaces because it uses |
|
228 | # This has to be done after init_create_namespaces because it uses | |
229 | # something in self.user_ns, but before init_sys_modules, which |
|
229 | # something in self.user_ns, but before init_sys_modules, which | |
230 | # is the first thing to modify sys. |
|
230 | # is the first thing to modify sys. | |
231 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
231 | # TODO: When we override sys.stdout and sys.stderr before this class | |
232 | # is created, we are saving the overridden ones here. Not sure if this |
|
232 | # is created, we are saving the overridden ones here. Not sure if this | |
233 | # is what we want to do. |
|
233 | # is what we want to do. | |
234 | self.save_sys_module_state() |
|
234 | self.save_sys_module_state() | |
235 | self.init_sys_modules() |
|
235 | self.init_sys_modules() | |
236 |
|
236 | |||
237 | self.init_history() |
|
237 | self.init_history() | |
238 | self.init_encoding() |
|
238 | self.init_encoding() | |
239 | self.init_prefilter() |
|
239 | self.init_prefilter() | |
240 |
|
240 | |||
241 | Magic.__init__(self, self) |
|
241 | Magic.__init__(self, self) | |
242 |
|
242 | |||
243 | self.init_syntax_highlighting() |
|
243 | self.init_syntax_highlighting() | |
244 | self.init_hooks() |
|
244 | self.init_hooks() | |
245 | self.init_pushd_popd_magic() |
|
245 | self.init_pushd_popd_magic() | |
246 | # self.init_traceback_handlers use to be here, but we moved it below |
|
246 | # self.init_traceback_handlers use to be here, but we moved it below | |
247 | # because it and init_io have to come after init_readline. |
|
247 | # because it and init_io have to come after init_readline. | |
248 | self.init_user_ns() |
|
248 | self.init_user_ns() | |
249 | self.init_logger() |
|
249 | self.init_logger() | |
250 | self.init_alias() |
|
250 | self.init_alias() | |
251 | self.init_builtins() |
|
251 | self.init_builtins() | |
252 |
|
252 | |||
253 | # pre_config_initialization |
|
253 | # pre_config_initialization | |
254 | self.init_shadow_hist() |
|
254 | self.init_shadow_hist() | |
255 |
|
255 | |||
256 | # The next section should contain averything that was in ipmaker. |
|
256 | # The next section should contain averything that was in ipmaker. | |
257 | self.init_logstart() |
|
257 | self.init_logstart() | |
258 |
|
258 | |||
259 | # The following was in post_config_initialization |
|
259 | # The following was in post_config_initialization | |
260 | self.init_inspector() |
|
260 | self.init_inspector() | |
261 | # init_readline() must come before init_io(), because init_io uses |
|
261 | # init_readline() must come before init_io(), because init_io uses | |
262 | # readline related things. |
|
262 | # readline related things. | |
263 | self.init_readline() |
|
263 | self.init_readline() | |
264 | # TODO: init_io() needs to happen before init_traceback handlers |
|
264 | # TODO: init_io() needs to happen before init_traceback handlers | |
265 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
265 | # because the traceback handlers hardcode the stdout/stderr streams. | |
266 | # This logic in in debugger.Pdb and should eventually be changed. |
|
266 | # This logic in in debugger.Pdb and should eventually be changed. | |
267 | self.init_io() |
|
267 | self.init_io() | |
268 | self.init_traceback_handlers(custom_exceptions) |
|
268 | self.init_traceback_handlers(custom_exceptions) | |
269 | self.init_prompts() |
|
269 | self.init_prompts() | |
270 | self.init_displayhook() |
|
270 | self.init_displayhook() | |
271 | self.init_reload_doctest() |
|
271 | self.init_reload_doctest() | |
272 | self.init_magics() |
|
272 | self.init_magics() | |
273 | self.init_pdb() |
|
273 | self.init_pdb() | |
274 | self.init_extension_manager() |
|
274 | self.init_extension_manager() | |
275 | self.init_plugin_manager() |
|
275 | self.init_plugin_manager() | |
276 | self.init_payload() |
|
276 | self.init_payload() | |
277 | self.hooks.late_startup_hook() |
|
277 | self.hooks.late_startup_hook() | |
278 |
|
278 | |||
279 | @classmethod |
|
279 | @classmethod | |
280 | def instance(cls, *args, **kwargs): |
|
280 | def instance(cls, *args, **kwargs): | |
281 | """Returns a global InteractiveShell instance.""" |
|
281 | """Returns a global InteractiveShell instance.""" | |
282 | if cls._instance is None: |
|
282 | if cls._instance is None: | |
283 | inst = cls(*args, **kwargs) |
|
283 | inst = cls(*args, **kwargs) | |
284 | # Now make sure that the instance will also be returned by |
|
284 | # Now make sure that the instance will also be returned by | |
285 | # the subclasses instance attribute. |
|
285 | # the subclasses instance attribute. | |
286 | for subclass in cls.mro(): |
|
286 | for subclass in cls.mro(): | |
287 | if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell): |
|
287 | if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell): | |
288 | subclass._instance = inst |
|
288 | subclass._instance = inst | |
289 | else: |
|
289 | else: | |
290 | break |
|
290 | break | |
291 | if isinstance(cls._instance, cls): |
|
291 | if isinstance(cls._instance, cls): | |
292 | return cls._instance |
|
292 | return cls._instance | |
293 | else: |
|
293 | else: | |
294 | raise MultipleInstanceError( |
|
294 | raise MultipleInstanceError( | |
295 | 'Multiple incompatible subclass instances of ' |
|
295 | 'Multiple incompatible subclass instances of ' | |
296 | 'InteractiveShell are being created.' |
|
296 | 'InteractiveShell are being created.' | |
297 | ) |
|
297 | ) | |
298 |
|
298 | |||
299 | @classmethod |
|
299 | @classmethod | |
300 | def initialized(cls): |
|
300 | def initialized(cls): | |
301 | return hasattr(cls, "_instance") |
|
301 | return hasattr(cls, "_instance") | |
302 |
|
302 | |||
303 | def get_ipython(self): |
|
303 | def get_ipython(self): | |
304 | """Return the currently running IPython instance.""" |
|
304 | """Return the currently running IPython instance.""" | |
305 | return self |
|
305 | return self | |
306 |
|
306 | |||
307 | #------------------------------------------------------------------------- |
|
307 | #------------------------------------------------------------------------- | |
308 | # Trait changed handlers |
|
308 | # Trait changed handlers | |
309 | #------------------------------------------------------------------------- |
|
309 | #------------------------------------------------------------------------- | |
310 |
|
310 | |||
311 | def _ipython_dir_changed(self, name, new): |
|
311 | def _ipython_dir_changed(self, name, new): | |
312 | if not os.path.isdir(new): |
|
312 | if not os.path.isdir(new): | |
313 | os.makedirs(new, mode = 0777) |
|
313 | os.makedirs(new, mode = 0777) | |
314 |
|
314 | |||
315 | def set_autoindent(self,value=None): |
|
315 | def set_autoindent(self,value=None): | |
316 | """Set the autoindent flag, checking for readline support. |
|
316 | """Set the autoindent flag, checking for readline support. | |
317 |
|
317 | |||
318 | If called with no arguments, it acts as a toggle.""" |
|
318 | If called with no arguments, it acts as a toggle.""" | |
319 |
|
319 | |||
320 | if not self.has_readline: |
|
320 | if not self.has_readline: | |
321 | if os.name == 'posix': |
|
321 | if os.name == 'posix': | |
322 | warn("The auto-indent feature requires the readline library") |
|
322 | warn("The auto-indent feature requires the readline library") | |
323 | self.autoindent = 0 |
|
323 | self.autoindent = 0 | |
324 | return |
|
324 | return | |
325 | if value is None: |
|
325 | if value is None: | |
326 | self.autoindent = not self.autoindent |
|
326 | self.autoindent = not self.autoindent | |
327 | else: |
|
327 | else: | |
328 | self.autoindent = value |
|
328 | self.autoindent = value | |
329 |
|
329 | |||
330 | #------------------------------------------------------------------------- |
|
330 | #------------------------------------------------------------------------- | |
331 | # init_* methods called by __init__ |
|
331 | # init_* methods called by __init__ | |
332 | #------------------------------------------------------------------------- |
|
332 | #------------------------------------------------------------------------- | |
333 |
|
333 | |||
334 | def init_ipython_dir(self, ipython_dir): |
|
334 | def init_ipython_dir(self, ipython_dir): | |
335 | if ipython_dir is not None: |
|
335 | if ipython_dir is not None: | |
336 | self.ipython_dir = ipython_dir |
|
336 | self.ipython_dir = ipython_dir | |
337 | self.config.Global.ipython_dir = self.ipython_dir |
|
337 | self.config.Global.ipython_dir = self.ipython_dir | |
338 | return |
|
338 | return | |
339 |
|
339 | |||
340 | if hasattr(self.config.Global, 'ipython_dir'): |
|
340 | if hasattr(self.config.Global, 'ipython_dir'): | |
341 | self.ipython_dir = self.config.Global.ipython_dir |
|
341 | self.ipython_dir = self.config.Global.ipython_dir | |
342 | else: |
|
342 | else: | |
343 | self.ipython_dir = get_ipython_dir() |
|
343 | self.ipython_dir = get_ipython_dir() | |
344 |
|
344 | |||
345 | # All children can just read this |
|
345 | # All children can just read this | |
346 | self.config.Global.ipython_dir = self.ipython_dir |
|
346 | self.config.Global.ipython_dir = self.ipython_dir | |
347 |
|
347 | |||
348 | def init_instance_attrs(self): |
|
348 | def init_instance_attrs(self): | |
349 | self.more = False |
|
349 | self.more = False | |
350 |
|
350 | |||
351 | # command compiler |
|
351 | # command compiler | |
352 | self.compile = codeop.CommandCompiler() |
|
352 | self.compile = codeop.CommandCompiler() | |
353 |
|
353 | |||
354 | # User input buffer |
|
354 | # User input buffer | |
355 | self.buffer = [] |
|
355 | self.buffer = [] | |
356 |
|
356 | |||
357 | # Make an empty namespace, which extension writers can rely on both |
|
357 | # Make an empty namespace, which extension writers can rely on both | |
358 | # existing and NEVER being used by ipython itself. This gives them a |
|
358 | # existing and NEVER being used by ipython itself. This gives them a | |
359 | # convenient location for storing additional information and state |
|
359 | # convenient location for storing additional information and state | |
360 | # their extensions may require, without fear of collisions with other |
|
360 | # their extensions may require, without fear of collisions with other | |
361 | # ipython names that may develop later. |
|
361 | # ipython names that may develop later. | |
362 | self.meta = Struct() |
|
362 | self.meta = Struct() | |
363 |
|
363 | |||
364 | # Object variable to store code object waiting execution. This is |
|
364 | # Object variable to store code object waiting execution. This is | |
365 | # used mainly by the multithreaded shells, but it can come in handy in |
|
365 | # used mainly by the multithreaded shells, but it can come in handy in | |
366 | # other situations. No need to use a Queue here, since it's a single |
|
366 | # other situations. No need to use a Queue here, since it's a single | |
367 | # item which gets cleared once run. |
|
367 | # item which gets cleared once run. | |
368 | self.code_to_run = None |
|
368 | self.code_to_run = None | |
369 |
|
369 | |||
370 | # Temporary files used for various purposes. Deleted at exit. |
|
370 | # Temporary files used for various purposes. Deleted at exit. | |
371 | self.tempfiles = [] |
|
371 | self.tempfiles = [] | |
372 |
|
372 | |||
373 | # Keep track of readline usage (later set by init_readline) |
|
373 | # Keep track of readline usage (later set by init_readline) | |
374 | self.has_readline = False |
|
374 | self.has_readline = False | |
375 |
|
375 | |||
376 | # keep track of where we started running (mainly for crash post-mortem) |
|
376 | # keep track of where we started running (mainly for crash post-mortem) | |
377 | # This is not being used anywhere currently. |
|
377 | # This is not being used anywhere currently. | |
378 | self.starting_dir = os.getcwd() |
|
378 | self.starting_dir = os.getcwd() | |
379 |
|
379 | |||
380 | # Indentation management |
|
380 | # Indentation management | |
381 | self.indent_current_nsp = 0 |
|
381 | self.indent_current_nsp = 0 | |
382 |
|
382 | |||
383 | def init_encoding(self): |
|
383 | def init_encoding(self): | |
384 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
384 | # Get system encoding at startup time. Certain terminals (like Emacs | |
385 | # under Win32 have it set to None, and we need to have a known valid |
|
385 | # under Win32 have it set to None, and we need to have a known valid | |
386 | # encoding to use in the raw_input() method |
|
386 | # encoding to use in the raw_input() method | |
387 | try: |
|
387 | try: | |
388 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
388 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
389 | except AttributeError: |
|
389 | except AttributeError: | |
390 | self.stdin_encoding = 'ascii' |
|
390 | self.stdin_encoding = 'ascii' | |
391 |
|
391 | |||
392 | def init_syntax_highlighting(self): |
|
392 | def init_syntax_highlighting(self): | |
393 | # Python source parser/formatter for syntax highlighting |
|
393 | # Python source parser/formatter for syntax highlighting | |
394 | pyformat = PyColorize.Parser().format |
|
394 | pyformat = PyColorize.Parser().format | |
395 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
395 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
396 |
|
396 | |||
397 | def init_pushd_popd_magic(self): |
|
397 | def init_pushd_popd_magic(self): | |
398 | # for pushd/popd management |
|
398 | # for pushd/popd management | |
399 | try: |
|
399 | try: | |
400 | self.home_dir = get_home_dir() |
|
400 | self.home_dir = get_home_dir() | |
401 | except HomeDirError, msg: |
|
401 | except HomeDirError, msg: | |
402 | fatal(msg) |
|
402 | fatal(msg) | |
403 |
|
403 | |||
404 | self.dir_stack = [] |
|
404 | self.dir_stack = [] | |
405 |
|
405 | |||
406 | def init_logger(self): |
|
406 | def init_logger(self): | |
407 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
407 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
408 | # local shortcut, this is used a LOT |
|
408 | # local shortcut, this is used a LOT | |
409 | self.log = self.logger.log |
|
409 | self.log = self.logger.log | |
410 |
|
410 | |||
411 | def init_logstart(self): |
|
411 | def init_logstart(self): | |
412 | if self.logappend: |
|
412 | if self.logappend: | |
413 | self.magic_logstart(self.logappend + ' append') |
|
413 | self.magic_logstart(self.logappend + ' append') | |
414 | elif self.logfile: |
|
414 | elif self.logfile: | |
415 | self.magic_logstart(self.logfile) |
|
415 | self.magic_logstart(self.logfile) | |
416 | elif self.logstart: |
|
416 | elif self.logstart: | |
417 | self.magic_logstart() |
|
417 | self.magic_logstart() | |
418 |
|
418 | |||
419 | def init_builtins(self): |
|
419 | def init_builtins(self): | |
420 | self.builtin_trap = BuiltinTrap(shell=self) |
|
420 | self.builtin_trap = BuiltinTrap(shell=self) | |
421 |
|
421 | |||
422 | def init_inspector(self): |
|
422 | def init_inspector(self): | |
423 | # Object inspector |
|
423 | # Object inspector | |
424 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
424 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
425 | PyColorize.ANSICodeColors, |
|
425 | PyColorize.ANSICodeColors, | |
426 | 'NoColor', |
|
426 | 'NoColor', | |
427 | self.object_info_string_level) |
|
427 | self.object_info_string_level) | |
428 |
|
428 | |||
429 | def init_io(self): |
|
429 | def init_io(self): | |
430 | import IPython.utils.io |
|
430 | import IPython.utils.io | |
431 | if sys.platform == 'win32' and self.has_readline: |
|
431 | if sys.platform == 'win32' and self.has_readline: | |
432 | Term = io.IOTerm( |
|
432 | Term = io.IOTerm( | |
433 | cout=self.readline._outputfile,cerr=self.readline._outputfile |
|
433 | cout=self.readline._outputfile,cerr=self.readline._outputfile | |
434 | ) |
|
434 | ) | |
435 | else: |
|
435 | else: | |
436 | Term = io.IOTerm() |
|
436 | Term = io.IOTerm() | |
437 | io.Term = Term |
|
437 | io.Term = Term | |
438 |
|
438 | |||
439 | def init_prompts(self): |
|
439 | def init_prompts(self): | |
440 | # TODO: This is a pass for now because the prompts are managed inside |
|
440 | # TODO: This is a pass for now because the prompts are managed inside | |
441 | # the DisplayHook. Once there is a separate prompt manager, this |
|
441 | # the DisplayHook. Once there is a separate prompt manager, this | |
442 | # will initialize that object and all prompt related information. |
|
442 | # will initialize that object and all prompt related information. | |
443 | pass |
|
443 | pass | |
444 |
|
444 | |||
445 | def init_displayhook(self): |
|
445 | def init_displayhook(self): | |
446 | # Initialize displayhook, set in/out prompts and printing system |
|
446 | # Initialize displayhook, set in/out prompts and printing system | |
447 | self.displayhook = self.displayhook_class( |
|
447 | self.displayhook = self.displayhook_class( | |
448 | shell=self, |
|
448 | shell=self, | |
449 | cache_size=self.cache_size, |
|
449 | cache_size=self.cache_size, | |
450 | input_sep = self.separate_in, |
|
450 | input_sep = self.separate_in, | |
451 | output_sep = self.separate_out, |
|
451 | output_sep = self.separate_out, | |
452 | output_sep2 = self.separate_out2, |
|
452 | output_sep2 = self.separate_out2, | |
453 | ps1 = self.prompt_in1, |
|
453 | ps1 = self.prompt_in1, | |
454 | ps2 = self.prompt_in2, |
|
454 | ps2 = self.prompt_in2, | |
455 | ps_out = self.prompt_out, |
|
455 | ps_out = self.prompt_out, | |
456 | pad_left = self.prompts_pad_left |
|
456 | pad_left = self.prompts_pad_left | |
457 | ) |
|
457 | ) | |
458 | # This is a context manager that installs/revmoes the displayhook at |
|
458 | # This is a context manager that installs/revmoes the displayhook at | |
459 | # the appropriate time. |
|
459 | # the appropriate time. | |
460 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
460 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
461 |
|
461 | |||
462 | def init_reload_doctest(self): |
|
462 | def init_reload_doctest(self): | |
463 | # Do a proper resetting of doctest, including the necessary displayhook |
|
463 | # Do a proper resetting of doctest, including the necessary displayhook | |
464 | # monkeypatching |
|
464 | # monkeypatching | |
465 | try: |
|
465 | try: | |
466 | doctest_reload() |
|
466 | doctest_reload() | |
467 | except ImportError: |
|
467 | except ImportError: | |
468 | warn("doctest module does not exist.") |
|
468 | warn("doctest module does not exist.") | |
469 |
|
469 | |||
470 | #------------------------------------------------------------------------- |
|
470 | #------------------------------------------------------------------------- | |
471 | # Things related to injections into the sys module |
|
471 | # Things related to injections into the sys module | |
472 | #------------------------------------------------------------------------- |
|
472 | #------------------------------------------------------------------------- | |
473 |
|
473 | |||
474 | def save_sys_module_state(self): |
|
474 | def save_sys_module_state(self): | |
475 | """Save the state of hooks in the sys module. |
|
475 | """Save the state of hooks in the sys module. | |
476 |
|
476 | |||
477 | This has to be called after self.user_ns is created. |
|
477 | This has to be called after self.user_ns is created. | |
478 | """ |
|
478 | """ | |
479 | self._orig_sys_module_state = {} |
|
479 | self._orig_sys_module_state = {} | |
480 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
480 | self._orig_sys_module_state['stdin'] = sys.stdin | |
481 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
481 | self._orig_sys_module_state['stdout'] = sys.stdout | |
482 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
482 | self._orig_sys_module_state['stderr'] = sys.stderr | |
483 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
483 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
484 | try: |
|
484 | try: | |
485 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
485 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
486 | except KeyError: |
|
486 | except KeyError: | |
487 | pass |
|
487 | pass | |
488 |
|
488 | |||
489 | def restore_sys_module_state(self): |
|
489 | def restore_sys_module_state(self): | |
490 | """Restore the state of the sys module.""" |
|
490 | """Restore the state of the sys module.""" | |
491 | try: |
|
491 | try: | |
492 | for k, v in self._orig_sys_module_state.items(): |
|
492 | for k, v in self._orig_sys_module_state.items(): | |
493 | setattr(sys, k, v) |
|
493 | setattr(sys, k, v) | |
494 | except AttributeError: |
|
494 | except AttributeError: | |
495 | pass |
|
495 | pass | |
496 | try: |
|
496 | try: | |
497 | delattr(sys, 'ipcompleter') |
|
497 | delattr(sys, 'ipcompleter') | |
498 | except AttributeError: |
|
498 | except AttributeError: | |
499 | pass |
|
499 | pass | |
500 | # Reset what what done in self.init_sys_modules |
|
500 | # Reset what what done in self.init_sys_modules | |
501 | try: |
|
501 | try: | |
502 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
502 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
503 | except (AttributeError, KeyError): |
|
503 | except (AttributeError, KeyError): | |
504 | pass |
|
504 | pass | |
505 |
|
505 | |||
506 | #------------------------------------------------------------------------- |
|
506 | #------------------------------------------------------------------------- | |
507 | # Things related to hooks |
|
507 | # Things related to hooks | |
508 | #------------------------------------------------------------------------- |
|
508 | #------------------------------------------------------------------------- | |
509 |
|
509 | |||
510 | def init_hooks(self): |
|
510 | def init_hooks(self): | |
511 | # hooks holds pointers used for user-side customizations |
|
511 | # hooks holds pointers used for user-side customizations | |
512 | self.hooks = Struct() |
|
512 | self.hooks = Struct() | |
513 |
|
513 | |||
514 | self.strdispatchers = {} |
|
514 | self.strdispatchers = {} | |
515 |
|
515 | |||
516 | # Set all default hooks, defined in the IPython.hooks module. |
|
516 | # Set all default hooks, defined in the IPython.hooks module. | |
517 | hooks = IPython.core.hooks |
|
517 | hooks = IPython.core.hooks | |
518 | for hook_name in hooks.__all__: |
|
518 | for hook_name in hooks.__all__: | |
519 | # default hooks have priority 100, i.e. low; user hooks should have |
|
519 | # default hooks have priority 100, i.e. low; user hooks should have | |
520 | # 0-100 priority |
|
520 | # 0-100 priority | |
521 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
521 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
522 |
|
522 | |||
523 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
523 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
524 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
524 | """set_hook(name,hook) -> sets an internal IPython hook. | |
525 |
|
525 | |||
526 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
526 | IPython exposes some of its internal API as user-modifiable hooks. By | |
527 | adding your function to one of these hooks, you can modify IPython's |
|
527 | adding your function to one of these hooks, you can modify IPython's | |
528 | behavior to call at runtime your own routines.""" |
|
528 | behavior to call at runtime your own routines.""" | |
529 |
|
529 | |||
530 | # At some point in the future, this should validate the hook before it |
|
530 | # At some point in the future, this should validate the hook before it | |
531 | # accepts it. Probably at least check that the hook takes the number |
|
531 | # accepts it. Probably at least check that the hook takes the number | |
532 | # of args it's supposed to. |
|
532 | # of args it's supposed to. | |
533 |
|
533 | |||
534 | f = new.instancemethod(hook,self,self.__class__) |
|
534 | f = new.instancemethod(hook,self,self.__class__) | |
535 |
|
535 | |||
536 | # check if the hook is for strdispatcher first |
|
536 | # check if the hook is for strdispatcher first | |
537 | if str_key is not None: |
|
537 | if str_key is not None: | |
538 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
538 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
539 | sdp.add_s(str_key, f, priority ) |
|
539 | sdp.add_s(str_key, f, priority ) | |
540 | self.strdispatchers[name] = sdp |
|
540 | self.strdispatchers[name] = sdp | |
541 | return |
|
541 | return | |
542 | if re_key is not None: |
|
542 | if re_key is not None: | |
543 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
543 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
544 | sdp.add_re(re.compile(re_key), f, priority ) |
|
544 | sdp.add_re(re.compile(re_key), f, priority ) | |
545 | self.strdispatchers[name] = sdp |
|
545 | self.strdispatchers[name] = sdp | |
546 | return |
|
546 | return | |
547 |
|
547 | |||
548 | dp = getattr(self.hooks, name, None) |
|
548 | dp = getattr(self.hooks, name, None) | |
549 | if name not in IPython.core.hooks.__all__: |
|
549 | if name not in IPython.core.hooks.__all__: | |
550 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
550 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
551 | if not dp: |
|
551 | if not dp: | |
552 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
552 | dp = IPython.core.hooks.CommandChainDispatcher() | |
553 |
|
553 | |||
554 | try: |
|
554 | try: | |
555 | dp.add(f,priority) |
|
555 | dp.add(f,priority) | |
556 | except AttributeError: |
|
556 | except AttributeError: | |
557 | # it was not commandchain, plain old func - replace |
|
557 | # it was not commandchain, plain old func - replace | |
558 | dp = f |
|
558 | dp = f | |
559 |
|
559 | |||
560 | setattr(self.hooks,name, dp) |
|
560 | setattr(self.hooks,name, dp) | |
561 |
|
561 | |||
562 | #------------------------------------------------------------------------- |
|
562 | #------------------------------------------------------------------------- | |
563 | # Things related to the "main" module |
|
563 | # Things related to the "main" module | |
564 | #------------------------------------------------------------------------- |
|
564 | #------------------------------------------------------------------------- | |
565 |
|
565 | |||
566 | def new_main_mod(self,ns=None): |
|
566 | def new_main_mod(self,ns=None): | |
567 | """Return a new 'main' module object for user code execution. |
|
567 | """Return a new 'main' module object for user code execution. | |
568 | """ |
|
568 | """ | |
569 | main_mod = self._user_main_module |
|
569 | main_mod = self._user_main_module | |
570 | init_fakemod_dict(main_mod,ns) |
|
570 | init_fakemod_dict(main_mod,ns) | |
571 | return main_mod |
|
571 | return main_mod | |
572 |
|
572 | |||
573 | def cache_main_mod(self,ns,fname): |
|
573 | def cache_main_mod(self,ns,fname): | |
574 | """Cache a main module's namespace. |
|
574 | """Cache a main module's namespace. | |
575 |
|
575 | |||
576 | When scripts are executed via %run, we must keep a reference to the |
|
576 | When scripts are executed via %run, we must keep a reference to the | |
577 | namespace of their __main__ module (a FakeModule instance) around so |
|
577 | namespace of their __main__ module (a FakeModule instance) around so | |
578 | that Python doesn't clear it, rendering objects defined therein |
|
578 | that Python doesn't clear it, rendering objects defined therein | |
579 | useless. |
|
579 | useless. | |
580 |
|
580 | |||
581 | This method keeps said reference in a private dict, keyed by the |
|
581 | This method keeps said reference in a private dict, keyed by the | |
582 | absolute path of the module object (which corresponds to the script |
|
582 | absolute path of the module object (which corresponds to the script | |
583 | path). This way, for multiple executions of the same script we only |
|
583 | path). This way, for multiple executions of the same script we only | |
584 | keep one copy of the namespace (the last one), thus preventing memory |
|
584 | keep one copy of the namespace (the last one), thus preventing memory | |
585 | leaks from old references while allowing the objects from the last |
|
585 | leaks from old references while allowing the objects from the last | |
586 | execution to be accessible. |
|
586 | execution to be accessible. | |
587 |
|
587 | |||
588 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
588 | Note: we can not allow the actual FakeModule instances to be deleted, | |
589 | because of how Python tears down modules (it hard-sets all their |
|
589 | because of how Python tears down modules (it hard-sets all their | |
590 | references to None without regard for reference counts). This method |
|
590 | references to None without regard for reference counts). This method | |
591 | must therefore make a *copy* of the given namespace, to allow the |
|
591 | must therefore make a *copy* of the given namespace, to allow the | |
592 | original module's __dict__ to be cleared and reused. |
|
592 | original module's __dict__ to be cleared and reused. | |
593 |
|
593 | |||
594 |
|
594 | |||
595 | Parameters |
|
595 | Parameters | |
596 | ---------- |
|
596 | ---------- | |
597 | ns : a namespace (a dict, typically) |
|
597 | ns : a namespace (a dict, typically) | |
598 |
|
598 | |||
599 | fname : str |
|
599 | fname : str | |
600 | Filename associated with the namespace. |
|
600 | Filename associated with the namespace. | |
601 |
|
601 | |||
602 | Examples |
|
602 | Examples | |
603 | -------- |
|
603 | -------- | |
604 |
|
604 | |||
605 | In [10]: import IPython |
|
605 | In [10]: import IPython | |
606 |
|
606 | |||
607 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
607 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
608 |
|
608 | |||
609 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
609 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
610 | Out[12]: True |
|
610 | Out[12]: True | |
611 | """ |
|
611 | """ | |
612 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
612 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
613 |
|
613 | |||
614 | def clear_main_mod_cache(self): |
|
614 | def clear_main_mod_cache(self): | |
615 | """Clear the cache of main modules. |
|
615 | """Clear the cache of main modules. | |
616 |
|
616 | |||
617 | Mainly for use by utilities like %reset. |
|
617 | Mainly for use by utilities like %reset. | |
618 |
|
618 | |||
619 | Examples |
|
619 | Examples | |
620 | -------- |
|
620 | -------- | |
621 |
|
621 | |||
622 | In [15]: import IPython |
|
622 | In [15]: import IPython | |
623 |
|
623 | |||
624 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
624 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
625 |
|
625 | |||
626 | In [17]: len(_ip._main_ns_cache) > 0 |
|
626 | In [17]: len(_ip._main_ns_cache) > 0 | |
627 | Out[17]: True |
|
627 | Out[17]: True | |
628 |
|
628 | |||
629 | In [18]: _ip.clear_main_mod_cache() |
|
629 | In [18]: _ip.clear_main_mod_cache() | |
630 |
|
630 | |||
631 | In [19]: len(_ip._main_ns_cache) == 0 |
|
631 | In [19]: len(_ip._main_ns_cache) == 0 | |
632 | Out[19]: True |
|
632 | Out[19]: True | |
633 | """ |
|
633 | """ | |
634 | self._main_ns_cache.clear() |
|
634 | self._main_ns_cache.clear() | |
635 |
|
635 | |||
636 | #------------------------------------------------------------------------- |
|
636 | #------------------------------------------------------------------------- | |
637 | # Things related to debugging |
|
637 | # Things related to debugging | |
638 | #------------------------------------------------------------------------- |
|
638 | #------------------------------------------------------------------------- | |
639 |
|
639 | |||
640 | def init_pdb(self): |
|
640 | def init_pdb(self): | |
641 | # Set calling of pdb on exceptions |
|
641 | # Set calling of pdb on exceptions | |
642 | # self.call_pdb is a property |
|
642 | # self.call_pdb is a property | |
643 | self.call_pdb = self.pdb |
|
643 | self.call_pdb = self.pdb | |
644 |
|
644 | |||
645 | def _get_call_pdb(self): |
|
645 | def _get_call_pdb(self): | |
646 | return self._call_pdb |
|
646 | return self._call_pdb | |
647 |
|
647 | |||
648 | def _set_call_pdb(self,val): |
|
648 | def _set_call_pdb(self,val): | |
649 |
|
649 | |||
650 | if val not in (0,1,False,True): |
|
650 | if val not in (0,1,False,True): | |
651 | raise ValueError,'new call_pdb value must be boolean' |
|
651 | raise ValueError,'new call_pdb value must be boolean' | |
652 |
|
652 | |||
653 | # store value in instance |
|
653 | # store value in instance | |
654 | self._call_pdb = val |
|
654 | self._call_pdb = val | |
655 |
|
655 | |||
656 | # notify the actual exception handlers |
|
656 | # notify the actual exception handlers | |
657 | self.InteractiveTB.call_pdb = val |
|
657 | self.InteractiveTB.call_pdb = val | |
658 |
|
658 | |||
659 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
659 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
660 | 'Control auto-activation of pdb at exceptions') |
|
660 | 'Control auto-activation of pdb at exceptions') | |
661 |
|
661 | |||
662 | def debugger(self,force=False): |
|
662 | def debugger(self,force=False): | |
663 | """Call the pydb/pdb debugger. |
|
663 | """Call the pydb/pdb debugger. | |
664 |
|
664 | |||
665 | Keywords: |
|
665 | Keywords: | |
666 |
|
666 | |||
667 | - force(False): by default, this routine checks the instance call_pdb |
|
667 | - force(False): by default, this routine checks the instance call_pdb | |
668 | flag and does not actually invoke the debugger if the flag is false. |
|
668 | flag and does not actually invoke the debugger if the flag is false. | |
669 | The 'force' option forces the debugger to activate even if the flag |
|
669 | The 'force' option forces the debugger to activate even if the flag | |
670 | is false. |
|
670 | is false. | |
671 | """ |
|
671 | """ | |
672 |
|
672 | |||
673 | if not (force or self.call_pdb): |
|
673 | if not (force or self.call_pdb): | |
674 | return |
|
674 | return | |
675 |
|
675 | |||
676 | if not hasattr(sys,'last_traceback'): |
|
676 | if not hasattr(sys,'last_traceback'): | |
677 | error('No traceback has been produced, nothing to debug.') |
|
677 | error('No traceback has been produced, nothing to debug.') | |
678 | return |
|
678 | return | |
679 |
|
679 | |||
680 | # use pydb if available |
|
680 | # use pydb if available | |
681 | if debugger.has_pydb: |
|
681 | if debugger.has_pydb: | |
682 | from pydb import pm |
|
682 | from pydb import pm | |
683 | else: |
|
683 | else: | |
684 | # fallback to our internal debugger |
|
684 | # fallback to our internal debugger | |
685 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
685 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
686 | self.history_saving_wrapper(pm)() |
|
686 | self.history_saving_wrapper(pm)() | |
687 |
|
687 | |||
688 | #------------------------------------------------------------------------- |
|
688 | #------------------------------------------------------------------------- | |
689 | # Things related to IPython's various namespaces |
|
689 | # Things related to IPython's various namespaces | |
690 | #------------------------------------------------------------------------- |
|
690 | #------------------------------------------------------------------------- | |
691 |
|
691 | |||
692 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
692 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
693 | # Create the namespace where the user will operate. user_ns is |
|
693 | # Create the namespace where the user will operate. user_ns is | |
694 | # normally the only one used, and it is passed to the exec calls as |
|
694 | # normally the only one used, and it is passed to the exec calls as | |
695 | # the locals argument. But we do carry a user_global_ns namespace |
|
695 | # the locals argument. But we do carry a user_global_ns namespace | |
696 | # given as the exec 'globals' argument, This is useful in embedding |
|
696 | # given as the exec 'globals' argument, This is useful in embedding | |
697 | # situations where the ipython shell opens in a context where the |
|
697 | # situations where the ipython shell opens in a context where the | |
698 | # distinction between locals and globals is meaningful. For |
|
698 | # distinction between locals and globals is meaningful. For | |
699 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
699 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
700 |
|
700 | |||
701 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
701 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
702 | # level as a dict instead of a module. This is a manual fix, but I |
|
702 | # level as a dict instead of a module. This is a manual fix, but I | |
703 | # should really track down where the problem is coming from. Alex |
|
703 | # should really track down where the problem is coming from. Alex | |
704 | # Schmolck reported this problem first. |
|
704 | # Schmolck reported this problem first. | |
705 |
|
705 | |||
706 | # A useful post by Alex Martelli on this topic: |
|
706 | # A useful post by Alex Martelli on this topic: | |
707 | # Re: inconsistent value from __builtins__ |
|
707 | # Re: inconsistent value from __builtins__ | |
708 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
708 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
709 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
709 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
710 | # Gruppen: comp.lang.python |
|
710 | # Gruppen: comp.lang.python | |
711 |
|
711 | |||
712 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
712 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
713 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
713 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
714 | # > <type 'dict'> |
|
714 | # > <type 'dict'> | |
715 | # > >>> print type(__builtins__) |
|
715 | # > >>> print type(__builtins__) | |
716 | # > <type 'module'> |
|
716 | # > <type 'module'> | |
717 | # > Is this difference in return value intentional? |
|
717 | # > Is this difference in return value intentional? | |
718 |
|
718 | |||
719 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
719 | # Well, it's documented that '__builtins__' can be either a dictionary | |
720 | # or a module, and it's been that way for a long time. Whether it's |
|
720 | # or a module, and it's been that way for a long time. Whether it's | |
721 | # intentional (or sensible), I don't know. In any case, the idea is |
|
721 | # intentional (or sensible), I don't know. In any case, the idea is | |
722 | # that if you need to access the built-in namespace directly, you |
|
722 | # that if you need to access the built-in namespace directly, you | |
723 | # should start with "import __builtin__" (note, no 's') which will |
|
723 | # should start with "import __builtin__" (note, no 's') which will | |
724 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
724 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
725 |
|
725 | |||
726 | # These routines return properly built dicts as needed by the rest of |
|
726 | # These routines return properly built dicts as needed by the rest of | |
727 | # the code, and can also be used by extension writers to generate |
|
727 | # the code, and can also be used by extension writers to generate | |
728 | # properly initialized namespaces. |
|
728 | # properly initialized namespaces. | |
729 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns) |
|
729 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns) | |
730 |
|
730 | |||
731 | # Assign namespaces |
|
731 | # Assign namespaces | |
732 | # This is the namespace where all normal user variables live |
|
732 | # This is the namespace where all normal user variables live | |
733 | self.user_ns = user_ns |
|
733 | self.user_ns = user_ns | |
734 | self.user_global_ns = user_global_ns |
|
734 | self.user_global_ns = user_global_ns | |
735 |
|
735 | |||
736 | # An auxiliary namespace that checks what parts of the user_ns were |
|
736 | # An auxiliary namespace that checks what parts of the user_ns were | |
737 | # loaded at startup, so we can list later only variables defined in |
|
737 | # loaded at startup, so we can list later only variables defined in | |
738 | # actual interactive use. Since it is always a subset of user_ns, it |
|
738 | # actual interactive use. Since it is always a subset of user_ns, it | |
739 | # doesn't need to be separately tracked in the ns_table. |
|
739 | # doesn't need to be separately tracked in the ns_table. | |
740 | self.user_ns_hidden = {} |
|
740 | self.user_ns_hidden = {} | |
741 |
|
741 | |||
742 | # A namespace to keep track of internal data structures to prevent |
|
742 | # A namespace to keep track of internal data structures to prevent | |
743 | # them from cluttering user-visible stuff. Will be updated later |
|
743 | # them from cluttering user-visible stuff. Will be updated later | |
744 | self.internal_ns = {} |
|
744 | self.internal_ns = {} | |
745 |
|
745 | |||
746 | # Now that FakeModule produces a real module, we've run into a nasty |
|
746 | # Now that FakeModule produces a real module, we've run into a nasty | |
747 | # problem: after script execution (via %run), the module where the user |
|
747 | # problem: after script execution (via %run), the module where the user | |
748 | # code ran is deleted. Now that this object is a true module (needed |
|
748 | # code ran is deleted. Now that this object is a true module (needed | |
749 | # so docetst and other tools work correctly), the Python module |
|
749 | # so docetst and other tools work correctly), the Python module | |
750 | # teardown mechanism runs over it, and sets to None every variable |
|
750 | # teardown mechanism runs over it, and sets to None every variable | |
751 | # present in that module. Top-level references to objects from the |
|
751 | # present in that module. Top-level references to objects from the | |
752 | # script survive, because the user_ns is updated with them. However, |
|
752 | # script survive, because the user_ns is updated with them. However, | |
753 | # calling functions defined in the script that use other things from |
|
753 | # calling functions defined in the script that use other things from | |
754 | # the script will fail, because the function's closure had references |
|
754 | # the script will fail, because the function's closure had references | |
755 | # to the original objects, which are now all None. So we must protect |
|
755 | # to the original objects, which are now all None. So we must protect | |
756 | # these modules from deletion by keeping a cache. |
|
756 | # these modules from deletion by keeping a cache. | |
757 | # |
|
757 | # | |
758 | # To avoid keeping stale modules around (we only need the one from the |
|
758 | # To avoid keeping stale modules around (we only need the one from the | |
759 | # last run), we use a dict keyed with the full path to the script, so |
|
759 | # last run), we use a dict keyed with the full path to the script, so | |
760 | # only the last version of the module is held in the cache. Note, |
|
760 | # only the last version of the module is held in the cache. Note, | |
761 | # however, that we must cache the module *namespace contents* (their |
|
761 | # however, that we must cache the module *namespace contents* (their | |
762 | # __dict__). Because if we try to cache the actual modules, old ones |
|
762 | # __dict__). Because if we try to cache the actual modules, old ones | |
763 | # (uncached) could be destroyed while still holding references (such as |
|
763 | # (uncached) could be destroyed while still holding references (such as | |
764 | # those held by GUI objects that tend to be long-lived)> |
|
764 | # those held by GUI objects that tend to be long-lived)> | |
765 | # |
|
765 | # | |
766 | # The %reset command will flush this cache. See the cache_main_mod() |
|
766 | # The %reset command will flush this cache. See the cache_main_mod() | |
767 | # and clear_main_mod_cache() methods for details on use. |
|
767 | # and clear_main_mod_cache() methods for details on use. | |
768 |
|
768 | |||
769 | # This is the cache used for 'main' namespaces |
|
769 | # This is the cache used for 'main' namespaces | |
770 | self._main_ns_cache = {} |
|
770 | self._main_ns_cache = {} | |
771 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
771 | # And this is the single instance of FakeModule whose __dict__ we keep | |
772 | # copying and clearing for reuse on each %run |
|
772 | # copying and clearing for reuse on each %run | |
773 | self._user_main_module = FakeModule() |
|
773 | self._user_main_module = FakeModule() | |
774 |
|
774 | |||
775 | # A table holding all the namespaces IPython deals with, so that |
|
775 | # A table holding all the namespaces IPython deals with, so that | |
776 | # introspection facilities can search easily. |
|
776 | # introspection facilities can search easily. | |
777 | self.ns_table = {'user':user_ns, |
|
777 | self.ns_table = {'user':user_ns, | |
778 | 'user_global':user_global_ns, |
|
778 | 'user_global':user_global_ns, | |
779 | 'internal':self.internal_ns, |
|
779 | 'internal':self.internal_ns, | |
780 | 'builtin':__builtin__.__dict__ |
|
780 | 'builtin':__builtin__.__dict__ | |
781 | } |
|
781 | } | |
782 |
|
782 | |||
783 | # Similarly, track all namespaces where references can be held and that |
|
783 | # Similarly, track all namespaces where references can be held and that | |
784 | # we can safely clear (so it can NOT include builtin). This one can be |
|
784 | # we can safely clear (so it can NOT include builtin). This one can be | |
785 | # a simple list. |
|
785 | # a simple list. | |
786 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, |
|
786 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, | |
787 | self.internal_ns, self._main_ns_cache ] |
|
787 | self.internal_ns, self._main_ns_cache ] | |
788 |
|
788 | |||
789 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
789 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
790 | """Return a valid local and global user interactive namespaces. |
|
790 | """Return a valid local and global user interactive namespaces. | |
791 |
|
791 | |||
792 | This builds a dict with the minimal information needed to operate as a |
|
792 | This builds a dict with the minimal information needed to operate as a | |
793 | valid IPython user namespace, which you can pass to the various |
|
793 | valid IPython user namespace, which you can pass to the various | |
794 | embedding classes in ipython. The default implementation returns the |
|
794 | embedding classes in ipython. The default implementation returns the | |
795 | same dict for both the locals and the globals to allow functions to |
|
795 | same dict for both the locals and the globals to allow functions to | |
796 | refer to variables in the namespace. Customized implementations can |
|
796 | refer to variables in the namespace. Customized implementations can | |
797 | return different dicts. The locals dictionary can actually be anything |
|
797 | return different dicts. The locals dictionary can actually be anything | |
798 | following the basic mapping protocol of a dict, but the globals dict |
|
798 | following the basic mapping protocol of a dict, but the globals dict | |
799 | must be a true dict, not even a subclass. It is recommended that any |
|
799 | must be a true dict, not even a subclass. It is recommended that any | |
800 | custom object for the locals namespace synchronize with the globals |
|
800 | custom object for the locals namespace synchronize with the globals | |
801 | dict somehow. |
|
801 | dict somehow. | |
802 |
|
802 | |||
803 | Raises TypeError if the provided globals namespace is not a true dict. |
|
803 | Raises TypeError if the provided globals namespace is not a true dict. | |
804 |
|
804 | |||
805 | Parameters |
|
805 | Parameters | |
806 | ---------- |
|
806 | ---------- | |
807 | user_ns : dict-like, optional |
|
807 | user_ns : dict-like, optional | |
808 | The current user namespace. The items in this namespace should |
|
808 | The current user namespace. The items in this namespace should | |
809 | be included in the output. If None, an appropriate blank |
|
809 | be included in the output. If None, an appropriate blank | |
810 | namespace should be created. |
|
810 | namespace should be created. | |
811 | user_global_ns : dict, optional |
|
811 | user_global_ns : dict, optional | |
812 | The current user global namespace. The items in this namespace |
|
812 | The current user global namespace. The items in this namespace | |
813 | should be included in the output. If None, an appropriate |
|
813 | should be included in the output. If None, an appropriate | |
814 | blank namespace should be created. |
|
814 | blank namespace should be created. | |
815 |
|
815 | |||
816 | Returns |
|
816 | Returns | |
817 | ------- |
|
817 | ------- | |
818 | A pair of dictionary-like object to be used as the local namespace |
|
818 | A pair of dictionary-like object to be used as the local namespace | |
819 | of the interpreter and a dict to be used as the global namespace. |
|
819 | of the interpreter and a dict to be used as the global namespace. | |
820 | """ |
|
820 | """ | |
821 |
|
821 | |||
822 |
|
822 | |||
823 | # We must ensure that __builtin__ (without the final 's') is always |
|
823 | # We must ensure that __builtin__ (without the final 's') is always | |
824 | # available and pointing to the __builtin__ *module*. For more details: |
|
824 | # available and pointing to the __builtin__ *module*. For more details: | |
825 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
825 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
826 |
|
826 | |||
827 | if user_ns is None: |
|
827 | if user_ns is None: | |
828 | # Set __name__ to __main__ to better match the behavior of the |
|
828 | # Set __name__ to __main__ to better match the behavior of the | |
829 | # normal interpreter. |
|
829 | # normal interpreter. | |
830 | user_ns = {'__name__' :'__main__', |
|
830 | user_ns = {'__name__' :'__main__', | |
831 | '__builtin__' : __builtin__, |
|
831 | '__builtin__' : __builtin__, | |
832 | '__builtins__' : __builtin__, |
|
832 | '__builtins__' : __builtin__, | |
833 | } |
|
833 | } | |
834 | else: |
|
834 | else: | |
835 | user_ns.setdefault('__name__','__main__') |
|
835 | user_ns.setdefault('__name__','__main__') | |
836 | user_ns.setdefault('__builtin__',__builtin__) |
|
836 | user_ns.setdefault('__builtin__',__builtin__) | |
837 | user_ns.setdefault('__builtins__',__builtin__) |
|
837 | user_ns.setdefault('__builtins__',__builtin__) | |
838 |
|
838 | |||
839 | if user_global_ns is None: |
|
839 | if user_global_ns is None: | |
840 | user_global_ns = user_ns |
|
840 | user_global_ns = user_ns | |
841 | if type(user_global_ns) is not dict: |
|
841 | if type(user_global_ns) is not dict: | |
842 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
842 | raise TypeError("user_global_ns must be a true dict; got %r" | |
843 | % type(user_global_ns)) |
|
843 | % type(user_global_ns)) | |
844 |
|
844 | |||
845 | return user_ns, user_global_ns |
|
845 | return user_ns, user_global_ns | |
846 |
|
846 | |||
847 | def init_sys_modules(self): |
|
847 | def init_sys_modules(self): | |
848 | # We need to insert into sys.modules something that looks like a |
|
848 | # We need to insert into sys.modules something that looks like a | |
849 | # module but which accesses the IPython namespace, for shelve and |
|
849 | # module but which accesses the IPython namespace, for shelve and | |
850 | # pickle to work interactively. Normally they rely on getting |
|
850 | # pickle to work interactively. Normally they rely on getting | |
851 | # everything out of __main__, but for embedding purposes each IPython |
|
851 | # everything out of __main__, but for embedding purposes each IPython | |
852 | # instance has its own private namespace, so we can't go shoving |
|
852 | # instance has its own private namespace, so we can't go shoving | |
853 | # everything into __main__. |
|
853 | # everything into __main__. | |
854 |
|
854 | |||
855 | # note, however, that we should only do this for non-embedded |
|
855 | # note, however, that we should only do this for non-embedded | |
856 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
856 | # ipythons, which really mimic the __main__.__dict__ with their own | |
857 | # namespace. Embedded instances, on the other hand, should not do |
|
857 | # namespace. Embedded instances, on the other hand, should not do | |
858 | # this because they need to manage the user local/global namespaces |
|
858 | # this because they need to manage the user local/global namespaces | |
859 | # only, but they live within a 'normal' __main__ (meaning, they |
|
859 | # only, but they live within a 'normal' __main__ (meaning, they | |
860 | # shouldn't overtake the execution environment of the script they're |
|
860 | # shouldn't overtake the execution environment of the script they're | |
861 | # embedded in). |
|
861 | # embedded in). | |
862 |
|
862 | |||
863 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
863 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
864 |
|
864 | |||
865 | try: |
|
865 | try: | |
866 | main_name = self.user_ns['__name__'] |
|
866 | main_name = self.user_ns['__name__'] | |
867 | except KeyError: |
|
867 | except KeyError: | |
868 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
868 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
869 | else: |
|
869 | else: | |
870 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
870 | sys.modules[main_name] = FakeModule(self.user_ns) | |
871 |
|
871 | |||
872 | def init_user_ns(self): |
|
872 | def init_user_ns(self): | |
873 | """Initialize all user-visible namespaces to their minimum defaults. |
|
873 | """Initialize all user-visible namespaces to their minimum defaults. | |
874 |
|
874 | |||
875 | Certain history lists are also initialized here, as they effectively |
|
875 | Certain history lists are also initialized here, as they effectively | |
876 | act as user namespaces. |
|
876 | act as user namespaces. | |
877 |
|
877 | |||
878 | Notes |
|
878 | Notes | |
879 | ----- |
|
879 | ----- | |
880 | All data structures here are only filled in, they are NOT reset by this |
|
880 | All data structures here are only filled in, they are NOT reset by this | |
881 | method. If they were not empty before, data will simply be added to |
|
881 | method. If they were not empty before, data will simply be added to | |
882 | therm. |
|
882 | therm. | |
883 | """ |
|
883 | """ | |
884 | # This function works in two parts: first we put a few things in |
|
884 | # This function works in two parts: first we put a few things in | |
885 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
885 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
886 | # initial variables aren't shown by %who. After the sync, we add the |
|
886 | # initial variables aren't shown by %who. After the sync, we add the | |
887 | # rest of what we *do* want the user to see with %who even on a new |
|
887 | # rest of what we *do* want the user to see with %who even on a new | |
888 | # session (probably nothing, so theye really only see their own stuff) |
|
888 | # session (probably nothing, so theye really only see their own stuff) | |
889 |
|
889 | |||
890 | # The user dict must *always* have a __builtin__ reference to the |
|
890 | # The user dict must *always* have a __builtin__ reference to the | |
891 | # Python standard __builtin__ namespace, which must be imported. |
|
891 | # Python standard __builtin__ namespace, which must be imported. | |
892 | # This is so that certain operations in prompt evaluation can be |
|
892 | # This is so that certain operations in prompt evaluation can be | |
893 | # reliably executed with builtins. Note that we can NOT use |
|
893 | # reliably executed with builtins. Note that we can NOT use | |
894 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
894 | # __builtins__ (note the 's'), because that can either be a dict or a | |
895 | # module, and can even mutate at runtime, depending on the context |
|
895 | # module, and can even mutate at runtime, depending on the context | |
896 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
896 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
897 | # always a module object, though it must be explicitly imported. |
|
897 | # always a module object, though it must be explicitly imported. | |
898 |
|
898 | |||
899 | # For more details: |
|
899 | # For more details: | |
900 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
900 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
901 | ns = dict(__builtin__ = __builtin__) |
|
901 | ns = dict(__builtin__ = __builtin__) | |
902 |
|
902 | |||
903 | # Put 'help' in the user namespace |
|
903 | # Put 'help' in the user namespace | |
904 | try: |
|
904 | try: | |
905 | from site import _Helper |
|
905 | from site import _Helper | |
906 | ns['help'] = _Helper() |
|
906 | ns['help'] = _Helper() | |
907 | except ImportError: |
|
907 | except ImportError: | |
908 | warn('help() not available - check site.py') |
|
908 | warn('help() not available - check site.py') | |
909 |
|
909 | |||
910 | # make global variables for user access to the histories |
|
910 | # make global variables for user access to the histories | |
911 | ns['_ih'] = self.input_hist |
|
911 | ns['_ih'] = self.input_hist | |
912 | ns['_oh'] = self.output_hist |
|
912 | ns['_oh'] = self.output_hist | |
913 | ns['_dh'] = self.dir_hist |
|
913 | ns['_dh'] = self.dir_hist | |
914 |
|
914 | |||
915 | ns['_sh'] = shadowns |
|
915 | ns['_sh'] = shadowns | |
916 |
|
916 | |||
917 | # user aliases to input and output histories. These shouldn't show up |
|
917 | # user aliases to input and output histories. These shouldn't show up | |
918 | # in %who, as they can have very large reprs. |
|
918 | # in %who, as they can have very large reprs. | |
919 | ns['In'] = self.input_hist |
|
919 | ns['In'] = self.input_hist | |
920 | ns['Out'] = self.output_hist |
|
920 | ns['Out'] = self.output_hist | |
921 |
|
921 | |||
922 | # Store myself as the public api!!! |
|
922 | # Store myself as the public api!!! | |
923 | ns['get_ipython'] = self.get_ipython |
|
923 | ns['get_ipython'] = self.get_ipython | |
924 |
|
924 | |||
925 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
925 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
926 | # by %who |
|
926 | # by %who | |
927 | self.user_ns_hidden.update(ns) |
|
927 | self.user_ns_hidden.update(ns) | |
928 |
|
928 | |||
929 | # Anything put into ns now would show up in %who. Think twice before |
|
929 | # Anything put into ns now would show up in %who. Think twice before | |
930 | # putting anything here, as we really want %who to show the user their |
|
930 | # putting anything here, as we really want %who to show the user their | |
931 | # stuff, not our variables. |
|
931 | # stuff, not our variables. | |
932 |
|
932 | |||
933 | # Finally, update the real user's namespace |
|
933 | # Finally, update the real user's namespace | |
934 | self.user_ns.update(ns) |
|
934 | self.user_ns.update(ns) | |
935 |
|
935 | |||
936 |
|
936 | |||
937 | def reset(self): |
|
937 | def reset(self): | |
938 | """Clear all internal namespaces. |
|
938 | """Clear all internal namespaces. | |
939 |
|
939 | |||
940 | Note that this is much more aggressive than %reset, since it clears |
|
940 | Note that this is much more aggressive than %reset, since it clears | |
941 | fully all namespaces, as well as all input/output lists. |
|
941 | fully all namespaces, as well as all input/output lists. | |
942 | """ |
|
942 | """ | |
943 | for ns in self.ns_refs_table: |
|
943 | for ns in self.ns_refs_table: | |
944 | ns.clear() |
|
944 | ns.clear() | |
945 |
|
945 | |||
946 | self.alias_manager.clear_aliases() |
|
946 | self.alias_manager.clear_aliases() | |
947 |
|
947 | |||
948 | # Clear input and output histories |
|
948 | # Clear input and output histories | |
949 | self.input_hist[:] = [] |
|
949 | self.input_hist[:] = [] | |
950 | self.input_hist_raw[:] = [] |
|
950 | self.input_hist_raw[:] = [] | |
951 | self.output_hist.clear() |
|
951 | self.output_hist.clear() | |
952 |
|
952 | |||
953 | # Restore the user namespaces to minimal usability |
|
953 | # Restore the user namespaces to minimal usability | |
954 | self.init_user_ns() |
|
954 | self.init_user_ns() | |
955 |
|
955 | |||
956 | # Restore the default and user aliases |
|
956 | # Restore the default and user aliases | |
957 | self.alias_manager.init_aliases() |
|
957 | self.alias_manager.init_aliases() | |
958 |
|
958 | |||
959 | def reset_selective(self, regex=None): |
|
959 | def reset_selective(self, regex=None): | |
960 | """Clear selective variables from internal namespaces based on a specified regular expression. |
|
960 | """Clear selective variables from internal namespaces based on a specified regular expression. | |
961 |
|
961 | |||
962 | Parameters |
|
962 | Parameters | |
963 | ---------- |
|
963 | ---------- | |
964 | regex : string or compiled pattern, optional |
|
964 | regex : string or compiled pattern, optional | |
965 | A regular expression pattern that will be used in searching variable names in the users |
|
965 | A regular expression pattern that will be used in searching variable names in the users | |
966 | namespaces. |
|
966 | namespaces. | |
967 | """ |
|
967 | """ | |
968 | if regex is not None: |
|
968 | if regex is not None: | |
969 | try: |
|
969 | try: | |
970 | m = re.compile(regex) |
|
970 | m = re.compile(regex) | |
971 | except TypeError: |
|
971 | except TypeError: | |
972 | raise TypeError('regex must be a string or compiled pattern') |
|
972 | raise TypeError('regex must be a string or compiled pattern') | |
973 | # Search for keys in each namespace that match the given regex |
|
973 | # Search for keys in each namespace that match the given regex | |
974 | # If a match is found, delete the key/value pair. |
|
974 | # If a match is found, delete the key/value pair. | |
975 | for ns in self.ns_refs_table: |
|
975 | for ns in self.ns_refs_table: | |
976 | for var in ns: |
|
976 | for var in ns: | |
977 | if m.search(var): |
|
977 | if m.search(var): | |
978 | del ns[var] |
|
978 | del ns[var] | |
979 |
|
979 | |||
980 | def push(self, variables, interactive=True): |
|
980 | def push(self, variables, interactive=True): | |
981 | """Inject a group of variables into the IPython user namespace. |
|
981 | """Inject a group of variables into the IPython user namespace. | |
982 |
|
982 | |||
983 | Parameters |
|
983 | Parameters | |
984 | ---------- |
|
984 | ---------- | |
985 | variables : dict, str or list/tuple of str |
|
985 | variables : dict, str or list/tuple of str | |
986 | The variables to inject into the user's namespace. If a dict, |
|
986 | The variables to inject into the user's namespace. If a dict, | |
987 | a simple update is done. If a str, the string is assumed to |
|
987 | a simple update is done. If a str, the string is assumed to | |
988 | have variable names separated by spaces. A list/tuple of str |
|
988 | have variable names separated by spaces. A list/tuple of str | |
989 | can also be used to give the variable names. If just the variable |
|
989 | can also be used to give the variable names. If just the variable | |
990 | names are give (list/tuple/str) then the variable values looked |
|
990 | names are give (list/tuple/str) then the variable values looked | |
991 | up in the callers frame. |
|
991 | up in the callers frame. | |
992 | interactive : bool |
|
992 | interactive : bool | |
993 | If True (default), the variables will be listed with the ``who`` |
|
993 | If True (default), the variables will be listed with the ``who`` | |
994 | magic. |
|
994 | magic. | |
995 | """ |
|
995 | """ | |
996 | vdict = None |
|
996 | vdict = None | |
997 |
|
997 | |||
998 | # We need a dict of name/value pairs to do namespace updates. |
|
998 | # We need a dict of name/value pairs to do namespace updates. | |
999 | if isinstance(variables, dict): |
|
999 | if isinstance(variables, dict): | |
1000 | vdict = variables |
|
1000 | vdict = variables | |
1001 | elif isinstance(variables, (basestring, list, tuple)): |
|
1001 | elif isinstance(variables, (basestring, list, tuple)): | |
1002 | if isinstance(variables, basestring): |
|
1002 | if isinstance(variables, basestring): | |
1003 | vlist = variables.split() |
|
1003 | vlist = variables.split() | |
1004 | else: |
|
1004 | else: | |
1005 | vlist = variables |
|
1005 | vlist = variables | |
1006 | vdict = {} |
|
1006 | vdict = {} | |
1007 | cf = sys._getframe(1) |
|
1007 | cf = sys._getframe(1) | |
1008 | for name in vlist: |
|
1008 | for name in vlist: | |
1009 | try: |
|
1009 | try: | |
1010 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1010 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1011 | except: |
|
1011 | except: | |
1012 | print ('Could not get variable %s from %s' % |
|
1012 | print ('Could not get variable %s from %s' % | |
1013 | (name,cf.f_code.co_name)) |
|
1013 | (name,cf.f_code.co_name)) | |
1014 | else: |
|
1014 | else: | |
1015 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1015 | raise ValueError('variables must be a dict/str/list/tuple') | |
1016 |
|
1016 | |||
1017 | # Propagate variables to user namespace |
|
1017 | # Propagate variables to user namespace | |
1018 | self.user_ns.update(vdict) |
|
1018 | self.user_ns.update(vdict) | |
1019 |
|
1019 | |||
1020 | # And configure interactive visibility |
|
1020 | # And configure interactive visibility | |
1021 | config_ns = self.user_ns_hidden |
|
1021 | config_ns = self.user_ns_hidden | |
1022 | if interactive: |
|
1022 | if interactive: | |
1023 | for name, val in vdict.iteritems(): |
|
1023 | for name, val in vdict.iteritems(): | |
1024 | config_ns.pop(name, None) |
|
1024 | config_ns.pop(name, None) | |
1025 | else: |
|
1025 | else: | |
1026 | for name,val in vdict.iteritems(): |
|
1026 | for name,val in vdict.iteritems(): | |
1027 | config_ns[name] = val |
|
1027 | config_ns[name] = val | |
1028 |
|
1028 | |||
1029 | #------------------------------------------------------------------------- |
|
1029 | #------------------------------------------------------------------------- | |
1030 | # Things related to object introspection |
|
1030 | # Things related to object introspection | |
1031 | #------------------------------------------------------------------------- |
|
1031 | #------------------------------------------------------------------------- | |
1032 | def _ofind(self, oname, namespaces=None): |
|
1032 | def _ofind(self, oname, namespaces=None): | |
1033 | """Find an object in the available namespaces. |
|
1033 | """Find an object in the available namespaces. | |
1034 |
|
1034 | |||
1035 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1035 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1036 |
|
1036 | |||
1037 | Has special code to detect magic functions. |
|
1037 | Has special code to detect magic functions. | |
1038 | """ |
|
1038 | """ | |
1039 | #oname = oname.strip() |
|
1039 | #oname = oname.strip() | |
1040 | #print '1- oname: <%r>' % oname # dbg |
|
1040 | #print '1- oname: <%r>' % oname # dbg | |
1041 | try: |
|
1041 | try: | |
1042 | oname = oname.strip().encode('ascii') |
|
1042 | oname = oname.strip().encode('ascii') | |
1043 | #print '2- oname: <%r>' % oname # dbg |
|
1043 | #print '2- oname: <%r>' % oname # dbg | |
1044 | except UnicodeEncodeError: |
|
1044 | except UnicodeEncodeError: | |
1045 | print 'Python identifiers can only contain ascii characters.' |
|
1045 | print 'Python identifiers can only contain ascii characters.' | |
1046 | return dict(found=False) |
|
1046 | return dict(found=False) | |
1047 |
|
1047 | |||
1048 | alias_ns = None |
|
1048 | alias_ns = None | |
1049 | if namespaces is None: |
|
1049 | if namespaces is None: | |
1050 | # Namespaces to search in: |
|
1050 | # Namespaces to search in: | |
1051 | # Put them in a list. The order is important so that we |
|
1051 | # Put them in a list. The order is important so that we | |
1052 | # find things in the same order that Python finds them. |
|
1052 | # find things in the same order that Python finds them. | |
1053 | namespaces = [ ('Interactive', self.user_ns), |
|
1053 | namespaces = [ ('Interactive', self.user_ns), | |
1054 | ('IPython internal', self.internal_ns), |
|
1054 | ('IPython internal', self.internal_ns), | |
1055 | ('Python builtin', __builtin__.__dict__), |
|
1055 | ('Python builtin', __builtin__.__dict__), | |
1056 | ('Alias', self.alias_manager.alias_table), |
|
1056 | ('Alias', self.alias_manager.alias_table), | |
1057 | ] |
|
1057 | ] | |
1058 | alias_ns = self.alias_manager.alias_table |
|
1058 | alias_ns = self.alias_manager.alias_table | |
1059 |
|
1059 | |||
1060 | # initialize results to 'null' |
|
1060 | # initialize results to 'null' | |
1061 | found = False; obj = None; ospace = None; ds = None; |
|
1061 | found = False; obj = None; ospace = None; ds = None; | |
1062 | ismagic = False; isalias = False; parent = None |
|
1062 | ismagic = False; isalias = False; parent = None | |
1063 |
|
1063 | |||
1064 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1064 | # We need to special-case 'print', which as of python2.6 registers as a | |
1065 | # function but should only be treated as one if print_function was |
|
1065 | # function but should only be treated as one if print_function was | |
1066 | # loaded with a future import. In this case, just bail. |
|
1066 | # loaded with a future import. In this case, just bail. | |
1067 | if (oname == 'print' and not (self.compile.compiler.flags & |
|
1067 | if (oname == 'print' and not (self.compile.compiler.flags & | |
1068 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1068 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1069 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1069 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1070 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1070 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1071 |
|
1071 | |||
1072 | # Look for the given name by splitting it in parts. If the head is |
|
1072 | # Look for the given name by splitting it in parts. If the head is | |
1073 | # found, then we look for all the remaining parts as members, and only |
|
1073 | # found, then we look for all the remaining parts as members, and only | |
1074 | # declare success if we can find them all. |
|
1074 | # declare success if we can find them all. | |
1075 | oname_parts = oname.split('.') |
|
1075 | oname_parts = oname.split('.') | |
1076 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1076 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1077 | for nsname,ns in namespaces: |
|
1077 | for nsname,ns in namespaces: | |
1078 | try: |
|
1078 | try: | |
1079 | obj = ns[oname_head] |
|
1079 | obj = ns[oname_head] | |
1080 | except KeyError: |
|
1080 | except KeyError: | |
1081 | continue |
|
1081 | continue | |
1082 | else: |
|
1082 | else: | |
1083 | #print 'oname_rest:', oname_rest # dbg |
|
1083 | #print 'oname_rest:', oname_rest # dbg | |
1084 | for part in oname_rest: |
|
1084 | for part in oname_rest: | |
1085 | try: |
|
1085 | try: | |
1086 | parent = obj |
|
1086 | parent = obj | |
1087 | obj = getattr(obj,part) |
|
1087 | obj = getattr(obj,part) | |
1088 | except: |
|
1088 | except: | |
1089 | # Blanket except b/c some badly implemented objects |
|
1089 | # Blanket except b/c some badly implemented objects | |
1090 | # allow __getattr__ to raise exceptions other than |
|
1090 | # allow __getattr__ to raise exceptions other than | |
1091 | # AttributeError, which then crashes IPython. |
|
1091 | # AttributeError, which then crashes IPython. | |
1092 | break |
|
1092 | break | |
1093 | else: |
|
1093 | else: | |
1094 | # If we finish the for loop (no break), we got all members |
|
1094 | # If we finish the for loop (no break), we got all members | |
1095 | found = True |
|
1095 | found = True | |
1096 | ospace = nsname |
|
1096 | ospace = nsname | |
1097 | if ns == alias_ns: |
|
1097 | if ns == alias_ns: | |
1098 | isalias = True |
|
1098 | isalias = True | |
1099 | break # namespace loop |
|
1099 | break # namespace loop | |
1100 |
|
1100 | |||
1101 | # Try to see if it's magic |
|
1101 | # Try to see if it's magic | |
1102 | if not found: |
|
1102 | if not found: | |
1103 | if oname.startswith(ESC_MAGIC): |
|
1103 | if oname.startswith(ESC_MAGIC): | |
1104 | oname = oname[1:] |
|
1104 | oname = oname[1:] | |
1105 | obj = getattr(self,'magic_'+oname,None) |
|
1105 | obj = getattr(self,'magic_'+oname,None) | |
1106 | if obj is not None: |
|
1106 | if obj is not None: | |
1107 | found = True |
|
1107 | found = True | |
1108 | ospace = 'IPython internal' |
|
1108 | ospace = 'IPython internal' | |
1109 | ismagic = True |
|
1109 | ismagic = True | |
1110 |
|
1110 | |||
1111 | # Last try: special-case some literals like '', [], {}, etc: |
|
1111 | # Last try: special-case some literals like '', [], {}, etc: | |
1112 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1112 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1113 | obj = eval(oname_head) |
|
1113 | obj = eval(oname_head) | |
1114 | found = True |
|
1114 | found = True | |
1115 | ospace = 'Interactive' |
|
1115 | ospace = 'Interactive' | |
1116 |
|
1116 | |||
1117 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1117 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1118 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1118 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1119 |
|
1119 | |||
1120 | def _ofind_property(self, oname, info): |
|
1120 | def _ofind_property(self, oname, info): | |
1121 | """Second part of object finding, to look for property details.""" |
|
1121 | """Second part of object finding, to look for property details.""" | |
1122 | if info.found: |
|
1122 | if info.found: | |
1123 | # Get the docstring of the class property if it exists. |
|
1123 | # Get the docstring of the class property if it exists. | |
1124 | path = oname.split('.') |
|
1124 | path = oname.split('.') | |
1125 | root = '.'.join(path[:-1]) |
|
1125 | root = '.'.join(path[:-1]) | |
1126 | if info.parent is not None: |
|
1126 | if info.parent is not None: | |
1127 | try: |
|
1127 | try: | |
1128 | target = getattr(info.parent, '__class__') |
|
1128 | target = getattr(info.parent, '__class__') | |
1129 | # The object belongs to a class instance. |
|
1129 | # The object belongs to a class instance. | |
1130 | try: |
|
1130 | try: | |
1131 | target = getattr(target, path[-1]) |
|
1131 | target = getattr(target, path[-1]) | |
1132 | # The class defines the object. |
|
1132 | # The class defines the object. | |
1133 | if isinstance(target, property): |
|
1133 | if isinstance(target, property): | |
1134 | oname = root + '.__class__.' + path[-1] |
|
1134 | oname = root + '.__class__.' + path[-1] | |
1135 | info = Struct(self._ofind(oname)) |
|
1135 | info = Struct(self._ofind(oname)) | |
1136 | except AttributeError: pass |
|
1136 | except AttributeError: pass | |
1137 | except AttributeError: pass |
|
1137 | except AttributeError: pass | |
1138 |
|
1138 | |||
1139 | # We return either the new info or the unmodified input if the object |
|
1139 | # We return either the new info or the unmodified input if the object | |
1140 | # hadn't been found |
|
1140 | # hadn't been found | |
1141 | return info |
|
1141 | return info | |
1142 |
|
1142 | |||
1143 | def _object_find(self, oname, namespaces=None): |
|
1143 | def _object_find(self, oname, namespaces=None): | |
1144 | """Find an object and return a struct with info about it.""" |
|
1144 | """Find an object and return a struct with info about it.""" | |
1145 | inf = Struct(self._ofind(oname, namespaces)) |
|
1145 | inf = Struct(self._ofind(oname, namespaces)) | |
1146 | return Struct(self._ofind_property(oname, inf)) |
|
1146 | return Struct(self._ofind_property(oname, inf)) | |
1147 |
|
1147 | |||
1148 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1148 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1149 | """Generic interface to the inspector system. |
|
1149 | """Generic interface to the inspector system. | |
1150 |
|
1150 | |||
1151 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1151 | This function is meant to be called by pdef, pdoc & friends.""" | |
1152 | info = self._object_find(oname) |
|
1152 | info = self._object_find(oname) | |
1153 | if info.found: |
|
1153 | if info.found: | |
1154 | pmethod = getattr(self.inspector, meth) |
|
1154 | pmethod = getattr(self.inspector, meth) | |
1155 | formatter = format_screen if info.ismagic else None |
|
1155 | formatter = format_screen if info.ismagic else None | |
1156 | if meth == 'pdoc': |
|
1156 | if meth == 'pdoc': | |
1157 | pmethod(info.obj, oname, formatter) |
|
1157 | pmethod(info.obj, oname, formatter) | |
1158 | elif meth == 'pinfo': |
|
1158 | elif meth == 'pinfo': | |
1159 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1159 | pmethod(info.obj, oname, formatter, info, **kw) | |
1160 | else: |
|
1160 | else: | |
1161 | pmethod(info.obj, oname) |
|
1161 | pmethod(info.obj, oname) | |
1162 | else: |
|
1162 | else: | |
1163 | print 'Object `%s` not found.' % oname |
|
1163 | print 'Object `%s` not found.' % oname | |
1164 | return 'not found' # so callers can take other action |
|
1164 | return 'not found' # so callers can take other action | |
1165 |
|
1165 | |||
1166 | def object_inspect(self, oname): |
|
1166 | def object_inspect(self, oname): | |
1167 | info = self._object_find(oname) |
|
1167 | info = self._object_find(oname) | |
1168 | if info.found: |
|
1168 | if info.found: | |
1169 | return self.inspector.info(info.obj, info=info) |
|
1169 | return self.inspector.info(info.obj, info=info) | |
1170 | else: |
|
1170 | else: | |
1171 | return oinspect.mk_object_info({}) |
|
1171 | return oinspect.mk_object_info({'found' : False}) | |
1172 |
|
1172 | |||
1173 | #------------------------------------------------------------------------- |
|
1173 | #------------------------------------------------------------------------- | |
1174 | # Things related to history management |
|
1174 | # Things related to history management | |
1175 | #------------------------------------------------------------------------- |
|
1175 | #------------------------------------------------------------------------- | |
1176 |
|
1176 | |||
1177 | def init_history(self): |
|
1177 | def init_history(self): | |
1178 | # List of input with multi-line handling. |
|
1178 | # List of input with multi-line handling. | |
1179 | self.input_hist = InputList() |
|
1179 | self.input_hist = InputList() | |
1180 | # This one will hold the 'raw' input history, without any |
|
1180 | # This one will hold the 'raw' input history, without any | |
1181 | # pre-processing. This will allow users to retrieve the input just as |
|
1181 | # pre-processing. This will allow users to retrieve the input just as | |
1182 | # it was exactly typed in by the user, with %hist -r. |
|
1182 | # it was exactly typed in by the user, with %hist -r. | |
1183 | self.input_hist_raw = InputList() |
|
1183 | self.input_hist_raw = InputList() | |
1184 |
|
1184 | |||
1185 | # list of visited directories |
|
1185 | # list of visited directories | |
1186 | try: |
|
1186 | try: | |
1187 | self.dir_hist = [os.getcwd()] |
|
1187 | self.dir_hist = [os.getcwd()] | |
1188 | except OSError: |
|
1188 | except OSError: | |
1189 | self.dir_hist = [] |
|
1189 | self.dir_hist = [] | |
1190 |
|
1190 | |||
1191 | # dict of output history |
|
1191 | # dict of output history | |
1192 | self.output_hist = {} |
|
1192 | self.output_hist = {} | |
1193 |
|
1193 | |||
1194 | # Now the history file |
|
1194 | # Now the history file | |
1195 | if self.profile: |
|
1195 | if self.profile: | |
1196 | histfname = 'history-%s' % self.profile |
|
1196 | histfname = 'history-%s' % self.profile | |
1197 | else: |
|
1197 | else: | |
1198 | histfname = 'history' |
|
1198 | histfname = 'history' | |
1199 | self.histfile = os.path.join(self.ipython_dir, histfname) |
|
1199 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
1200 |
|
1200 | |||
1201 | # Fill the history zero entry, user counter starts at 1 |
|
1201 | # Fill the history zero entry, user counter starts at 1 | |
1202 | self.input_hist.append('\n') |
|
1202 | self.input_hist.append('\n') | |
1203 | self.input_hist_raw.append('\n') |
|
1203 | self.input_hist_raw.append('\n') | |
1204 |
|
1204 | |||
1205 | def init_shadow_hist(self): |
|
1205 | def init_shadow_hist(self): | |
1206 | try: |
|
1206 | try: | |
1207 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1207 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1208 | except exceptions.UnicodeDecodeError: |
|
1208 | except exceptions.UnicodeDecodeError: | |
1209 | print "Your ipython_dir can't be decoded to unicode!" |
|
1209 | print "Your ipython_dir can't be decoded to unicode!" | |
1210 | print "Please set HOME environment variable to something that" |
|
1210 | print "Please set HOME environment variable to something that" | |
1211 | print r"only has ASCII characters, e.g. c:\home" |
|
1211 | print r"only has ASCII characters, e.g. c:\home" | |
1212 | print "Now it is", self.ipython_dir |
|
1212 | print "Now it is", self.ipython_dir | |
1213 | sys.exit() |
|
1213 | sys.exit() | |
1214 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1214 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1215 |
|
1215 | |||
1216 | def savehist(self): |
|
1216 | def savehist(self): | |
1217 | """Save input history to a file (via readline library).""" |
|
1217 | """Save input history to a file (via readline library).""" | |
1218 |
|
1218 | |||
1219 | try: |
|
1219 | try: | |
1220 | self.readline.write_history_file(self.histfile) |
|
1220 | self.readline.write_history_file(self.histfile) | |
1221 | except: |
|
1221 | except: | |
1222 | print 'Unable to save IPython command history to file: ' + \ |
|
1222 | print 'Unable to save IPython command history to file: ' + \ | |
1223 | `self.histfile` |
|
1223 | `self.histfile` | |
1224 |
|
1224 | |||
1225 | def reloadhist(self): |
|
1225 | def reloadhist(self): | |
1226 | """Reload the input history from disk file.""" |
|
1226 | """Reload the input history from disk file.""" | |
1227 |
|
1227 | |||
1228 | try: |
|
1228 | try: | |
1229 | self.readline.clear_history() |
|
1229 | self.readline.clear_history() | |
1230 | self.readline.read_history_file(self.shell.histfile) |
|
1230 | self.readline.read_history_file(self.shell.histfile) | |
1231 | except AttributeError: |
|
1231 | except AttributeError: | |
1232 | pass |
|
1232 | pass | |
1233 |
|
1233 | |||
1234 | def history_saving_wrapper(self, func): |
|
1234 | def history_saving_wrapper(self, func): | |
1235 | """ Wrap func for readline history saving |
|
1235 | """ Wrap func for readline history saving | |
1236 |
|
1236 | |||
1237 | Convert func into callable that saves & restores |
|
1237 | Convert func into callable that saves & restores | |
1238 | history around the call """ |
|
1238 | history around the call """ | |
1239 |
|
1239 | |||
1240 | if self.has_readline: |
|
1240 | if self.has_readline: | |
1241 | from IPython.utils import rlineimpl as readline |
|
1241 | from IPython.utils import rlineimpl as readline | |
1242 | else: |
|
1242 | else: | |
1243 | return func |
|
1243 | return func | |
1244 |
|
1244 | |||
1245 | def wrapper(): |
|
1245 | def wrapper(): | |
1246 | self.savehist() |
|
1246 | self.savehist() | |
1247 | try: |
|
1247 | try: | |
1248 | func() |
|
1248 | func() | |
1249 | finally: |
|
1249 | finally: | |
1250 | readline.read_history_file(self.histfile) |
|
1250 | readline.read_history_file(self.histfile) | |
1251 | return wrapper |
|
1251 | return wrapper | |
1252 |
|
1252 | |||
1253 | def get_history(self, index=None, raw=False, output=True): |
|
1253 | def get_history(self, index=None, raw=False, output=True): | |
1254 | """Get the history list. |
|
1254 | """Get the history list. | |
1255 |
|
1255 | |||
1256 | Get the input and output history. |
|
1256 | Get the input and output history. | |
1257 |
|
1257 | |||
1258 | Parameters |
|
1258 | Parameters | |
1259 | ---------- |
|
1259 | ---------- | |
1260 | index : n or (n1, n2) or None |
|
1260 | index : n or (n1, n2) or None | |
1261 | If n, then the last entries. If a tuple, then all in |
|
1261 | If n, then the last entries. If a tuple, then all in | |
1262 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
1262 | range(n1, n2). If None, then all entries. Raises IndexError if | |
1263 | the format of index is incorrect. |
|
1263 | the format of index is incorrect. | |
1264 | raw : bool |
|
1264 | raw : bool | |
1265 | If True, return the raw input. |
|
1265 | If True, return the raw input. | |
1266 | output : bool |
|
1266 | output : bool | |
1267 | If True, then return the output as well. |
|
1267 | If True, then return the output as well. | |
1268 |
|
1268 | |||
1269 | Returns |
|
1269 | Returns | |
1270 | ------- |
|
1270 | ------- | |
1271 | If output is True, then return a dict of tuples, keyed by the prompt |
|
1271 | If output is True, then return a dict of tuples, keyed by the prompt | |
1272 | numbers and with values of (input, output). If output is False, then |
|
1272 | numbers and with values of (input, output). If output is False, then | |
1273 | a dict, keyed by the prompt number with the values of input. Raises |
|
1273 | a dict, keyed by the prompt number with the values of input. Raises | |
1274 | IndexError if no history is found. |
|
1274 | IndexError if no history is found. | |
1275 | """ |
|
1275 | """ | |
1276 | if raw: |
|
1276 | if raw: | |
1277 | input_hist = self.input_hist_raw |
|
1277 | input_hist = self.input_hist_raw | |
1278 | else: |
|
1278 | else: | |
1279 | input_hist = self.input_hist |
|
1279 | input_hist = self.input_hist | |
1280 | if output: |
|
1280 | if output: | |
1281 | output_hist = self.user_ns['Out'] |
|
1281 | output_hist = self.user_ns['Out'] | |
1282 | n = len(input_hist) |
|
1282 | n = len(input_hist) | |
1283 | if index is None: |
|
1283 | if index is None: | |
1284 | start=0; stop=n |
|
1284 | start=0; stop=n | |
1285 | elif isinstance(index, int): |
|
1285 | elif isinstance(index, int): | |
1286 | start=n-index; stop=n |
|
1286 | start=n-index; stop=n | |
1287 | elif isinstance(index, tuple) and len(index) == 2: |
|
1287 | elif isinstance(index, tuple) and len(index) == 2: | |
1288 | start=index[0]; stop=index[1] |
|
1288 | start=index[0]; stop=index[1] | |
1289 | else: |
|
1289 | else: | |
1290 | raise IndexError('Not a valid index for the input history: %r' % index) |
|
1290 | raise IndexError('Not a valid index for the input history: %r' % index) | |
1291 | hist = {} |
|
1291 | hist = {} | |
1292 | for i in range(start, stop): |
|
1292 | for i in range(start, stop): | |
1293 | if output: |
|
1293 | if output: | |
1294 | hist[i] = (input_hist[i], output_hist.get(i)) |
|
1294 | hist[i] = (input_hist[i], output_hist.get(i)) | |
1295 | else: |
|
1295 | else: | |
1296 | hist[i] = input_hist[i] |
|
1296 | hist[i] = input_hist[i] | |
1297 | if len(hist)==0: |
|
1297 | if len(hist)==0: | |
1298 | raise IndexError('No history for range of indices: %r' % index) |
|
1298 | raise IndexError('No history for range of indices: %r' % index) | |
1299 | return hist |
|
1299 | return hist | |
1300 |
|
1300 | |||
1301 | #------------------------------------------------------------------------- |
|
1301 | #------------------------------------------------------------------------- | |
1302 | # Things related to exception handling and tracebacks (not debugging) |
|
1302 | # Things related to exception handling and tracebacks (not debugging) | |
1303 | #------------------------------------------------------------------------- |
|
1303 | #------------------------------------------------------------------------- | |
1304 |
|
1304 | |||
1305 | def init_traceback_handlers(self, custom_exceptions): |
|
1305 | def init_traceback_handlers(self, custom_exceptions): | |
1306 | # Syntax error handler. |
|
1306 | # Syntax error handler. | |
1307 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1307 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1308 |
|
1308 | |||
1309 | # The interactive one is initialized with an offset, meaning we always |
|
1309 | # The interactive one is initialized with an offset, meaning we always | |
1310 | # want to remove the topmost item in the traceback, which is our own |
|
1310 | # want to remove the topmost item in the traceback, which is our own | |
1311 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1311 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1312 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1312 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1313 | color_scheme='NoColor', |
|
1313 | color_scheme='NoColor', | |
1314 | tb_offset = 1) |
|
1314 | tb_offset = 1) | |
1315 |
|
1315 | |||
1316 | # The instance will store a pointer to the system-wide exception hook, |
|
1316 | # The instance will store a pointer to the system-wide exception hook, | |
1317 | # so that runtime code (such as magics) can access it. This is because |
|
1317 | # so that runtime code (such as magics) can access it. This is because | |
1318 | # during the read-eval loop, it may get temporarily overwritten. |
|
1318 | # during the read-eval loop, it may get temporarily overwritten. | |
1319 | self.sys_excepthook = sys.excepthook |
|
1319 | self.sys_excepthook = sys.excepthook | |
1320 |
|
1320 | |||
1321 | # and add any custom exception handlers the user may have specified |
|
1321 | # and add any custom exception handlers the user may have specified | |
1322 | self.set_custom_exc(*custom_exceptions) |
|
1322 | self.set_custom_exc(*custom_exceptions) | |
1323 |
|
1323 | |||
1324 | # Set the exception mode |
|
1324 | # Set the exception mode | |
1325 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1325 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1326 |
|
1326 | |||
1327 | def set_custom_exc(self, exc_tuple, handler): |
|
1327 | def set_custom_exc(self, exc_tuple, handler): | |
1328 | """set_custom_exc(exc_tuple,handler) |
|
1328 | """set_custom_exc(exc_tuple,handler) | |
1329 |
|
1329 | |||
1330 | Set a custom exception handler, which will be called if any of the |
|
1330 | Set a custom exception handler, which will be called if any of the | |
1331 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1331 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1332 | runcode() method. |
|
1332 | runcode() method. | |
1333 |
|
1333 | |||
1334 | Inputs: |
|
1334 | Inputs: | |
1335 |
|
1335 | |||
1336 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1336 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1337 | handler for. It is very important that you use a tuple, and NOT A |
|
1337 | handler for. It is very important that you use a tuple, and NOT A | |
1338 | LIST here, because of the way Python's except statement works. If |
|
1338 | LIST here, because of the way Python's except statement works. If | |
1339 | you only want to trap a single exception, use a singleton tuple: |
|
1339 | you only want to trap a single exception, use a singleton tuple: | |
1340 |
|
1340 | |||
1341 | exc_tuple == (MyCustomException,) |
|
1341 | exc_tuple == (MyCustomException,) | |
1342 |
|
1342 | |||
1343 | - handler: this must be defined as a function with the following |
|
1343 | - handler: this must be defined as a function with the following | |
1344 | basic interface:: |
|
1344 | basic interface:: | |
1345 |
|
1345 | |||
1346 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1346 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1347 | ... |
|
1347 | ... | |
1348 | # The return value must be |
|
1348 | # The return value must be | |
1349 | return structured_traceback |
|
1349 | return structured_traceback | |
1350 |
|
1350 | |||
1351 | This will be made into an instance method (via new.instancemethod) |
|
1351 | This will be made into an instance method (via new.instancemethod) | |
1352 | of IPython itself, and it will be called if any of the exceptions |
|
1352 | of IPython itself, and it will be called if any of the exceptions | |
1353 | listed in the exc_tuple are caught. If the handler is None, an |
|
1353 | listed in the exc_tuple are caught. If the handler is None, an | |
1354 | internal basic one is used, which just prints basic info. |
|
1354 | internal basic one is used, which just prints basic info. | |
1355 |
|
1355 | |||
1356 | WARNING: by putting in your own exception handler into IPython's main |
|
1356 | WARNING: by putting in your own exception handler into IPython's main | |
1357 | execution loop, you run a very good chance of nasty crashes. This |
|
1357 | execution loop, you run a very good chance of nasty crashes. This | |
1358 | facility should only be used if you really know what you are doing.""" |
|
1358 | facility should only be used if you really know what you are doing.""" | |
1359 |
|
1359 | |||
1360 | assert type(exc_tuple)==type(()) , \ |
|
1360 | assert type(exc_tuple)==type(()) , \ | |
1361 | "The custom exceptions must be given AS A TUPLE." |
|
1361 | "The custom exceptions must be given AS A TUPLE." | |
1362 |
|
1362 | |||
1363 | def dummy_handler(self,etype,value,tb): |
|
1363 | def dummy_handler(self,etype,value,tb): | |
1364 | print '*** Simple custom exception handler ***' |
|
1364 | print '*** Simple custom exception handler ***' | |
1365 | print 'Exception type :',etype |
|
1365 | print 'Exception type :',etype | |
1366 | print 'Exception value:',value |
|
1366 | print 'Exception value:',value | |
1367 | print 'Traceback :',tb |
|
1367 | print 'Traceback :',tb | |
1368 | print 'Source code :','\n'.join(self.buffer) |
|
1368 | print 'Source code :','\n'.join(self.buffer) | |
1369 |
|
1369 | |||
1370 | if handler is None: handler = dummy_handler |
|
1370 | if handler is None: handler = dummy_handler | |
1371 |
|
1371 | |||
1372 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1372 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1373 | self.custom_exceptions = exc_tuple |
|
1373 | self.custom_exceptions = exc_tuple | |
1374 |
|
1374 | |||
1375 | def excepthook(self, etype, value, tb): |
|
1375 | def excepthook(self, etype, value, tb): | |
1376 | """One more defense for GUI apps that call sys.excepthook. |
|
1376 | """One more defense for GUI apps that call sys.excepthook. | |
1377 |
|
1377 | |||
1378 | GUI frameworks like wxPython trap exceptions and call |
|
1378 | GUI frameworks like wxPython trap exceptions and call | |
1379 | sys.excepthook themselves. I guess this is a feature that |
|
1379 | sys.excepthook themselves. I guess this is a feature that | |
1380 | enables them to keep running after exceptions that would |
|
1380 | enables them to keep running after exceptions that would | |
1381 | otherwise kill their mainloop. This is a bother for IPython |
|
1381 | otherwise kill their mainloop. This is a bother for IPython | |
1382 | which excepts to catch all of the program exceptions with a try: |
|
1382 | which excepts to catch all of the program exceptions with a try: | |
1383 | except: statement. |
|
1383 | except: statement. | |
1384 |
|
1384 | |||
1385 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1385 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1386 | any app directly invokes sys.excepthook, it will look to the user like |
|
1386 | any app directly invokes sys.excepthook, it will look to the user like | |
1387 | IPython crashed. In order to work around this, we can disable the |
|
1387 | IPython crashed. In order to work around this, we can disable the | |
1388 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1388 | CrashHandler and replace it with this excepthook instead, which prints a | |
1389 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1389 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1390 | call sys.excepthook will generate a regular-looking exception from |
|
1390 | call sys.excepthook will generate a regular-looking exception from | |
1391 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1391 | IPython, and the CrashHandler will only be triggered by real IPython | |
1392 | crashes. |
|
1392 | crashes. | |
1393 |
|
1393 | |||
1394 | This hook should be used sparingly, only in places which are not likely |
|
1394 | This hook should be used sparingly, only in places which are not likely | |
1395 | to be true IPython errors. |
|
1395 | to be true IPython errors. | |
1396 | """ |
|
1396 | """ | |
1397 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1397 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1398 |
|
1398 | |||
1399 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1399 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1400 | exception_only=False): |
|
1400 | exception_only=False): | |
1401 | """Display the exception that just occurred. |
|
1401 | """Display the exception that just occurred. | |
1402 |
|
1402 | |||
1403 | If nothing is known about the exception, this is the method which |
|
1403 | If nothing is known about the exception, this is the method which | |
1404 | should be used throughout the code for presenting user tracebacks, |
|
1404 | should be used throughout the code for presenting user tracebacks, | |
1405 | rather than directly invoking the InteractiveTB object. |
|
1405 | rather than directly invoking the InteractiveTB object. | |
1406 |
|
1406 | |||
1407 | A specific showsyntaxerror() also exists, but this method can take |
|
1407 | A specific showsyntaxerror() also exists, but this method can take | |
1408 | care of calling it if needed, so unless you are explicitly catching a |
|
1408 | care of calling it if needed, so unless you are explicitly catching a | |
1409 | SyntaxError exception, don't try to analyze the stack manually and |
|
1409 | SyntaxError exception, don't try to analyze the stack manually and | |
1410 | simply call this method.""" |
|
1410 | simply call this method.""" | |
1411 |
|
1411 | |||
1412 | try: |
|
1412 | try: | |
1413 | if exc_tuple is None: |
|
1413 | if exc_tuple is None: | |
1414 | etype, value, tb = sys.exc_info() |
|
1414 | etype, value, tb = sys.exc_info() | |
1415 | else: |
|
1415 | else: | |
1416 | etype, value, tb = exc_tuple |
|
1416 | etype, value, tb = exc_tuple | |
1417 |
|
1417 | |||
1418 | if etype is None: |
|
1418 | if etype is None: | |
1419 | if hasattr(sys, 'last_type'): |
|
1419 | if hasattr(sys, 'last_type'): | |
1420 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1420 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1421 | sys.last_traceback |
|
1421 | sys.last_traceback | |
1422 | else: |
|
1422 | else: | |
1423 | self.write_err('No traceback available to show.\n') |
|
1423 | self.write_err('No traceback available to show.\n') | |
1424 | return |
|
1424 | return | |
1425 |
|
1425 | |||
1426 | if etype is SyntaxError: |
|
1426 | if etype is SyntaxError: | |
1427 | # Though this won't be called by syntax errors in the input |
|
1427 | # Though this won't be called by syntax errors in the input | |
1428 | # line, there may be SyntaxError cases whith imported code. |
|
1428 | # line, there may be SyntaxError cases whith imported code. | |
1429 | self.showsyntaxerror(filename) |
|
1429 | self.showsyntaxerror(filename) | |
1430 | elif etype is UsageError: |
|
1430 | elif etype is UsageError: | |
1431 | print "UsageError:", value |
|
1431 | print "UsageError:", value | |
1432 | else: |
|
1432 | else: | |
1433 | # WARNING: these variables are somewhat deprecated and not |
|
1433 | # WARNING: these variables are somewhat deprecated and not | |
1434 | # necessarily safe to use in a threaded environment, but tools |
|
1434 | # necessarily safe to use in a threaded environment, but tools | |
1435 | # like pdb depend on their existence, so let's set them. If we |
|
1435 | # like pdb depend on their existence, so let's set them. If we | |
1436 | # find problems in the field, we'll need to revisit their use. |
|
1436 | # find problems in the field, we'll need to revisit their use. | |
1437 | sys.last_type = etype |
|
1437 | sys.last_type = etype | |
1438 | sys.last_value = value |
|
1438 | sys.last_value = value | |
1439 | sys.last_traceback = tb |
|
1439 | sys.last_traceback = tb | |
1440 |
|
1440 | |||
1441 | if etype in self.custom_exceptions: |
|
1441 | if etype in self.custom_exceptions: | |
1442 | # FIXME: Old custom traceback objects may just return a |
|
1442 | # FIXME: Old custom traceback objects may just return a | |
1443 | # string, in that case we just put it into a list |
|
1443 | # string, in that case we just put it into a list | |
1444 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1444 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1445 | if isinstance(ctb, basestring): |
|
1445 | if isinstance(ctb, basestring): | |
1446 | stb = [stb] |
|
1446 | stb = [stb] | |
1447 | else: |
|
1447 | else: | |
1448 | if exception_only: |
|
1448 | if exception_only: | |
1449 | stb = ['An exception has occurred, use %tb to see ' |
|
1449 | stb = ['An exception has occurred, use %tb to see ' | |
1450 | 'the full traceback.\n'] |
|
1450 | 'the full traceback.\n'] | |
1451 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1451 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1452 | value)) |
|
1452 | value)) | |
1453 | else: |
|
1453 | else: | |
1454 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1454 | stb = self.InteractiveTB.structured_traceback(etype, | |
1455 | value, tb, tb_offset=tb_offset) |
|
1455 | value, tb, tb_offset=tb_offset) | |
1456 | # FIXME: the pdb calling should be done by us, not by |
|
1456 | # FIXME: the pdb calling should be done by us, not by | |
1457 | # the code computing the traceback. |
|
1457 | # the code computing the traceback. | |
1458 | if self.InteractiveTB.call_pdb: |
|
1458 | if self.InteractiveTB.call_pdb: | |
1459 | # pdb mucks up readline, fix it back |
|
1459 | # pdb mucks up readline, fix it back | |
1460 | self.set_completer() |
|
1460 | self.set_completer() | |
1461 |
|
1461 | |||
1462 | # Actually show the traceback |
|
1462 | # Actually show the traceback | |
1463 | self._showtraceback(etype, value, stb) |
|
1463 | self._showtraceback(etype, value, stb) | |
1464 |
|
1464 | |||
1465 | except KeyboardInterrupt: |
|
1465 | except KeyboardInterrupt: | |
1466 | self.write_err("\nKeyboardInterrupt\n") |
|
1466 | self.write_err("\nKeyboardInterrupt\n") | |
1467 |
|
1467 | |||
1468 | def _showtraceback(self, etype, evalue, stb): |
|
1468 | def _showtraceback(self, etype, evalue, stb): | |
1469 | """Actually show a traceback. |
|
1469 | """Actually show a traceback. | |
1470 |
|
1470 | |||
1471 | Subclasses may override this method to put the traceback on a different |
|
1471 | Subclasses may override this method to put the traceback on a different | |
1472 | place, like a side channel. |
|
1472 | place, like a side channel. | |
1473 | """ |
|
1473 | """ | |
1474 | # FIXME: this should use the proper write channels, but our test suite |
|
1474 | # FIXME: this should use the proper write channels, but our test suite | |
1475 | # relies on it coming out of stdout... |
|
1475 | # relies on it coming out of stdout... | |
1476 | print >> sys.stdout, self.InteractiveTB.stb2text(stb) |
|
1476 | print >> sys.stdout, self.InteractiveTB.stb2text(stb) | |
1477 |
|
1477 | |||
1478 | def showsyntaxerror(self, filename=None): |
|
1478 | def showsyntaxerror(self, filename=None): | |
1479 | """Display the syntax error that just occurred. |
|
1479 | """Display the syntax error that just occurred. | |
1480 |
|
1480 | |||
1481 | This doesn't display a stack trace because there isn't one. |
|
1481 | This doesn't display a stack trace because there isn't one. | |
1482 |
|
1482 | |||
1483 | If a filename is given, it is stuffed in the exception instead |
|
1483 | If a filename is given, it is stuffed in the exception instead | |
1484 | of what was there before (because Python's parser always uses |
|
1484 | of what was there before (because Python's parser always uses | |
1485 | "<string>" when reading from a string). |
|
1485 | "<string>" when reading from a string). | |
1486 | """ |
|
1486 | """ | |
1487 | etype, value, last_traceback = sys.exc_info() |
|
1487 | etype, value, last_traceback = sys.exc_info() | |
1488 |
|
1488 | |||
1489 | # See note about these variables in showtraceback() above |
|
1489 | # See note about these variables in showtraceback() above | |
1490 | sys.last_type = etype |
|
1490 | sys.last_type = etype | |
1491 | sys.last_value = value |
|
1491 | sys.last_value = value | |
1492 | sys.last_traceback = last_traceback |
|
1492 | sys.last_traceback = last_traceback | |
1493 |
|
1493 | |||
1494 | if filename and etype is SyntaxError: |
|
1494 | if filename and etype is SyntaxError: | |
1495 | # Work hard to stuff the correct filename in the exception |
|
1495 | # Work hard to stuff the correct filename in the exception | |
1496 | try: |
|
1496 | try: | |
1497 | msg, (dummy_filename, lineno, offset, line) = value |
|
1497 | msg, (dummy_filename, lineno, offset, line) = value | |
1498 | except: |
|
1498 | except: | |
1499 | # Not the format we expect; leave it alone |
|
1499 | # Not the format we expect; leave it alone | |
1500 | pass |
|
1500 | pass | |
1501 | else: |
|
1501 | else: | |
1502 | # Stuff in the right filename |
|
1502 | # Stuff in the right filename | |
1503 | try: |
|
1503 | try: | |
1504 | # Assume SyntaxError is a class exception |
|
1504 | # Assume SyntaxError is a class exception | |
1505 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1505 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1506 | except: |
|
1506 | except: | |
1507 | # If that failed, assume SyntaxError is a string |
|
1507 | # If that failed, assume SyntaxError is a string | |
1508 | value = msg, (filename, lineno, offset, line) |
|
1508 | value = msg, (filename, lineno, offset, line) | |
1509 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1509 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1510 | self._showtraceback(etype, value, stb) |
|
1510 | self._showtraceback(etype, value, stb) | |
1511 |
|
1511 | |||
1512 | #------------------------------------------------------------------------- |
|
1512 | #------------------------------------------------------------------------- | |
1513 | # Things related to tab completion |
|
1513 | # Things related to tab completion | |
1514 | #------------------------------------------------------------------------- |
|
1514 | #------------------------------------------------------------------------- | |
1515 |
|
1515 | |||
1516 | def complete(self, text, line=None, cursor_pos=None): |
|
1516 | def complete(self, text, line=None, cursor_pos=None): | |
1517 | """Return the completed text and a list of completions. |
|
1517 | """Return the completed text and a list of completions. | |
1518 |
|
1518 | |||
1519 | Parameters |
|
1519 | Parameters | |
1520 | ---------- |
|
1520 | ---------- | |
1521 |
|
1521 | |||
1522 | text : string |
|
1522 | text : string | |
1523 | A string of text to be completed on. It can be given as empty and |
|
1523 | A string of text to be completed on. It can be given as empty and | |
1524 | instead a line/position pair are given. In this case, the |
|
1524 | instead a line/position pair are given. In this case, the | |
1525 | completer itself will split the line like readline does. |
|
1525 | completer itself will split the line like readline does. | |
1526 |
|
1526 | |||
1527 | line : string, optional |
|
1527 | line : string, optional | |
1528 | The complete line that text is part of. |
|
1528 | The complete line that text is part of. | |
1529 |
|
1529 | |||
1530 | cursor_pos : int, optional |
|
1530 | cursor_pos : int, optional | |
1531 | The position of the cursor on the input line. |
|
1531 | The position of the cursor on the input line. | |
1532 |
|
1532 | |||
1533 | Returns |
|
1533 | Returns | |
1534 | ------- |
|
1534 | ------- | |
1535 | text : string |
|
1535 | text : string | |
1536 | The actual text that was completed. |
|
1536 | The actual text that was completed. | |
1537 |
|
1537 | |||
1538 | matches : list |
|
1538 | matches : list | |
1539 | A sorted list with all possible completions. |
|
1539 | A sorted list with all possible completions. | |
1540 |
|
1540 | |||
1541 | The optional arguments allow the completion to take more context into |
|
1541 | The optional arguments allow the completion to take more context into | |
1542 | account, and are part of the low-level completion API. |
|
1542 | account, and are part of the low-level completion API. | |
1543 |
|
1543 | |||
1544 | This is a wrapper around the completion mechanism, similar to what |
|
1544 | This is a wrapper around the completion mechanism, similar to what | |
1545 | readline does at the command line when the TAB key is hit. By |
|
1545 | readline does at the command line when the TAB key is hit. By | |
1546 | exposing it as a method, it can be used by other non-readline |
|
1546 | exposing it as a method, it can be used by other non-readline | |
1547 | environments (such as GUIs) for text completion. |
|
1547 | environments (such as GUIs) for text completion. | |
1548 |
|
1548 | |||
1549 | Simple usage example: |
|
1549 | Simple usage example: | |
1550 |
|
1550 | |||
1551 | In [1]: x = 'hello' |
|
1551 | In [1]: x = 'hello' | |
1552 |
|
1552 | |||
1553 | In [2]: _ip.complete('x.l') |
|
1553 | In [2]: _ip.complete('x.l') | |
1554 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1554 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1555 | """ |
|
1555 | """ | |
1556 |
|
1556 | |||
1557 | # Inject names into __builtin__ so we can complete on the added names. |
|
1557 | # Inject names into __builtin__ so we can complete on the added names. | |
1558 | with self.builtin_trap: |
|
1558 | with self.builtin_trap: | |
1559 | return self.Completer.complete(text, line, cursor_pos) |
|
1559 | return self.Completer.complete(text, line, cursor_pos) | |
1560 |
|
1560 | |||
1561 | def set_custom_completer(self, completer, pos=0): |
|
1561 | def set_custom_completer(self, completer, pos=0): | |
1562 | """Adds a new custom completer function. |
|
1562 | """Adds a new custom completer function. | |
1563 |
|
1563 | |||
1564 | The position argument (defaults to 0) is the index in the completers |
|
1564 | The position argument (defaults to 0) is the index in the completers | |
1565 | list where you want the completer to be inserted.""" |
|
1565 | list where you want the completer to be inserted.""" | |
1566 |
|
1566 | |||
1567 | newcomp = new.instancemethod(completer,self.Completer, |
|
1567 | newcomp = new.instancemethod(completer,self.Completer, | |
1568 | self.Completer.__class__) |
|
1568 | self.Completer.__class__) | |
1569 | self.Completer.matchers.insert(pos,newcomp) |
|
1569 | self.Completer.matchers.insert(pos,newcomp) | |
1570 |
|
1570 | |||
1571 | def set_completer(self): |
|
1571 | def set_completer(self): | |
1572 | """Reset readline's completer to be our own.""" |
|
1572 | """Reset readline's completer to be our own.""" | |
1573 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1573 | self.readline.set_completer(self.Completer.rlcomplete) | |
1574 |
|
1574 | |||
1575 | def set_completer_frame(self, frame=None): |
|
1575 | def set_completer_frame(self, frame=None): | |
1576 | """Set the frame of the completer.""" |
|
1576 | """Set the frame of the completer.""" | |
1577 | if frame: |
|
1577 | if frame: | |
1578 | self.Completer.namespace = frame.f_locals |
|
1578 | self.Completer.namespace = frame.f_locals | |
1579 | self.Completer.global_namespace = frame.f_globals |
|
1579 | self.Completer.global_namespace = frame.f_globals | |
1580 | else: |
|
1580 | else: | |
1581 | self.Completer.namespace = self.user_ns |
|
1581 | self.Completer.namespace = self.user_ns | |
1582 | self.Completer.global_namespace = self.user_global_ns |
|
1582 | self.Completer.global_namespace = self.user_global_ns | |
1583 |
|
1583 | |||
1584 | #------------------------------------------------------------------------- |
|
1584 | #------------------------------------------------------------------------- | |
1585 | # Things related to readline |
|
1585 | # Things related to readline | |
1586 | #------------------------------------------------------------------------- |
|
1586 | #------------------------------------------------------------------------- | |
1587 |
|
1587 | |||
1588 | def init_readline(self): |
|
1588 | def init_readline(self): | |
1589 | """Command history completion/saving/reloading.""" |
|
1589 | """Command history completion/saving/reloading.""" | |
1590 |
|
1590 | |||
1591 | if self.readline_use: |
|
1591 | if self.readline_use: | |
1592 | import IPython.utils.rlineimpl as readline |
|
1592 | import IPython.utils.rlineimpl as readline | |
1593 |
|
1593 | |||
1594 | self.rl_next_input = None |
|
1594 | self.rl_next_input = None | |
1595 | self.rl_do_indent = False |
|
1595 | self.rl_do_indent = False | |
1596 |
|
1596 | |||
1597 | if not self.readline_use or not readline.have_readline: |
|
1597 | if not self.readline_use or not readline.have_readline: | |
1598 | self.has_readline = False |
|
1598 | self.has_readline = False | |
1599 | self.readline = None |
|
1599 | self.readline = None | |
1600 | # Set a number of methods that depend on readline to be no-op |
|
1600 | # Set a number of methods that depend on readline to be no-op | |
1601 | self.savehist = no_op |
|
1601 | self.savehist = no_op | |
1602 | self.reloadhist = no_op |
|
1602 | self.reloadhist = no_op | |
1603 | self.set_completer = no_op |
|
1603 | self.set_completer = no_op | |
1604 | self.set_custom_completer = no_op |
|
1604 | self.set_custom_completer = no_op | |
1605 | self.set_completer_frame = no_op |
|
1605 | self.set_completer_frame = no_op | |
1606 | warn('Readline services not available or not loaded.') |
|
1606 | warn('Readline services not available or not loaded.') | |
1607 | else: |
|
1607 | else: | |
1608 | self.has_readline = True |
|
1608 | self.has_readline = True | |
1609 | self.readline = readline |
|
1609 | self.readline = readline | |
1610 | sys.modules['readline'] = readline |
|
1610 | sys.modules['readline'] = readline | |
1611 | import atexit |
|
1611 | import atexit | |
1612 | from IPython.core.completer import IPCompleter |
|
1612 | from IPython.core.completer import IPCompleter | |
1613 | self.Completer = IPCompleter(self, |
|
1613 | self.Completer = IPCompleter(self, | |
1614 | self.user_ns, |
|
1614 | self.user_ns, | |
1615 | self.user_global_ns, |
|
1615 | self.user_global_ns, | |
1616 | self.readline_omit__names, |
|
1616 | self.readline_omit__names, | |
1617 | self.alias_manager.alias_table) |
|
1617 | self.alias_manager.alias_table) | |
1618 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1618 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1619 | self.strdispatchers['complete_command'] = sdisp |
|
1619 | self.strdispatchers['complete_command'] = sdisp | |
1620 | self.Completer.custom_completers = sdisp |
|
1620 | self.Completer.custom_completers = sdisp | |
1621 | # Platform-specific configuration |
|
1621 | # Platform-specific configuration | |
1622 | if os.name == 'nt': |
|
1622 | if os.name == 'nt': | |
1623 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1623 | self.readline_startup_hook = readline.set_pre_input_hook | |
1624 | else: |
|
1624 | else: | |
1625 | self.readline_startup_hook = readline.set_startup_hook |
|
1625 | self.readline_startup_hook = readline.set_startup_hook | |
1626 |
|
1626 | |||
1627 | # Load user's initrc file (readline config) |
|
1627 | # Load user's initrc file (readline config) | |
1628 | # Or if libedit is used, load editrc. |
|
1628 | # Or if libedit is used, load editrc. | |
1629 | inputrc_name = os.environ.get('INPUTRC') |
|
1629 | inputrc_name = os.environ.get('INPUTRC') | |
1630 | if inputrc_name is None: |
|
1630 | if inputrc_name is None: | |
1631 | home_dir = get_home_dir() |
|
1631 | home_dir = get_home_dir() | |
1632 | if home_dir is not None: |
|
1632 | if home_dir is not None: | |
1633 | inputrc_name = '.inputrc' |
|
1633 | inputrc_name = '.inputrc' | |
1634 | if readline.uses_libedit: |
|
1634 | if readline.uses_libedit: | |
1635 | inputrc_name = '.editrc' |
|
1635 | inputrc_name = '.editrc' | |
1636 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1636 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1637 | if os.path.isfile(inputrc_name): |
|
1637 | if os.path.isfile(inputrc_name): | |
1638 | try: |
|
1638 | try: | |
1639 | readline.read_init_file(inputrc_name) |
|
1639 | readline.read_init_file(inputrc_name) | |
1640 | except: |
|
1640 | except: | |
1641 | warn('Problems reading readline initialization file <%s>' |
|
1641 | warn('Problems reading readline initialization file <%s>' | |
1642 | % inputrc_name) |
|
1642 | % inputrc_name) | |
1643 |
|
1643 | |||
1644 | # save this in sys so embedded copies can restore it properly |
|
1644 | # save this in sys so embedded copies can restore it properly | |
1645 | sys.ipcompleter = self.Completer.rlcomplete |
|
1645 | sys.ipcompleter = self.Completer.rlcomplete | |
1646 | self.set_completer() |
|
1646 | self.set_completer() | |
1647 |
|
1647 | |||
1648 | # Configure readline according to user's prefs |
|
1648 | # Configure readline according to user's prefs | |
1649 | # This is only done if GNU readline is being used. If libedit |
|
1649 | # This is only done if GNU readline is being used. If libedit | |
1650 | # is being used (as on Leopard) the readline config is |
|
1650 | # is being used (as on Leopard) the readline config is | |
1651 | # not run as the syntax for libedit is different. |
|
1651 | # not run as the syntax for libedit is different. | |
1652 | if not readline.uses_libedit: |
|
1652 | if not readline.uses_libedit: | |
1653 | for rlcommand in self.readline_parse_and_bind: |
|
1653 | for rlcommand in self.readline_parse_and_bind: | |
1654 | #print "loading rl:",rlcommand # dbg |
|
1654 | #print "loading rl:",rlcommand # dbg | |
1655 | readline.parse_and_bind(rlcommand) |
|
1655 | readline.parse_and_bind(rlcommand) | |
1656 |
|
1656 | |||
1657 | # Remove some chars from the delimiters list. If we encounter |
|
1657 | # Remove some chars from the delimiters list. If we encounter | |
1658 | # unicode chars, discard them. |
|
1658 | # unicode chars, discard them. | |
1659 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1659 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1660 | delims = delims.translate(string._idmap, |
|
1660 | delims = delims.translate(string._idmap, | |
1661 | self.readline_remove_delims) |
|
1661 | self.readline_remove_delims) | |
1662 | readline.set_completer_delims(delims) |
|
1662 | readline.set_completer_delims(delims) | |
1663 | # otherwise we end up with a monster history after a while: |
|
1663 | # otherwise we end up with a monster history after a while: | |
1664 | readline.set_history_length(1000) |
|
1664 | readline.set_history_length(1000) | |
1665 | try: |
|
1665 | try: | |
1666 | #print '*** Reading readline history' # dbg |
|
1666 | #print '*** Reading readline history' # dbg | |
1667 | readline.read_history_file(self.histfile) |
|
1667 | readline.read_history_file(self.histfile) | |
1668 | except IOError: |
|
1668 | except IOError: | |
1669 | pass # It doesn't exist yet. |
|
1669 | pass # It doesn't exist yet. | |
1670 |
|
1670 | |||
1671 | atexit.register(self.atexit_operations) |
|
1671 | atexit.register(self.atexit_operations) | |
1672 | del atexit |
|
1672 | del atexit | |
1673 |
|
1673 | |||
1674 | # Configure auto-indent for all platforms |
|
1674 | # Configure auto-indent for all platforms | |
1675 | self.set_autoindent(self.autoindent) |
|
1675 | self.set_autoindent(self.autoindent) | |
1676 |
|
1676 | |||
1677 | def set_next_input(self, s): |
|
1677 | def set_next_input(self, s): | |
1678 | """ Sets the 'default' input string for the next command line. |
|
1678 | """ Sets the 'default' input string for the next command line. | |
1679 |
|
1679 | |||
1680 | Requires readline. |
|
1680 | Requires readline. | |
1681 |
|
1681 | |||
1682 | Example: |
|
1682 | Example: | |
1683 |
|
1683 | |||
1684 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1684 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1685 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1685 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1686 | """ |
|
1686 | """ | |
1687 |
|
1687 | |||
1688 | self.rl_next_input = s |
|
1688 | self.rl_next_input = s | |
1689 |
|
1689 | |||
1690 | # Maybe move this to the terminal subclass? |
|
1690 | # Maybe move this to the terminal subclass? | |
1691 | def pre_readline(self): |
|
1691 | def pre_readline(self): | |
1692 | """readline hook to be used at the start of each line. |
|
1692 | """readline hook to be used at the start of each line. | |
1693 |
|
1693 | |||
1694 | Currently it handles auto-indent only.""" |
|
1694 | Currently it handles auto-indent only.""" | |
1695 |
|
1695 | |||
1696 | if self.rl_do_indent: |
|
1696 | if self.rl_do_indent: | |
1697 | self.readline.insert_text(self._indent_current_str()) |
|
1697 | self.readline.insert_text(self._indent_current_str()) | |
1698 | if self.rl_next_input is not None: |
|
1698 | if self.rl_next_input is not None: | |
1699 | self.readline.insert_text(self.rl_next_input) |
|
1699 | self.readline.insert_text(self.rl_next_input) | |
1700 | self.rl_next_input = None |
|
1700 | self.rl_next_input = None | |
1701 |
|
1701 | |||
1702 | def _indent_current_str(self): |
|
1702 | def _indent_current_str(self): | |
1703 | """return the current level of indentation as a string""" |
|
1703 | """return the current level of indentation as a string""" | |
1704 | return self.indent_current_nsp * ' ' |
|
1704 | return self.indent_current_nsp * ' ' | |
1705 |
|
1705 | |||
1706 | #------------------------------------------------------------------------- |
|
1706 | #------------------------------------------------------------------------- | |
1707 | # Things related to magics |
|
1707 | # Things related to magics | |
1708 | #------------------------------------------------------------------------- |
|
1708 | #------------------------------------------------------------------------- | |
1709 |
|
1709 | |||
1710 | def init_magics(self): |
|
1710 | def init_magics(self): | |
1711 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1711 | # FIXME: Move the color initialization to the DisplayHook, which | |
1712 | # should be split into a prompt manager and displayhook. We probably |
|
1712 | # should be split into a prompt manager and displayhook. We probably | |
1713 | # even need a centralize colors management object. |
|
1713 | # even need a centralize colors management object. | |
1714 | self.magic_colors(self.colors) |
|
1714 | self.magic_colors(self.colors) | |
1715 | # History was moved to a separate module |
|
1715 | # History was moved to a separate module | |
1716 | from . import history |
|
1716 | from . import history | |
1717 | history.init_ipython(self) |
|
1717 | history.init_ipython(self) | |
1718 |
|
1718 | |||
1719 | def magic(self,arg_s): |
|
1719 | def magic(self,arg_s): | |
1720 | """Call a magic function by name. |
|
1720 | """Call a magic function by name. | |
1721 |
|
1721 | |||
1722 | Input: a string containing the name of the magic function to call and any |
|
1722 | Input: a string containing the name of the magic function to call and any | |
1723 | additional arguments to be passed to the magic. |
|
1723 | additional arguments to be passed to the magic. | |
1724 |
|
1724 | |||
1725 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1725 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1726 | prompt: |
|
1726 | prompt: | |
1727 |
|
1727 | |||
1728 | In[1]: %name -opt foo bar |
|
1728 | In[1]: %name -opt foo bar | |
1729 |
|
1729 | |||
1730 | To call a magic without arguments, simply use magic('name'). |
|
1730 | To call a magic without arguments, simply use magic('name'). | |
1731 |
|
1731 | |||
1732 | This provides a proper Python function to call IPython's magics in any |
|
1732 | This provides a proper Python function to call IPython's magics in any | |
1733 | valid Python code you can type at the interpreter, including loops and |
|
1733 | valid Python code you can type at the interpreter, including loops and | |
1734 | compound statements. |
|
1734 | compound statements. | |
1735 | """ |
|
1735 | """ | |
1736 | args = arg_s.split(' ',1) |
|
1736 | args = arg_s.split(' ',1) | |
1737 | magic_name = args[0] |
|
1737 | magic_name = args[0] | |
1738 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1738 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1739 |
|
1739 | |||
1740 | try: |
|
1740 | try: | |
1741 | magic_args = args[1] |
|
1741 | magic_args = args[1] | |
1742 | except IndexError: |
|
1742 | except IndexError: | |
1743 | magic_args = '' |
|
1743 | magic_args = '' | |
1744 | fn = getattr(self,'magic_'+magic_name,None) |
|
1744 | fn = getattr(self,'magic_'+magic_name,None) | |
1745 | if fn is None: |
|
1745 | if fn is None: | |
1746 | error("Magic function `%s` not found." % magic_name) |
|
1746 | error("Magic function `%s` not found." % magic_name) | |
1747 | else: |
|
1747 | else: | |
1748 | magic_args = self.var_expand(magic_args,1) |
|
1748 | magic_args = self.var_expand(magic_args,1) | |
1749 | with nested(self.builtin_trap,): |
|
1749 | with nested(self.builtin_trap,): | |
1750 | result = fn(magic_args) |
|
1750 | result = fn(magic_args) | |
1751 | return result |
|
1751 | return result | |
1752 |
|
1752 | |||
1753 | def define_magic(self, magicname, func): |
|
1753 | def define_magic(self, magicname, func): | |
1754 | """Expose own function as magic function for ipython |
|
1754 | """Expose own function as magic function for ipython | |
1755 |
|
1755 | |||
1756 | def foo_impl(self,parameter_s=''): |
|
1756 | def foo_impl(self,parameter_s=''): | |
1757 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1757 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1758 | print 'Magic function. Passed parameter is between < >:' |
|
1758 | print 'Magic function. Passed parameter is between < >:' | |
1759 | print '<%s>' % parameter_s |
|
1759 | print '<%s>' % parameter_s | |
1760 | print 'The self object is:',self |
|
1760 | print 'The self object is:',self | |
1761 |
|
1761 | |||
1762 | self.define_magic('foo',foo_impl) |
|
1762 | self.define_magic('foo',foo_impl) | |
1763 | """ |
|
1763 | """ | |
1764 |
|
1764 | |||
1765 | import new |
|
1765 | import new | |
1766 | im = new.instancemethod(func,self, self.__class__) |
|
1766 | im = new.instancemethod(func,self, self.__class__) | |
1767 | old = getattr(self, "magic_" + magicname, None) |
|
1767 | old = getattr(self, "magic_" + magicname, None) | |
1768 | setattr(self, "magic_" + magicname, im) |
|
1768 | setattr(self, "magic_" + magicname, im) | |
1769 | return old |
|
1769 | return old | |
1770 |
|
1770 | |||
1771 | #------------------------------------------------------------------------- |
|
1771 | #------------------------------------------------------------------------- | |
1772 | # Things related to macros |
|
1772 | # Things related to macros | |
1773 | #------------------------------------------------------------------------- |
|
1773 | #------------------------------------------------------------------------- | |
1774 |
|
1774 | |||
1775 | def define_macro(self, name, themacro): |
|
1775 | def define_macro(self, name, themacro): | |
1776 | """Define a new macro |
|
1776 | """Define a new macro | |
1777 |
|
1777 | |||
1778 | Parameters |
|
1778 | Parameters | |
1779 | ---------- |
|
1779 | ---------- | |
1780 | name : str |
|
1780 | name : str | |
1781 | The name of the macro. |
|
1781 | The name of the macro. | |
1782 | themacro : str or Macro |
|
1782 | themacro : str or Macro | |
1783 | The action to do upon invoking the macro. If a string, a new |
|
1783 | The action to do upon invoking the macro. If a string, a new | |
1784 | Macro object is created by passing the string to it. |
|
1784 | Macro object is created by passing the string to it. | |
1785 | """ |
|
1785 | """ | |
1786 |
|
1786 | |||
1787 | from IPython.core import macro |
|
1787 | from IPython.core import macro | |
1788 |
|
1788 | |||
1789 | if isinstance(themacro, basestring): |
|
1789 | if isinstance(themacro, basestring): | |
1790 | themacro = macro.Macro(themacro) |
|
1790 | themacro = macro.Macro(themacro) | |
1791 | if not isinstance(themacro, macro.Macro): |
|
1791 | if not isinstance(themacro, macro.Macro): | |
1792 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1792 | raise ValueError('A macro must be a string or a Macro instance.') | |
1793 | self.user_ns[name] = themacro |
|
1793 | self.user_ns[name] = themacro | |
1794 |
|
1794 | |||
1795 | #------------------------------------------------------------------------- |
|
1795 | #------------------------------------------------------------------------- | |
1796 | # Things related to the running of system commands |
|
1796 | # Things related to the running of system commands | |
1797 | #------------------------------------------------------------------------- |
|
1797 | #------------------------------------------------------------------------- | |
1798 |
|
1798 | |||
1799 | def system(self, cmd): |
|
1799 | def system(self, cmd): | |
1800 | """Call the given cmd in a subprocess.""" |
|
1800 | """Call the given cmd in a subprocess.""" | |
1801 | # We do not support backgrounding processes because we either use |
|
1801 | # We do not support backgrounding processes because we either use | |
1802 | # pexpect or pipes to read from. Users can always just call |
|
1802 | # pexpect or pipes to read from. Users can always just call | |
1803 | # os.system() if they really want a background process. |
|
1803 | # os.system() if they really want a background process. | |
1804 | if cmd.endswith('&'): |
|
1804 | if cmd.endswith('&'): | |
1805 | raise OSError("Background processes not supported.") |
|
1805 | raise OSError("Background processes not supported.") | |
1806 |
|
1806 | |||
1807 | return system(self.var_expand(cmd, depth=2)) |
|
1807 | return system(self.var_expand(cmd, depth=2)) | |
1808 |
|
1808 | |||
1809 | def getoutput(self, cmd): |
|
1809 | def getoutput(self, cmd): | |
1810 | """Get output (possibly including stderr) from a subprocess.""" |
|
1810 | """Get output (possibly including stderr) from a subprocess.""" | |
1811 | if cmd.endswith('&'): |
|
1811 | if cmd.endswith('&'): | |
1812 | raise OSError("Background processes not supported.") |
|
1812 | raise OSError("Background processes not supported.") | |
1813 | return getoutput(self.var_expand(cmd, depth=2)) |
|
1813 | return getoutput(self.var_expand(cmd, depth=2)) | |
1814 |
|
1814 | |||
1815 | #------------------------------------------------------------------------- |
|
1815 | #------------------------------------------------------------------------- | |
1816 | # Things related to aliases |
|
1816 | # Things related to aliases | |
1817 | #------------------------------------------------------------------------- |
|
1817 | #------------------------------------------------------------------------- | |
1818 |
|
1818 | |||
1819 | def init_alias(self): |
|
1819 | def init_alias(self): | |
1820 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1820 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1821 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1821 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1822 |
|
1822 | |||
1823 | #------------------------------------------------------------------------- |
|
1823 | #------------------------------------------------------------------------- | |
1824 | # Things related to extensions and plugins |
|
1824 | # Things related to extensions and plugins | |
1825 | #------------------------------------------------------------------------- |
|
1825 | #------------------------------------------------------------------------- | |
1826 |
|
1826 | |||
1827 | def init_extension_manager(self): |
|
1827 | def init_extension_manager(self): | |
1828 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1828 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1829 |
|
1829 | |||
1830 | def init_plugin_manager(self): |
|
1830 | def init_plugin_manager(self): | |
1831 | self.plugin_manager = PluginManager(config=self.config) |
|
1831 | self.plugin_manager = PluginManager(config=self.config) | |
1832 |
|
1832 | |||
1833 | #------------------------------------------------------------------------- |
|
1833 | #------------------------------------------------------------------------- | |
1834 | # Things related to payloads |
|
1834 | # Things related to payloads | |
1835 | #------------------------------------------------------------------------- |
|
1835 | #------------------------------------------------------------------------- | |
1836 |
|
1836 | |||
1837 | def init_payload(self): |
|
1837 | def init_payload(self): | |
1838 | self.payload_manager = PayloadManager(config=self.config) |
|
1838 | self.payload_manager = PayloadManager(config=self.config) | |
1839 |
|
1839 | |||
1840 | #------------------------------------------------------------------------- |
|
1840 | #------------------------------------------------------------------------- | |
1841 | # Things related to the prefilter |
|
1841 | # Things related to the prefilter | |
1842 | #------------------------------------------------------------------------- |
|
1842 | #------------------------------------------------------------------------- | |
1843 |
|
1843 | |||
1844 | def init_prefilter(self): |
|
1844 | def init_prefilter(self): | |
1845 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1845 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1846 | # Ultimately this will be refactored in the new interpreter code, but |
|
1846 | # Ultimately this will be refactored in the new interpreter code, but | |
1847 | # for now, we should expose the main prefilter method (there's legacy |
|
1847 | # for now, we should expose the main prefilter method (there's legacy | |
1848 | # code out there that may rely on this). |
|
1848 | # code out there that may rely on this). | |
1849 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1849 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1850 |
|
1850 | |||
1851 | #------------------------------------------------------------------------- |
|
1851 | #------------------------------------------------------------------------- | |
1852 | # Things related to extracting values/expressions from kernel and user_ns |
|
1852 | # Things related to extracting values/expressions from kernel and user_ns | |
1853 | #------------------------------------------------------------------------- |
|
1853 | #------------------------------------------------------------------------- | |
1854 |
|
1854 | |||
1855 | def _simple_error(self): |
|
1855 | def _simple_error(self): | |
1856 | etype, value = sys.exc_info()[:2] |
|
1856 | etype, value = sys.exc_info()[:2] | |
1857 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1857 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1858 |
|
1858 | |||
1859 | def get_user_variables(self, names): |
|
1859 | def get_user_variables(self, names): | |
1860 | """Get a list of variable names from the user's namespace. |
|
1860 | """Get a list of variable names from the user's namespace. | |
1861 |
|
1861 | |||
1862 | The return value is a dict with the repr() of each value. |
|
1862 | The return value is a dict with the repr() of each value. | |
1863 | """ |
|
1863 | """ | |
1864 | out = {} |
|
1864 | out = {} | |
1865 | user_ns = self.user_ns |
|
1865 | user_ns = self.user_ns | |
1866 | for varname in names: |
|
1866 | for varname in names: | |
1867 | try: |
|
1867 | try: | |
1868 | value = repr(user_ns[varname]) |
|
1868 | value = repr(user_ns[varname]) | |
1869 | except: |
|
1869 | except: | |
1870 | value = self._simple_error() |
|
1870 | value = self._simple_error() | |
1871 | out[varname] = value |
|
1871 | out[varname] = value | |
1872 | return out |
|
1872 | return out | |
1873 |
|
1873 | |||
1874 | def eval_expressions(self, expressions): |
|
1874 | def eval_expressions(self, expressions): | |
1875 | """Evaluate a dict of expressions in the user's namespace. |
|
1875 | """Evaluate a dict of expressions in the user's namespace. | |
1876 |
|
1876 | |||
1877 | The return value is a dict with the repr() of each value. |
|
1877 | The return value is a dict with the repr() of each value. | |
1878 | """ |
|
1878 | """ | |
1879 | out = {} |
|
1879 | out = {} | |
1880 | user_ns = self.user_ns |
|
1880 | user_ns = self.user_ns | |
1881 | global_ns = self.user_global_ns |
|
1881 | global_ns = self.user_global_ns | |
1882 | for key, expr in expressions.iteritems(): |
|
1882 | for key, expr in expressions.iteritems(): | |
1883 | try: |
|
1883 | try: | |
1884 | value = repr(eval(expr, global_ns, user_ns)) |
|
1884 | value = repr(eval(expr, global_ns, user_ns)) | |
1885 | except: |
|
1885 | except: | |
1886 | value = self._simple_error() |
|
1886 | value = self._simple_error() | |
1887 | out[key] = value |
|
1887 | out[key] = value | |
1888 | return out |
|
1888 | return out | |
1889 |
|
1889 | |||
1890 | #------------------------------------------------------------------------- |
|
1890 | #------------------------------------------------------------------------- | |
1891 | # Things related to the running of code |
|
1891 | # Things related to the running of code | |
1892 | #------------------------------------------------------------------------- |
|
1892 | #------------------------------------------------------------------------- | |
1893 |
|
1893 | |||
1894 | def ex(self, cmd): |
|
1894 | def ex(self, cmd): | |
1895 | """Execute a normal python statement in user namespace.""" |
|
1895 | """Execute a normal python statement in user namespace.""" | |
1896 | with nested(self.builtin_trap,): |
|
1896 | with nested(self.builtin_trap,): | |
1897 | exec cmd in self.user_global_ns, self.user_ns |
|
1897 | exec cmd in self.user_global_ns, self.user_ns | |
1898 |
|
1898 | |||
1899 | def ev(self, expr): |
|
1899 | def ev(self, expr): | |
1900 | """Evaluate python expression expr in user namespace. |
|
1900 | """Evaluate python expression expr in user namespace. | |
1901 |
|
1901 | |||
1902 | Returns the result of evaluation |
|
1902 | Returns the result of evaluation | |
1903 | """ |
|
1903 | """ | |
1904 | with nested(self.builtin_trap,): |
|
1904 | with nested(self.builtin_trap,): | |
1905 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1905 | return eval(expr, self.user_global_ns, self.user_ns) | |
1906 |
|
1906 | |||
1907 | def safe_execfile(self, fname, *where, **kw): |
|
1907 | def safe_execfile(self, fname, *where, **kw): | |
1908 | """A safe version of the builtin execfile(). |
|
1908 | """A safe version of the builtin execfile(). | |
1909 |
|
1909 | |||
1910 | This version will never throw an exception, but instead print |
|
1910 | This version will never throw an exception, but instead print | |
1911 | helpful error messages to the screen. This only works on pure |
|
1911 | helpful error messages to the screen. This only works on pure | |
1912 | Python files with the .py extension. |
|
1912 | Python files with the .py extension. | |
1913 |
|
1913 | |||
1914 | Parameters |
|
1914 | Parameters | |
1915 | ---------- |
|
1915 | ---------- | |
1916 | fname : string |
|
1916 | fname : string | |
1917 | The name of the file to be executed. |
|
1917 | The name of the file to be executed. | |
1918 | where : tuple |
|
1918 | where : tuple | |
1919 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1919 | One or two namespaces, passed to execfile() as (globals,locals). | |
1920 | If only one is given, it is passed as both. |
|
1920 | If only one is given, it is passed as both. | |
1921 | exit_ignore : bool (False) |
|
1921 | exit_ignore : bool (False) | |
1922 | If True, then silence SystemExit for non-zero status (it is always |
|
1922 | If True, then silence SystemExit for non-zero status (it is always | |
1923 | silenced for zero status, as it is so common). |
|
1923 | silenced for zero status, as it is so common). | |
1924 | """ |
|
1924 | """ | |
1925 | kw.setdefault('exit_ignore', False) |
|
1925 | kw.setdefault('exit_ignore', False) | |
1926 |
|
1926 | |||
1927 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1927 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1928 |
|
1928 | |||
1929 | # Make sure we have a .py file |
|
1929 | # Make sure we have a .py file | |
1930 | if not fname.endswith('.py'): |
|
1930 | if not fname.endswith('.py'): | |
1931 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1931 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1932 |
|
1932 | |||
1933 | # Make sure we can open the file |
|
1933 | # Make sure we can open the file | |
1934 | try: |
|
1934 | try: | |
1935 | with open(fname) as thefile: |
|
1935 | with open(fname) as thefile: | |
1936 | pass |
|
1936 | pass | |
1937 | except: |
|
1937 | except: | |
1938 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1938 | warn('Could not open file <%s> for safe execution.' % fname) | |
1939 | return |
|
1939 | return | |
1940 |
|
1940 | |||
1941 | # Find things also in current directory. This is needed to mimic the |
|
1941 | # Find things also in current directory. This is needed to mimic the | |
1942 | # behavior of running a script from the system command line, where |
|
1942 | # behavior of running a script from the system command line, where | |
1943 | # Python inserts the script's directory into sys.path |
|
1943 | # Python inserts the script's directory into sys.path | |
1944 | dname = os.path.dirname(fname) |
|
1944 | dname = os.path.dirname(fname) | |
1945 |
|
1945 | |||
1946 | with prepended_to_syspath(dname): |
|
1946 | with prepended_to_syspath(dname): | |
1947 | try: |
|
1947 | try: | |
1948 | execfile(fname,*where) |
|
1948 | execfile(fname,*where) | |
1949 | except SystemExit, status: |
|
1949 | except SystemExit, status: | |
1950 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
1950 | # If the call was made with 0 or None exit status (sys.exit(0) | |
1951 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
1951 | # or sys.exit() ), don't bother showing a traceback, as both of | |
1952 | # these are considered normal by the OS: |
|
1952 | # these are considered normal by the OS: | |
1953 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
1953 | # > python -c'import sys;sys.exit(0)'; echo $? | |
1954 | # 0 |
|
1954 | # 0 | |
1955 | # > python -c'import sys;sys.exit()'; echo $? |
|
1955 | # > python -c'import sys;sys.exit()'; echo $? | |
1956 | # 0 |
|
1956 | # 0 | |
1957 | # For other exit status, we show the exception unless |
|
1957 | # For other exit status, we show the exception unless | |
1958 | # explicitly silenced, but only in short form. |
|
1958 | # explicitly silenced, but only in short form. | |
1959 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
1959 | if status.code not in (0, None) and not kw['exit_ignore']: | |
1960 | self.showtraceback(exception_only=True) |
|
1960 | self.showtraceback(exception_only=True) | |
1961 | except: |
|
1961 | except: | |
1962 | self.showtraceback() |
|
1962 | self.showtraceback() | |
1963 |
|
1963 | |||
1964 | def safe_execfile_ipy(self, fname): |
|
1964 | def safe_execfile_ipy(self, fname): | |
1965 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1965 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
1966 |
|
1966 | |||
1967 | Parameters |
|
1967 | Parameters | |
1968 | ---------- |
|
1968 | ---------- | |
1969 | fname : str |
|
1969 | fname : str | |
1970 | The name of the file to execute. The filename must have a |
|
1970 | The name of the file to execute. The filename must have a | |
1971 | .ipy extension. |
|
1971 | .ipy extension. | |
1972 | """ |
|
1972 | """ | |
1973 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1973 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1974 |
|
1974 | |||
1975 | # Make sure we have a .py file |
|
1975 | # Make sure we have a .py file | |
1976 | if not fname.endswith('.ipy'): |
|
1976 | if not fname.endswith('.ipy'): | |
1977 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1977 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1978 |
|
1978 | |||
1979 | # Make sure we can open the file |
|
1979 | # Make sure we can open the file | |
1980 | try: |
|
1980 | try: | |
1981 | with open(fname) as thefile: |
|
1981 | with open(fname) as thefile: | |
1982 | pass |
|
1982 | pass | |
1983 | except: |
|
1983 | except: | |
1984 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1984 | warn('Could not open file <%s> for safe execution.' % fname) | |
1985 | return |
|
1985 | return | |
1986 |
|
1986 | |||
1987 | # Find things also in current directory. This is needed to mimic the |
|
1987 | # Find things also in current directory. This is needed to mimic the | |
1988 | # behavior of running a script from the system command line, where |
|
1988 | # behavior of running a script from the system command line, where | |
1989 | # Python inserts the script's directory into sys.path |
|
1989 | # Python inserts the script's directory into sys.path | |
1990 | dname = os.path.dirname(fname) |
|
1990 | dname = os.path.dirname(fname) | |
1991 |
|
1991 | |||
1992 | with prepended_to_syspath(dname): |
|
1992 | with prepended_to_syspath(dname): | |
1993 | try: |
|
1993 | try: | |
1994 | with open(fname) as thefile: |
|
1994 | with open(fname) as thefile: | |
1995 | script = thefile.read() |
|
1995 | script = thefile.read() | |
1996 | # self.runlines currently captures all exceptions |
|
1996 | # self.runlines currently captures all exceptions | |
1997 | # raise in user code. It would be nice if there were |
|
1997 | # raise in user code. It would be nice if there were | |
1998 | # versions of runlines, execfile that did raise, so |
|
1998 | # versions of runlines, execfile that did raise, so | |
1999 | # we could catch the errors. |
|
1999 | # we could catch the errors. | |
2000 | self.runlines(script, clean=True) |
|
2000 | self.runlines(script, clean=True) | |
2001 | except: |
|
2001 | except: | |
2002 | self.showtraceback() |
|
2002 | self.showtraceback() | |
2003 | warn('Unknown failure executing file: <%s>' % fname) |
|
2003 | warn('Unknown failure executing file: <%s>' % fname) | |
2004 |
|
2004 | |||
2005 | def runlines(self, lines, clean=False): |
|
2005 | def runlines(self, lines, clean=False): | |
2006 | """Run a string of one or more lines of source. |
|
2006 | """Run a string of one or more lines of source. | |
2007 |
|
2007 | |||
2008 | This method is capable of running a string containing multiple source |
|
2008 | This method is capable of running a string containing multiple source | |
2009 | lines, as if they had been entered at the IPython prompt. Since it |
|
2009 | lines, as if they had been entered at the IPython prompt. Since it | |
2010 | exposes IPython's processing machinery, the given strings can contain |
|
2010 | exposes IPython's processing machinery, the given strings can contain | |
2011 | magic calls (%magic), special shell access (!cmd), etc. |
|
2011 | magic calls (%magic), special shell access (!cmd), etc. | |
2012 | """ |
|
2012 | """ | |
2013 |
|
2013 | |||
2014 | if isinstance(lines, (list, tuple)): |
|
2014 | if isinstance(lines, (list, tuple)): | |
2015 | lines = '\n'.join(lines) |
|
2015 | lines = '\n'.join(lines) | |
2016 |
|
2016 | |||
2017 | if clean: |
|
2017 | if clean: | |
2018 | lines = self._cleanup_ipy_script(lines) |
|
2018 | lines = self._cleanup_ipy_script(lines) | |
2019 |
|
2019 | |||
2020 | # We must start with a clean buffer, in case this is run from an |
|
2020 | # We must start with a clean buffer, in case this is run from an | |
2021 | # interactive IPython session (via a magic, for example). |
|
2021 | # interactive IPython session (via a magic, for example). | |
2022 | self.resetbuffer() |
|
2022 | self.resetbuffer() | |
2023 | lines = lines.splitlines() |
|
2023 | lines = lines.splitlines() | |
2024 | more = 0 |
|
2024 | more = 0 | |
2025 | with nested(self.builtin_trap, self.display_trap): |
|
2025 | with nested(self.builtin_trap, self.display_trap): | |
2026 | for line in lines: |
|
2026 | for line in lines: | |
2027 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2027 | # skip blank lines so we don't mess up the prompt counter, but do | |
2028 | # NOT skip even a blank line if we are in a code block (more is |
|
2028 | # NOT skip even a blank line if we are in a code block (more is | |
2029 | # true) |
|
2029 | # true) | |
2030 |
|
2030 | |||
2031 | if line or more: |
|
2031 | if line or more: | |
2032 | # push to raw history, so hist line numbers stay in sync |
|
2032 | # push to raw history, so hist line numbers stay in sync | |
2033 | self.input_hist_raw.append(line + '\n') |
|
2033 | self.input_hist_raw.append(line + '\n') | |
2034 | prefiltered = self.prefilter_manager.prefilter_lines(line, |
|
2034 | prefiltered = self.prefilter_manager.prefilter_lines(line, | |
2035 | more) |
|
2035 | more) | |
2036 | more = self.push_line(prefiltered) |
|
2036 | more = self.push_line(prefiltered) | |
2037 | # IPython's runsource returns None if there was an error |
|
2037 | # IPython's runsource returns None if there was an error | |
2038 | # compiling the code. This allows us to stop processing right |
|
2038 | # compiling the code. This allows us to stop processing right | |
2039 | # away, so the user gets the error message at the right place. |
|
2039 | # away, so the user gets the error message at the right place. | |
2040 | if more is None: |
|
2040 | if more is None: | |
2041 | break |
|
2041 | break | |
2042 | else: |
|
2042 | else: | |
2043 | self.input_hist_raw.append("\n") |
|
2043 | self.input_hist_raw.append("\n") | |
2044 | # final newline in case the input didn't have it, so that the code |
|
2044 | # final newline in case the input didn't have it, so that the code | |
2045 | # actually does get executed |
|
2045 | # actually does get executed | |
2046 | if more: |
|
2046 | if more: | |
2047 | self.push_line('\n') |
|
2047 | self.push_line('\n') | |
2048 |
|
2048 | |||
2049 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2049 | def runsource(self, source, filename='<input>', symbol='single'): | |
2050 | """Compile and run some source in the interpreter. |
|
2050 | """Compile and run some source in the interpreter. | |
2051 |
|
2051 | |||
2052 | Arguments are as for compile_command(). |
|
2052 | Arguments are as for compile_command(). | |
2053 |
|
2053 | |||
2054 | One several things can happen: |
|
2054 | One several things can happen: | |
2055 |
|
2055 | |||
2056 | 1) The input is incorrect; compile_command() raised an |
|
2056 | 1) The input is incorrect; compile_command() raised an | |
2057 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2057 | exception (SyntaxError or OverflowError). A syntax traceback | |
2058 | will be printed by calling the showsyntaxerror() method. |
|
2058 | will be printed by calling the showsyntaxerror() method. | |
2059 |
|
2059 | |||
2060 | 2) The input is incomplete, and more input is required; |
|
2060 | 2) The input is incomplete, and more input is required; | |
2061 | compile_command() returned None. Nothing happens. |
|
2061 | compile_command() returned None. Nothing happens. | |
2062 |
|
2062 | |||
2063 | 3) The input is complete; compile_command() returned a code |
|
2063 | 3) The input is complete; compile_command() returned a code | |
2064 | object. The code is executed by calling self.runcode() (which |
|
2064 | object. The code is executed by calling self.runcode() (which | |
2065 | also handles run-time exceptions, except for SystemExit). |
|
2065 | also handles run-time exceptions, except for SystemExit). | |
2066 |
|
2066 | |||
2067 | The return value is: |
|
2067 | The return value is: | |
2068 |
|
2068 | |||
2069 | - True in case 2 |
|
2069 | - True in case 2 | |
2070 |
|
2070 | |||
2071 | - False in the other cases, unless an exception is raised, where |
|
2071 | - False in the other cases, unless an exception is raised, where | |
2072 | None is returned instead. This can be used by external callers to |
|
2072 | None is returned instead. This can be used by external callers to | |
2073 | know whether to continue feeding input or not. |
|
2073 | know whether to continue feeding input or not. | |
2074 |
|
2074 | |||
2075 | The return value can be used to decide whether to use sys.ps1 or |
|
2075 | The return value can be used to decide whether to use sys.ps1 or | |
2076 | sys.ps2 to prompt the next line.""" |
|
2076 | sys.ps2 to prompt the next line.""" | |
2077 |
|
2077 | |||
2078 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2078 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2079 | # this allows execution of indented pasted code. It is tempting |
|
2079 | # this allows execution of indented pasted code. It is tempting | |
2080 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2080 | # to add '\n' at the end of source to run commands like ' a=1' | |
2081 | # directly, but this fails for more complicated scenarios |
|
2081 | # directly, but this fails for more complicated scenarios | |
2082 | source=source.encode(self.stdin_encoding) |
|
2082 | source=source.encode(self.stdin_encoding) | |
2083 | if source[:1] in [' ', '\t']: |
|
2083 | if source[:1] in [' ', '\t']: | |
2084 | source = 'if 1:\n%s' % source |
|
2084 | source = 'if 1:\n%s' % source | |
2085 |
|
2085 | |||
2086 | try: |
|
2086 | try: | |
2087 | code = self.compile(source,filename,symbol) |
|
2087 | code = self.compile(source,filename,symbol) | |
2088 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2088 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2089 | # Case 1 |
|
2089 | # Case 1 | |
2090 | self.showsyntaxerror(filename) |
|
2090 | self.showsyntaxerror(filename) | |
2091 | return None |
|
2091 | return None | |
2092 |
|
2092 | |||
2093 | if code is None: |
|
2093 | if code is None: | |
2094 | # Case 2 |
|
2094 | # Case 2 | |
2095 | return True |
|
2095 | return True | |
2096 |
|
2096 | |||
2097 | # Case 3 |
|
2097 | # Case 3 | |
2098 | # We store the code object so that threaded shells and |
|
2098 | # We store the code object so that threaded shells and | |
2099 | # custom exception handlers can access all this info if needed. |
|
2099 | # custom exception handlers can access all this info if needed. | |
2100 | # The source corresponding to this can be obtained from the |
|
2100 | # The source corresponding to this can be obtained from the | |
2101 | # buffer attribute as '\n'.join(self.buffer). |
|
2101 | # buffer attribute as '\n'.join(self.buffer). | |
2102 | self.code_to_run = code |
|
2102 | self.code_to_run = code | |
2103 | # now actually execute the code object |
|
2103 | # now actually execute the code object | |
2104 | if self.runcode(code) == 0: |
|
2104 | if self.runcode(code) == 0: | |
2105 | return False |
|
2105 | return False | |
2106 | else: |
|
2106 | else: | |
2107 | return None |
|
2107 | return None | |
2108 |
|
2108 | |||
2109 | def runcode(self,code_obj): |
|
2109 | def runcode(self,code_obj): | |
2110 | """Execute a code object. |
|
2110 | """Execute a code object. | |
2111 |
|
2111 | |||
2112 | When an exception occurs, self.showtraceback() is called to display a |
|
2112 | When an exception occurs, self.showtraceback() is called to display a | |
2113 | traceback. |
|
2113 | traceback. | |
2114 |
|
2114 | |||
2115 | Return value: a flag indicating whether the code to be run completed |
|
2115 | Return value: a flag indicating whether the code to be run completed | |
2116 | successfully: |
|
2116 | successfully: | |
2117 |
|
2117 | |||
2118 | - 0: successful execution. |
|
2118 | - 0: successful execution. | |
2119 | - 1: an error occurred. |
|
2119 | - 1: an error occurred. | |
2120 | """ |
|
2120 | """ | |
2121 |
|
2121 | |||
2122 | # Set our own excepthook in case the user code tries to call it |
|
2122 | # Set our own excepthook in case the user code tries to call it | |
2123 | # directly, so that the IPython crash handler doesn't get triggered |
|
2123 | # directly, so that the IPython crash handler doesn't get triggered | |
2124 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2124 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2125 |
|
2125 | |||
2126 | # we save the original sys.excepthook in the instance, in case config |
|
2126 | # we save the original sys.excepthook in the instance, in case config | |
2127 | # code (such as magics) needs access to it. |
|
2127 | # code (such as magics) needs access to it. | |
2128 | self.sys_excepthook = old_excepthook |
|
2128 | self.sys_excepthook = old_excepthook | |
2129 | outflag = 1 # happens in more places, so it's easier as default |
|
2129 | outflag = 1 # happens in more places, so it's easier as default | |
2130 | try: |
|
2130 | try: | |
2131 | try: |
|
2131 | try: | |
2132 | self.hooks.pre_runcode_hook() |
|
2132 | self.hooks.pre_runcode_hook() | |
2133 | #rprint('Running code') # dbg |
|
2133 | #rprint('Running code') # dbg | |
2134 | exec code_obj in self.user_global_ns, self.user_ns |
|
2134 | exec code_obj in self.user_global_ns, self.user_ns | |
2135 | finally: |
|
2135 | finally: | |
2136 | # Reset our crash handler in place |
|
2136 | # Reset our crash handler in place | |
2137 | sys.excepthook = old_excepthook |
|
2137 | sys.excepthook = old_excepthook | |
2138 | except SystemExit: |
|
2138 | except SystemExit: | |
2139 | self.resetbuffer() |
|
2139 | self.resetbuffer() | |
2140 | self.showtraceback(exception_only=True) |
|
2140 | self.showtraceback(exception_only=True) | |
2141 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2141 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2142 | except self.custom_exceptions: |
|
2142 | except self.custom_exceptions: | |
2143 | etype,value,tb = sys.exc_info() |
|
2143 | etype,value,tb = sys.exc_info() | |
2144 | self.CustomTB(etype,value,tb) |
|
2144 | self.CustomTB(etype,value,tb) | |
2145 | except: |
|
2145 | except: | |
2146 | self.showtraceback() |
|
2146 | self.showtraceback() | |
2147 | else: |
|
2147 | else: | |
2148 | outflag = 0 |
|
2148 | outflag = 0 | |
2149 | if softspace(sys.stdout, 0): |
|
2149 | if softspace(sys.stdout, 0): | |
2150 |
|
2150 | |||
2151 | # Flush out code object which has been run (and source) |
|
2151 | # Flush out code object which has been run (and source) | |
2152 | self.code_to_run = None |
|
2152 | self.code_to_run = None | |
2153 | return outflag |
|
2153 | return outflag | |
2154 |
|
2154 | |||
2155 | def push_line(self, line): |
|
2155 | def push_line(self, line): | |
2156 | """Push a line to the interpreter. |
|
2156 | """Push a line to the interpreter. | |
2157 |
|
2157 | |||
2158 | The line should not have a trailing newline; it may have |
|
2158 | The line should not have a trailing newline; it may have | |
2159 | internal newlines. The line is appended to a buffer and the |
|
2159 | internal newlines. The line is appended to a buffer and the | |
2160 | interpreter's runsource() method is called with the |
|
2160 | interpreter's runsource() method is called with the | |
2161 | concatenated contents of the buffer as source. If this |
|
2161 | concatenated contents of the buffer as source. If this | |
2162 | indicates that the command was executed or invalid, the buffer |
|
2162 | indicates that the command was executed or invalid, the buffer | |
2163 | is reset; otherwise, the command is incomplete, and the buffer |
|
2163 | is reset; otherwise, the command is incomplete, and the buffer | |
2164 | is left as it was after the line was appended. The return |
|
2164 | is left as it was after the line was appended. The return | |
2165 | value is 1 if more input is required, 0 if the line was dealt |
|
2165 | value is 1 if more input is required, 0 if the line was dealt | |
2166 | with in some way (this is the same as runsource()). |
|
2166 | with in some way (this is the same as runsource()). | |
2167 | """ |
|
2167 | """ | |
2168 |
|
2168 | |||
2169 | # autoindent management should be done here, and not in the |
|
2169 | # autoindent management should be done here, and not in the | |
2170 | # interactive loop, since that one is only seen by keyboard input. We |
|
2170 | # interactive loop, since that one is only seen by keyboard input. We | |
2171 | # need this done correctly even for code run via runlines (which uses |
|
2171 | # need this done correctly even for code run via runlines (which uses | |
2172 | # push). |
|
2172 | # push). | |
2173 |
|
2173 | |||
2174 | #print 'push line: <%s>' % line # dbg |
|
2174 | #print 'push line: <%s>' % line # dbg | |
2175 | for subline in line.splitlines(): |
|
2175 | for subline in line.splitlines(): | |
2176 | self._autoindent_update(subline) |
|
2176 | self._autoindent_update(subline) | |
2177 | self.buffer.append(line) |
|
2177 | self.buffer.append(line) | |
2178 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2178 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2179 | if not more: |
|
2179 | if not more: | |
2180 | self.resetbuffer() |
|
2180 | self.resetbuffer() | |
2181 | return more |
|
2181 | return more | |
2182 |
|
2182 | |||
2183 | def resetbuffer(self): |
|
2183 | def resetbuffer(self): | |
2184 | """Reset the input buffer.""" |
|
2184 | """Reset the input buffer.""" | |
2185 | self.buffer[:] = [] |
|
2185 | self.buffer[:] = [] | |
2186 |
|
2186 | |||
2187 | def _is_secondary_block_start(self, s): |
|
2187 | def _is_secondary_block_start(self, s): | |
2188 | if not s.endswith(':'): |
|
2188 | if not s.endswith(':'): | |
2189 | return False |
|
2189 | return False | |
2190 | if (s.startswith('elif') or |
|
2190 | if (s.startswith('elif') or | |
2191 | s.startswith('else') or |
|
2191 | s.startswith('else') or | |
2192 | s.startswith('except') or |
|
2192 | s.startswith('except') or | |
2193 | s.startswith('finally')): |
|
2193 | s.startswith('finally')): | |
2194 | return True |
|
2194 | return True | |
2195 |
|
2195 | |||
2196 | def _cleanup_ipy_script(self, script): |
|
2196 | def _cleanup_ipy_script(self, script): | |
2197 | """Make a script safe for self.runlines() |
|
2197 | """Make a script safe for self.runlines() | |
2198 |
|
2198 | |||
2199 | Currently, IPython is lines based, with blocks being detected by |
|
2199 | Currently, IPython is lines based, with blocks being detected by | |
2200 | empty lines. This is a problem for block based scripts that may |
|
2200 | empty lines. This is a problem for block based scripts that may | |
2201 | not have empty lines after blocks. This script adds those empty |
|
2201 | not have empty lines after blocks. This script adds those empty | |
2202 | lines to make scripts safe for running in the current line based |
|
2202 | lines to make scripts safe for running in the current line based | |
2203 | IPython. |
|
2203 | IPython. | |
2204 | """ |
|
2204 | """ | |
2205 | res = [] |
|
2205 | res = [] | |
2206 | lines = script.splitlines() |
|
2206 | lines = script.splitlines() | |
2207 | level = 0 |
|
2207 | level = 0 | |
2208 |
|
2208 | |||
2209 | for l in lines: |
|
2209 | for l in lines: | |
2210 | lstripped = l.lstrip() |
|
2210 | lstripped = l.lstrip() | |
2211 | stripped = l.strip() |
|
2211 | stripped = l.strip() | |
2212 | if not stripped: |
|
2212 | if not stripped: | |
2213 | continue |
|
2213 | continue | |
2214 | newlevel = len(l) - len(lstripped) |
|
2214 | newlevel = len(l) - len(lstripped) | |
2215 | if level > 0 and newlevel == 0 and \ |
|
2215 | if level > 0 and newlevel == 0 and \ | |
2216 | not self._is_secondary_block_start(stripped): |
|
2216 | not self._is_secondary_block_start(stripped): | |
2217 | # add empty line |
|
2217 | # add empty line | |
2218 | res.append('') |
|
2218 | res.append('') | |
2219 | res.append(l) |
|
2219 | res.append(l) | |
2220 | level = newlevel |
|
2220 | level = newlevel | |
2221 |
|
2221 | |||
2222 | return '\n'.join(res) + '\n' |
|
2222 | return '\n'.join(res) + '\n' | |
2223 |
|
2223 | |||
2224 | def _autoindent_update(self,line): |
|
2224 | def _autoindent_update(self,line): | |
2225 | """Keep track of the indent level.""" |
|
2225 | """Keep track of the indent level.""" | |
2226 |
|
2226 | |||
2227 | #debugx('line') |
|
2227 | #debugx('line') | |
2228 | #debugx('self.indent_current_nsp') |
|
2228 | #debugx('self.indent_current_nsp') | |
2229 | if self.autoindent: |
|
2229 | if self.autoindent: | |
2230 | if line: |
|
2230 | if line: | |
2231 | inisp = num_ini_spaces(line) |
|
2231 | inisp = num_ini_spaces(line) | |
2232 | if inisp < self.indent_current_nsp: |
|
2232 | if inisp < self.indent_current_nsp: | |
2233 | self.indent_current_nsp = inisp |
|
2233 | self.indent_current_nsp = inisp | |
2234 |
|
2234 | |||
2235 | if line[-1] == ':': |
|
2235 | if line[-1] == ':': | |
2236 | self.indent_current_nsp += 4 |
|
2236 | self.indent_current_nsp += 4 | |
2237 | elif dedent_re.match(line): |
|
2237 | elif dedent_re.match(line): | |
2238 | self.indent_current_nsp -= 4 |
|
2238 | self.indent_current_nsp -= 4 | |
2239 | else: |
|
2239 | else: | |
2240 | self.indent_current_nsp = 0 |
|
2240 | self.indent_current_nsp = 0 | |
2241 |
|
2241 | |||
2242 | #------------------------------------------------------------------------- |
|
2242 | #------------------------------------------------------------------------- | |
2243 | # Things related to GUI support and pylab |
|
2243 | # Things related to GUI support and pylab | |
2244 | #------------------------------------------------------------------------- |
|
2244 | #------------------------------------------------------------------------- | |
2245 |
|
2245 | |||
2246 | def enable_pylab(self, gui=None): |
|
2246 | def enable_pylab(self, gui=None): | |
2247 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2247 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2248 |
|
2248 | |||
2249 | #------------------------------------------------------------------------- |
|
2249 | #------------------------------------------------------------------------- | |
2250 | # Utilities |
|
2250 | # Utilities | |
2251 | #------------------------------------------------------------------------- |
|
2251 | #------------------------------------------------------------------------- | |
2252 |
|
2252 | |||
2253 | def var_expand(self,cmd,depth=0): |
|
2253 | def var_expand(self,cmd,depth=0): | |
2254 | """Expand python variables in a string. |
|
2254 | """Expand python variables in a string. | |
2255 |
|
2255 | |||
2256 | The depth argument indicates how many frames above the caller should |
|
2256 | The depth argument indicates how many frames above the caller should | |
2257 | be walked to look for the local namespace where to expand variables. |
|
2257 | be walked to look for the local namespace where to expand variables. | |
2258 |
|
2258 | |||
2259 | The global namespace for expansion is always the user's interactive |
|
2259 | The global namespace for expansion is always the user's interactive | |
2260 | namespace. |
|
2260 | namespace. | |
2261 | """ |
|
2261 | """ | |
2262 |
|
2262 | |||
2263 | return str(ItplNS(cmd, |
|
2263 | return str(ItplNS(cmd, | |
2264 | self.user_ns, # globals |
|
2264 | self.user_ns, # globals | |
2265 | # Skip our own frame in searching for locals: |
|
2265 | # Skip our own frame in searching for locals: | |
2266 | sys._getframe(depth+1).f_locals # locals |
|
2266 | sys._getframe(depth+1).f_locals # locals | |
2267 | )) |
|
2267 | )) | |
2268 |
|
2268 | |||
2269 | def mktempfile(self,data=None): |
|
2269 | def mktempfile(self,data=None): | |
2270 | """Make a new tempfile and return its filename. |
|
2270 | """Make a new tempfile and return its filename. | |
2271 |
|
2271 | |||
2272 | This makes a call to tempfile.mktemp, but it registers the created |
|
2272 | This makes a call to tempfile.mktemp, but it registers the created | |
2273 | filename internally so ipython cleans it up at exit time. |
|
2273 | filename internally so ipython cleans it up at exit time. | |
2274 |
|
2274 | |||
2275 | Optional inputs: |
|
2275 | Optional inputs: | |
2276 |
|
2276 | |||
2277 | - data(None): if data is given, it gets written out to the temp file |
|
2277 | - data(None): if data is given, it gets written out to the temp file | |
2278 | immediately, and the file is closed again.""" |
|
2278 | immediately, and the file is closed again.""" | |
2279 |
|
2279 | |||
2280 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2280 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2281 | self.tempfiles.append(filename) |
|
2281 | self.tempfiles.append(filename) | |
2282 |
|
2282 | |||
2283 | if data: |
|
2283 | if data: | |
2284 | tmp_file = open(filename,'w') |
|
2284 | tmp_file = open(filename,'w') | |
2285 | tmp_file.write(data) |
|
2285 | tmp_file.write(data) | |
2286 | tmp_file.close() |
|
2286 | tmp_file.close() | |
2287 | return filename |
|
2287 | return filename | |
2288 |
|
2288 | |||
2289 | # TODO: This should be removed when Term is refactored. |
|
2289 | # TODO: This should be removed when Term is refactored. | |
2290 | def write(self,data): |
|
2290 | def write(self,data): | |
2291 | """Write a string to the default output""" |
|
2291 | """Write a string to the default output""" | |
2292 | io.Term.cout.write(data) |
|
2292 | io.Term.cout.write(data) | |
2293 |
|
2293 | |||
2294 | # TODO: This should be removed when Term is refactored. |
|
2294 | # TODO: This should be removed when Term is refactored. | |
2295 | def write_err(self,data): |
|
2295 | def write_err(self,data): | |
2296 | """Write a string to the default error output""" |
|
2296 | """Write a string to the default error output""" | |
2297 | io.Term.cerr.write(data) |
|
2297 | io.Term.cerr.write(data) | |
2298 |
|
2298 | |||
2299 | def ask_yes_no(self,prompt,default=True): |
|
2299 | def ask_yes_no(self,prompt,default=True): | |
2300 | if self.quiet: |
|
2300 | if self.quiet: | |
2301 | return True |
|
2301 | return True | |
2302 | return ask_yes_no(prompt,default) |
|
2302 | return ask_yes_no(prompt,default) | |
2303 |
|
2303 | |||
2304 | def show_usage(self): |
|
2304 | def show_usage(self): | |
2305 | """Show a usage message""" |
|
2305 | """Show a usage message""" | |
2306 | page.page(IPython.core.usage.interactive_usage) |
|
2306 | page.page(IPython.core.usage.interactive_usage) | |
2307 |
|
2307 | |||
2308 | #------------------------------------------------------------------------- |
|
2308 | #------------------------------------------------------------------------- | |
2309 | # Things related to IPython exiting |
|
2309 | # Things related to IPython exiting | |
2310 | #------------------------------------------------------------------------- |
|
2310 | #------------------------------------------------------------------------- | |
2311 |
|
2311 | |||
2312 | def atexit_operations(self): |
|
2312 | def atexit_operations(self): | |
2313 | """This will be executed at the time of exit. |
|
2313 | """This will be executed at the time of exit. | |
2314 |
|
2314 | |||
2315 | Saving of persistent data should be performed here. |
|
2315 | Saving of persistent data should be performed here. | |
2316 | """ |
|
2316 | """ | |
2317 | self.savehist() |
|
2317 | self.savehist() | |
2318 |
|
2318 | |||
2319 | # Cleanup all tempfiles left around |
|
2319 | # Cleanup all tempfiles left around | |
2320 | for tfile in self.tempfiles: |
|
2320 | for tfile in self.tempfiles: | |
2321 | try: |
|
2321 | try: | |
2322 | os.unlink(tfile) |
|
2322 | os.unlink(tfile) | |
2323 | except OSError: |
|
2323 | except OSError: | |
2324 | pass |
|
2324 | pass | |
2325 |
|
2325 | |||
2326 | # Clear all user namespaces to release all references cleanly. |
|
2326 | # Clear all user namespaces to release all references cleanly. | |
2327 | self.reset() |
|
2327 | self.reset() | |
2328 |
|
2328 | |||
2329 | # Run user hooks |
|
2329 | # Run user hooks | |
2330 | self.hooks.shutdown_hook() |
|
2330 | self.hooks.shutdown_hook() | |
2331 |
|
2331 | |||
2332 | def cleanup(self): |
|
2332 | def cleanup(self): | |
2333 | self.restore_sys_module_state() |
|
2333 | self.restore_sys_module_state() | |
2334 |
|
2334 | |||
2335 |
|
2335 | |||
2336 | class InteractiveShellABC(object): |
|
2336 | class InteractiveShellABC(object): | |
2337 | """An abstract base class for InteractiveShell.""" |
|
2337 | """An abstract base class for InteractiveShell.""" | |
2338 | __metaclass__ = abc.ABCMeta |
|
2338 | __metaclass__ = abc.ABCMeta | |
2339 |
|
2339 | |||
2340 | InteractiveShellABC.register(InteractiveShell) |
|
2340 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,810 +1,810 | |||||
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 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | __all__ = ['Inspector','InspectColors'] |
|
17 | __all__ = ['Inspector','InspectColors'] | |
18 |
|
18 | |||
19 | # stdlib modules |
|
19 | # stdlib modules | |
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import StringIO |
|
21 | import StringIO | |
22 | import inspect |
|
22 | import inspect | |
23 | import linecache |
|
23 | import linecache | |
24 | import os |
|
24 | import os | |
25 | import string |
|
25 | import string | |
26 | import sys |
|
26 | import sys | |
27 | import types |
|
27 | import types | |
28 | from collections import namedtuple |
|
28 | from collections import namedtuple | |
29 | from itertools import izip_longest |
|
29 | from itertools import izip_longest | |
30 |
|
30 | |||
31 | # IPython's own |
|
31 | # IPython's own | |
32 | from IPython.core import page |
|
32 | from IPython.core import page | |
33 | from IPython.external.Itpl import itpl |
|
33 | from IPython.external.Itpl import itpl | |
34 | from IPython.utils import PyColorize |
|
34 | from IPython.utils import PyColorize | |
35 | import IPython.utils.io |
|
35 | import IPython.utils.io | |
36 | from IPython.utils.text import indent |
|
36 | from IPython.utils.text import indent | |
37 | from IPython.utils.wildcard import list_namespace |
|
37 | from IPython.utils.wildcard import list_namespace | |
38 | from IPython.utils.coloransi import * |
|
38 | from IPython.utils.coloransi import * | |
39 |
|
39 | |||
40 | #**************************************************************************** |
|
40 | #**************************************************************************** | |
41 | # Builtin color schemes |
|
41 | # Builtin color schemes | |
42 |
|
42 | |||
43 | Colors = TermColors # just a shorthand |
|
43 | Colors = TermColors # just a shorthand | |
44 |
|
44 | |||
45 | # Build a few color schemes |
|
45 | # Build a few color schemes | |
46 | NoColor = ColorScheme( |
|
46 | NoColor = ColorScheme( | |
47 | 'NoColor',{ |
|
47 | 'NoColor',{ | |
48 | 'header' : Colors.NoColor, |
|
48 | 'header' : Colors.NoColor, | |
49 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
49 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) | |
50 | } ) |
|
50 | } ) | |
51 |
|
51 | |||
52 | LinuxColors = ColorScheme( |
|
52 | LinuxColors = ColorScheme( | |
53 | 'Linux',{ |
|
53 | 'Linux',{ | |
54 | 'header' : Colors.LightRed, |
|
54 | 'header' : Colors.LightRed, | |
55 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
55 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
56 | } ) |
|
56 | } ) | |
57 |
|
57 | |||
58 | LightBGColors = ColorScheme( |
|
58 | LightBGColors = ColorScheme( | |
59 | 'LightBG',{ |
|
59 | 'LightBG',{ | |
60 | 'header' : Colors.Red, |
|
60 | 'header' : Colors.Red, | |
61 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
61 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
62 | } ) |
|
62 | } ) | |
63 |
|
63 | |||
64 | # Build table of color schemes (needed by the parser) |
|
64 | # Build table of color schemes (needed by the parser) | |
65 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], |
|
65 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], | |
66 | 'Linux') |
|
66 | 'Linux') | |
67 |
|
67 | |||
68 | #**************************************************************************** |
|
68 | #**************************************************************************** | |
69 | # Auxiliary functions and objects |
|
69 | # Auxiliary functions and objects | |
70 |
|
70 | |||
71 | # See the messaging spec for the definition of all these fields. This list |
|
71 | # See the messaging spec for the definition of all these fields. This list | |
72 | # effectively defines the order of display |
|
72 | # effectively defines the order of display | |
73 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', |
|
73 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', | |
74 | 'length', 'file', 'definition', 'docstring', 'source', |
|
74 | 'length', 'file', 'definition', 'docstring', 'source', | |
75 | 'init_definition', 'class_docstring', 'init_docstring', |
|
75 | 'init_definition', 'class_docstring', 'init_docstring', | |
76 | 'call_def', 'call_docstring', |
|
76 | 'call_def', 'call_docstring', | |
77 | # These won't be printed but will be used to determine how to |
|
77 | # These won't be printed but will be used to determine how to | |
78 | # format the object |
|
78 | # format the object | |
79 | 'ismagic', 'isalias', 'argspec', 'found', |
|
79 | 'ismagic', 'isalias', 'argspec', 'found', | |
80 | ] |
|
80 | ] | |
81 |
|
81 | |||
82 |
|
82 | |||
83 | ObjectInfo = namedtuple('ObjectInfo', info_fields) |
|
83 | ObjectInfo = namedtuple('ObjectInfo', info_fields) | |
84 |
|
84 | |||
85 |
|
85 | |||
86 | def mk_object_info(kw): |
|
86 | def mk_object_info(kw): | |
87 | """Make a f""" |
|
87 | """Make a f""" | |
88 | infodict = dict(izip_longest(info_fields, [None])) |
|
88 | infodict = dict(izip_longest(info_fields, [None])) | |
89 | infodict.update(kw) |
|
89 | infodict.update(kw) | |
90 | return ObjectInfo(**infodict) |
|
90 | return ObjectInfo(**infodict) | |
91 |
|
91 | |||
92 |
|
92 | |||
93 | def getdoc(obj): |
|
93 | def getdoc(obj): | |
94 | """Stable wrapper around inspect.getdoc. |
|
94 | """Stable wrapper around inspect.getdoc. | |
95 |
|
95 | |||
96 | This can't crash because of attribute problems. |
|
96 | This can't crash because of attribute problems. | |
97 |
|
97 | |||
98 | It also attempts to call a getdoc() method on the given object. This |
|
98 | It also attempts to call a getdoc() method on the given object. This | |
99 | allows objects which provide their docstrings via non-standard mechanisms |
|
99 | allows objects which provide their docstrings via non-standard mechanisms | |
100 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
100 | (like Pyro proxies) to still be inspected by ipython's ? system.""" | |
101 |
|
101 | |||
102 | ds = None # default return value |
|
102 | ds = None # default return value | |
103 | try: |
|
103 | try: | |
104 | ds = inspect.getdoc(obj) |
|
104 | ds = inspect.getdoc(obj) | |
105 | except: |
|
105 | except: | |
106 | # Harden against an inspect failure, which can occur with |
|
106 | # Harden against an inspect failure, which can occur with | |
107 | # SWIG-wrapped extensions. |
|
107 | # SWIG-wrapped extensions. | |
108 | pass |
|
108 | pass | |
109 | # Allow objects to offer customized documentation via a getdoc method: |
|
109 | # Allow objects to offer customized documentation via a getdoc method: | |
110 | try: |
|
110 | try: | |
111 | ds2 = obj.getdoc() |
|
111 | ds2 = obj.getdoc() | |
112 | except: |
|
112 | except: | |
113 | pass |
|
113 | pass | |
114 | else: |
|
114 | else: | |
115 | # if we get extra info, we add it to the normal docstring. |
|
115 | # if we get extra info, we add it to the normal docstring. | |
116 | if ds is None: |
|
116 | if ds is None: | |
117 | ds = ds2 |
|
117 | ds = ds2 | |
118 | else: |
|
118 | else: | |
119 | ds = '%s\n%s' % (ds,ds2) |
|
119 | ds = '%s\n%s' % (ds,ds2) | |
120 | return ds |
|
120 | return ds | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | def getsource(obj,is_binary=False): |
|
123 | def getsource(obj,is_binary=False): | |
124 | """Wrapper around inspect.getsource. |
|
124 | """Wrapper around inspect.getsource. | |
125 |
|
125 | |||
126 | This can be modified by other projects to provide customized source |
|
126 | This can be modified by other projects to provide customized source | |
127 | extraction. |
|
127 | extraction. | |
128 |
|
128 | |||
129 | Inputs: |
|
129 | Inputs: | |
130 |
|
130 | |||
131 | - obj: an object whose source code we will attempt to extract. |
|
131 | - obj: an object whose source code we will attempt to extract. | |
132 |
|
132 | |||
133 | Optional inputs: |
|
133 | Optional inputs: | |
134 |
|
134 | |||
135 | - is_binary: whether the object is known to come from a binary source. |
|
135 | - is_binary: whether the object is known to come from a binary source. | |
136 | This implementation will skip returning any output for binary objects, but |
|
136 | This implementation will skip returning any output for binary objects, but | |
137 | custom extractors may know how to meaningfully process them.""" |
|
137 | custom extractors may know how to meaningfully process them.""" | |
138 |
|
138 | |||
139 | if is_binary: |
|
139 | if is_binary: | |
140 | return None |
|
140 | return None | |
141 | else: |
|
141 | else: | |
142 | try: |
|
142 | try: | |
143 | src = inspect.getsource(obj) |
|
143 | src = inspect.getsource(obj) | |
144 | except TypeError: |
|
144 | except TypeError: | |
145 | if hasattr(obj,'__class__'): |
|
145 | if hasattr(obj,'__class__'): | |
146 | src = inspect.getsource(obj.__class__) |
|
146 | src = inspect.getsource(obj.__class__) | |
147 | return src |
|
147 | return src | |
148 |
|
148 | |||
149 | def getargspec(obj): |
|
149 | def getargspec(obj): | |
150 | """Get the names and default values of a function's arguments. |
|
150 | """Get the names and default values of a function's arguments. | |
151 |
|
151 | |||
152 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
152 | A tuple of four things is returned: (args, varargs, varkw, defaults). | |
153 | 'args' is a list of the argument names (it may contain nested lists). |
|
153 | 'args' is a list of the argument names (it may contain nested lists). | |
154 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
154 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. | |
155 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
155 | 'defaults' is an n-tuple of the default values of the last n arguments. | |
156 |
|
156 | |||
157 | Modified version of inspect.getargspec from the Python Standard |
|
157 | Modified version of inspect.getargspec from the Python Standard | |
158 | Library.""" |
|
158 | Library.""" | |
159 |
|
159 | |||
160 | if inspect.isfunction(obj): |
|
160 | if inspect.isfunction(obj): | |
161 | func_obj = obj |
|
161 | func_obj = obj | |
162 | elif inspect.ismethod(obj): |
|
162 | elif inspect.ismethod(obj): | |
163 | func_obj = obj.im_func |
|
163 | func_obj = obj.im_func | |
164 | else: |
|
164 | else: | |
165 | raise TypeError('arg is not a Python function') |
|
165 | raise TypeError('arg is not a Python function') | |
166 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
166 | args, varargs, varkw = inspect.getargs(func_obj.func_code) | |
167 | return args, varargs, varkw, func_obj.func_defaults |
|
167 | return args, varargs, varkw, func_obj.func_defaults | |
168 |
|
168 | |||
169 | #**************************************************************************** |
|
169 | #**************************************************************************** | |
170 | # Class definitions |
|
170 | # Class definitions | |
171 |
|
171 | |||
172 | class myStringIO(StringIO.StringIO): |
|
172 | class myStringIO(StringIO.StringIO): | |
173 | """Adds a writeln method to normal StringIO.""" |
|
173 | """Adds a writeln method to normal StringIO.""" | |
174 | def writeln(self,*arg,**kw): |
|
174 | def writeln(self,*arg,**kw): | |
175 | """Does a write() and then a write('\n')""" |
|
175 | """Does a write() and then a write('\n')""" | |
176 | self.write(*arg,**kw) |
|
176 | self.write(*arg,**kw) | |
177 | self.write('\n') |
|
177 | self.write('\n') | |
178 |
|
178 | |||
179 |
|
179 | |||
180 | class Inspector: |
|
180 | class Inspector: | |
181 | def __init__(self,color_table,code_color_table,scheme, |
|
181 | def __init__(self,color_table,code_color_table,scheme, | |
182 | str_detail_level=0): |
|
182 | str_detail_level=0): | |
183 | self.color_table = color_table |
|
183 | self.color_table = color_table | |
184 | self.parser = PyColorize.Parser(code_color_table,out='str') |
|
184 | self.parser = PyColorize.Parser(code_color_table,out='str') | |
185 | self.format = self.parser.format |
|
185 | self.format = self.parser.format | |
186 | self.str_detail_level = str_detail_level |
|
186 | self.str_detail_level = str_detail_level | |
187 | self.set_active_scheme(scheme) |
|
187 | self.set_active_scheme(scheme) | |
188 |
|
188 | |||
189 | def _getdef(self,obj,oname=''): |
|
189 | def _getdef(self,obj,oname=''): | |
190 | """Return the definition header for any callable object. |
|
190 | """Return the definition header for any callable object. | |
191 |
|
191 | |||
192 | If any exception is generated, None is returned instead and the |
|
192 | If any exception is generated, None is returned instead and the | |
193 | exception is suppressed.""" |
|
193 | exception is suppressed.""" | |
194 |
|
194 | |||
195 | try: |
|
195 | try: | |
196 | # We need a plain string here, NOT unicode! |
|
196 | # We need a plain string here, NOT unicode! | |
197 | hdef = oname + inspect.formatargspec(*getargspec(obj)) |
|
197 | hdef = oname + inspect.formatargspec(*getargspec(obj)) | |
198 | return hdef.encode('ascii') |
|
198 | return hdef.encode('ascii') | |
199 | except: |
|
199 | except: | |
200 | return None |
|
200 | return None | |
201 |
|
201 | |||
202 | def __head(self,h): |
|
202 | def __head(self,h): | |
203 | """Return a header string with proper colors.""" |
|
203 | """Return a header string with proper colors.""" | |
204 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
204 | return '%s%s%s' % (self.color_table.active_colors.header,h, | |
205 | self.color_table.active_colors.normal) |
|
205 | self.color_table.active_colors.normal) | |
206 |
|
206 | |||
207 | def set_active_scheme(self,scheme): |
|
207 | def set_active_scheme(self,scheme): | |
208 | self.color_table.set_active_scheme(scheme) |
|
208 | self.color_table.set_active_scheme(scheme) | |
209 | self.parser.color_table.set_active_scheme(scheme) |
|
209 | self.parser.color_table.set_active_scheme(scheme) | |
210 |
|
210 | |||
211 | def noinfo(self,msg,oname): |
|
211 | def noinfo(self,msg,oname): | |
212 | """Generic message when no information is found.""" |
|
212 | """Generic message when no information is found.""" | |
213 | print 'No %s found' % msg, |
|
213 | print 'No %s found' % msg, | |
214 | if oname: |
|
214 | if oname: | |
215 | print 'for %s' % oname |
|
215 | print 'for %s' % oname | |
216 | else: |
|
216 | else: | |
217 |
|
217 | |||
218 |
|
218 | |||
219 | def pdef(self,obj,oname=''): |
|
219 | def pdef(self,obj,oname=''): | |
220 | """Print the definition header for any callable object. |
|
220 | """Print the definition header for any callable object. | |
221 |
|
221 | |||
222 | If the object is a class, print the constructor information.""" |
|
222 | If the object is a class, print the constructor information.""" | |
223 |
|
223 | |||
224 | if not callable(obj): |
|
224 | if not callable(obj): | |
225 | print 'Object is not callable.' |
|
225 | print 'Object is not callable.' | |
226 | return |
|
226 | return | |
227 |
|
227 | |||
228 | header = '' |
|
228 | header = '' | |
229 |
|
229 | |||
230 | if inspect.isclass(obj): |
|
230 | if inspect.isclass(obj): | |
231 | header = self.__head('Class constructor information:\n') |
|
231 | header = self.__head('Class constructor information:\n') | |
232 | obj = obj.__init__ |
|
232 | obj = obj.__init__ | |
233 | elif type(obj) is types.InstanceType: |
|
233 | elif type(obj) is types.InstanceType: | |
234 | obj = obj.__call__ |
|
234 | obj = obj.__call__ | |
235 |
|
235 | |||
236 | output = self._getdef(obj,oname) |
|
236 | output = self._getdef(obj,oname) | |
237 | if output is None: |
|
237 | if output is None: | |
238 | self.noinfo('definition header',oname) |
|
238 | self.noinfo('definition header',oname) | |
239 | else: |
|
239 | else: | |
240 | print >>IPython.utils.io.Term.cout, header,self.format(output), |
|
240 | print >>IPython.utils.io.Term.cout, header,self.format(output), | |
241 |
|
241 | |||
242 | def pdoc(self,obj,oname='',formatter = None): |
|
242 | def pdoc(self,obj,oname='',formatter = None): | |
243 | """Print the docstring for any object. |
|
243 | """Print the docstring for any object. | |
244 |
|
244 | |||
245 | Optional: |
|
245 | Optional: | |
246 | -formatter: a function to run the docstring through for specially |
|
246 | -formatter: a function to run the docstring through for specially | |
247 | formatted docstrings.""" |
|
247 | formatted docstrings.""" | |
248 |
|
248 | |||
249 | head = self.__head # so that itpl can find it even if private |
|
249 | head = self.__head # so that itpl can find it even if private | |
250 | ds = getdoc(obj) |
|
250 | ds = getdoc(obj) | |
251 | if formatter: |
|
251 | if formatter: | |
252 | ds = formatter(ds) |
|
252 | ds = formatter(ds) | |
253 | if inspect.isclass(obj): |
|
253 | if inspect.isclass(obj): | |
254 | init_ds = getdoc(obj.__init__) |
|
254 | init_ds = getdoc(obj.__init__) | |
255 | output = itpl('$head("Class Docstring:")\n' |
|
255 | output = itpl('$head("Class Docstring:")\n' | |
256 | '$indent(ds)\n' |
|
256 | '$indent(ds)\n' | |
257 | '$head("Constructor Docstring"):\n' |
|
257 | '$head("Constructor Docstring"):\n' | |
258 | '$indent(init_ds)') |
|
258 | '$indent(init_ds)') | |
259 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ |
|
259 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ | |
260 | and hasattr(obj,'__call__'): |
|
260 | and hasattr(obj,'__call__'): | |
261 | call_ds = getdoc(obj.__call__) |
|
261 | call_ds = getdoc(obj.__call__) | |
262 | if call_ds: |
|
262 | if call_ds: | |
263 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' |
|
263 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' | |
264 | '$head("Calling Docstring:")\n$indent(call_ds)') |
|
264 | '$head("Calling Docstring:")\n$indent(call_ds)') | |
265 | else: |
|
265 | else: | |
266 | output = ds |
|
266 | output = ds | |
267 | else: |
|
267 | else: | |
268 | output = ds |
|
268 | output = ds | |
269 | if output is None: |
|
269 | if output is None: | |
270 | self.noinfo('documentation',oname) |
|
270 | self.noinfo('documentation',oname) | |
271 | return |
|
271 | return | |
272 | page.page(output) |
|
272 | page.page(output) | |
273 |
|
273 | |||
274 | def psource(self,obj,oname=''): |
|
274 | def psource(self,obj,oname=''): | |
275 | """Print the source code for an object.""" |
|
275 | """Print the source code for an object.""" | |
276 |
|
276 | |||
277 | # Flush the source cache because inspect can return out-of-date source |
|
277 | # Flush the source cache because inspect can return out-of-date source | |
278 | linecache.checkcache() |
|
278 | linecache.checkcache() | |
279 | try: |
|
279 | try: | |
280 | src = getsource(obj) |
|
280 | src = getsource(obj) | |
281 | except: |
|
281 | except: | |
282 | self.noinfo('source',oname) |
|
282 | self.noinfo('source',oname) | |
283 | else: |
|
283 | else: | |
284 | page.page(self.format(src)) |
|
284 | page.page(self.format(src)) | |
285 |
|
285 | |||
286 | def pfile(self,obj,oname=''): |
|
286 | def pfile(self,obj,oname=''): | |
287 | """Show the whole file where an object was defined.""" |
|
287 | """Show the whole file where an object was defined.""" | |
288 |
|
288 | |||
289 | try: |
|
289 | try: | |
290 | try: |
|
290 | try: | |
291 | lineno = inspect.getsourcelines(obj)[1] |
|
291 | lineno = inspect.getsourcelines(obj)[1] | |
292 | except TypeError: |
|
292 | except TypeError: | |
293 | # For instances, try the class object like getsource() does |
|
293 | # For instances, try the class object like getsource() does | |
294 | if hasattr(obj,'__class__'): |
|
294 | if hasattr(obj,'__class__'): | |
295 | lineno = inspect.getsourcelines(obj.__class__)[1] |
|
295 | lineno = inspect.getsourcelines(obj.__class__)[1] | |
296 | # Adjust the inspected object so getabsfile() below works |
|
296 | # Adjust the inspected object so getabsfile() below works | |
297 | obj = obj.__class__ |
|
297 | obj = obj.__class__ | |
298 | except: |
|
298 | except: | |
299 | self.noinfo('file',oname) |
|
299 | self.noinfo('file',oname) | |
300 | return |
|
300 | return | |
301 |
|
301 | |||
302 | # We only reach this point if object was successfully queried |
|
302 | # We only reach this point if object was successfully queried | |
303 |
|
303 | |||
304 | # run contents of file through pager starting at line |
|
304 | # run contents of file through pager starting at line | |
305 | # where the object is defined |
|
305 | # where the object is defined | |
306 | ofile = inspect.getabsfile(obj) |
|
306 | ofile = inspect.getabsfile(obj) | |
307 |
|
307 | |||
308 | if (ofile.endswith('.so') or ofile.endswith('.dll')): |
|
308 | if (ofile.endswith('.so') or ofile.endswith('.dll')): | |
309 | print 'File %r is binary, not printing.' % ofile |
|
309 | print 'File %r is binary, not printing.' % ofile | |
310 | elif not os.path.isfile(ofile): |
|
310 | elif not os.path.isfile(ofile): | |
311 | print 'File %r does not exist, not printing.' % ofile |
|
311 | print 'File %r does not exist, not printing.' % ofile | |
312 | else: |
|
312 | else: | |
313 | # Print only text files, not extension binaries. Note that |
|
313 | # Print only text files, not extension binaries. Note that | |
314 | # getsourcelines returns lineno with 1-offset and page() uses |
|
314 | # getsourcelines returns lineno with 1-offset and page() uses | |
315 | # 0-offset, so we must adjust. |
|
315 | # 0-offset, so we must adjust. | |
316 | page.page(self.format(open(ofile).read()),lineno-1) |
|
316 | page.page(self.format(open(ofile).read()),lineno-1) | |
317 |
|
317 | |||
318 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): |
|
318 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): | |
319 | """Show detailed information about an object. |
|
319 | """Show detailed information about an object. | |
320 |
|
320 | |||
321 | Optional arguments: |
|
321 | Optional arguments: | |
322 |
|
322 | |||
323 | - oname: name of the variable pointing to the object. |
|
323 | - oname: name of the variable pointing to the object. | |
324 |
|
324 | |||
325 | - formatter: special formatter for docstrings (see pdoc) |
|
325 | - formatter: special formatter for docstrings (see pdoc) | |
326 |
|
326 | |||
327 | - info: a structure with some information fields which may have been |
|
327 | - info: a structure with some information fields which may have been | |
328 | precomputed already. |
|
328 | precomputed already. | |
329 |
|
329 | |||
330 | - detail_level: if set to 1, more information is given. |
|
330 | - detail_level: if set to 1, more information is given. | |
331 | """ |
|
331 | """ | |
332 |
|
332 | |||
333 | obj_type = type(obj) |
|
333 | obj_type = type(obj) | |
334 |
|
334 | |||
335 | header = self.__head |
|
335 | header = self.__head | |
336 | if info is None: |
|
336 | if info is None: | |
337 | ismagic = 0 |
|
337 | ismagic = 0 | |
338 | isalias = 0 |
|
338 | isalias = 0 | |
339 | ospace = '' |
|
339 | ospace = '' | |
340 | else: |
|
340 | else: | |
341 | ismagic = info.ismagic |
|
341 | ismagic = info.ismagic | |
342 | isalias = info.isalias |
|
342 | isalias = info.isalias | |
343 | ospace = info.namespace |
|
343 | ospace = info.namespace | |
344 | # Get docstring, special-casing aliases: |
|
344 | # Get docstring, special-casing aliases: | |
345 | if isalias: |
|
345 | if isalias: | |
346 | if not callable(obj): |
|
346 | if not callable(obj): | |
347 | try: |
|
347 | try: | |
348 | ds = "Alias to the system command:\n %s" % obj[1] |
|
348 | ds = "Alias to the system command:\n %s" % obj[1] | |
349 | except: |
|
349 | except: | |
350 | ds = "Alias: " + str(obj) |
|
350 | ds = "Alias: " + str(obj) | |
351 | else: |
|
351 | else: | |
352 | ds = "Alias to " + str(obj) |
|
352 | ds = "Alias to " + str(obj) | |
353 | if obj.__doc__: |
|
353 | if obj.__doc__: | |
354 | ds += "\nDocstring:\n" + obj.__doc__ |
|
354 | ds += "\nDocstring:\n" + obj.__doc__ | |
355 | else: |
|
355 | else: | |
356 | ds = getdoc(obj) |
|
356 | ds = getdoc(obj) | |
357 | if ds is None: |
|
357 | if ds is None: | |
358 | ds = '<no docstring>' |
|
358 | ds = '<no docstring>' | |
359 | if formatter is not None: |
|
359 | if formatter is not None: | |
360 | ds = formatter(ds) |
|
360 | ds = formatter(ds) | |
361 |
|
361 | |||
362 | # store output in a list which gets joined with \n at the end. |
|
362 | # store output in a list which gets joined with \n at the end. | |
363 | out = myStringIO() |
|
363 | out = myStringIO() | |
364 |
|
364 | |||
365 | string_max = 200 # max size of strings to show (snipped if longer) |
|
365 | string_max = 200 # max size of strings to show (snipped if longer) | |
366 | shalf = int((string_max -5)/2) |
|
366 | shalf = int((string_max -5)/2) | |
367 |
|
367 | |||
368 | if ismagic: |
|
368 | if ismagic: | |
369 | obj_type_name = 'Magic function' |
|
369 | obj_type_name = 'Magic function' | |
370 | elif isalias: |
|
370 | elif isalias: | |
371 | obj_type_name = 'System alias' |
|
371 | obj_type_name = 'System alias' | |
372 | else: |
|
372 | else: | |
373 | obj_type_name = obj_type.__name__ |
|
373 | obj_type_name = obj_type.__name__ | |
374 | out.writeln(header('Type:\t\t')+obj_type_name) |
|
374 | out.writeln(header('Type:\t\t')+obj_type_name) | |
375 |
|
375 | |||
376 | try: |
|
376 | try: | |
377 | bclass = obj.__class__ |
|
377 | bclass = obj.__class__ | |
378 | out.writeln(header('Base Class:\t')+str(bclass)) |
|
378 | out.writeln(header('Base Class:\t')+str(bclass)) | |
379 | except: pass |
|
379 | except: pass | |
380 |
|
380 | |||
381 | # String form, but snip if too long in ? form (full in ??) |
|
381 | # String form, but snip if too long in ? form (full in ??) | |
382 | if detail_level >= self.str_detail_level: |
|
382 | if detail_level >= self.str_detail_level: | |
383 | try: |
|
383 | try: | |
384 | ostr = str(obj) |
|
384 | ostr = str(obj) | |
385 | str_head = 'String Form:' |
|
385 | str_head = 'String Form:' | |
386 | if not detail_level and len(ostr)>string_max: |
|
386 | if not detail_level and len(ostr)>string_max: | |
387 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
387 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
388 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
388 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
389 | join(map(string.strip,ostr.split("\n"))) |
|
389 | join(map(string.strip,ostr.split("\n"))) | |
390 | if ostr.find('\n') > -1: |
|
390 | if ostr.find('\n') > -1: | |
391 | # Print multi-line strings starting at the next line. |
|
391 | # Print multi-line strings starting at the next line. | |
392 | str_sep = '\n' |
|
392 | str_sep = '\n' | |
393 | else: |
|
393 | else: | |
394 | str_sep = '\t' |
|
394 | str_sep = '\t' | |
395 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) |
|
395 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) | |
396 | except: |
|
396 | except: | |
397 | pass |
|
397 | pass | |
398 |
|
398 | |||
399 | if ospace: |
|
399 | if ospace: | |
400 | out.writeln(header('Namespace:\t')+ospace) |
|
400 | out.writeln(header('Namespace:\t')+ospace) | |
401 |
|
401 | |||
402 | # Length (for strings and lists) |
|
402 | # Length (for strings and lists) | |
403 | try: |
|
403 | try: | |
404 | length = str(len(obj)) |
|
404 | length = str(len(obj)) | |
405 | out.writeln(header('Length:\t\t')+length) |
|
405 | out.writeln(header('Length:\t\t')+length) | |
406 | except: pass |
|
406 | except: pass | |
407 |
|
407 | |||
408 | # Filename where object was defined |
|
408 | # Filename where object was defined | |
409 | binary_file = False |
|
409 | binary_file = False | |
410 | try: |
|
410 | try: | |
411 | try: |
|
411 | try: | |
412 | fname = inspect.getabsfile(obj) |
|
412 | fname = inspect.getabsfile(obj) | |
413 | except TypeError: |
|
413 | except TypeError: | |
414 | # For an instance, the file that matters is where its class was |
|
414 | # For an instance, the file that matters is where its class was | |
415 | # declared. |
|
415 | # declared. | |
416 | if hasattr(obj,'__class__'): |
|
416 | if hasattr(obj,'__class__'): | |
417 | fname = inspect.getabsfile(obj.__class__) |
|
417 | fname = inspect.getabsfile(obj.__class__) | |
418 | if fname.endswith('<string>'): |
|
418 | if fname.endswith('<string>'): | |
419 | fname = 'Dynamically generated function. No source code available.' |
|
419 | fname = 'Dynamically generated function. No source code available.' | |
420 | if (fname.endswith('.so') or fname.endswith('.dll')): |
|
420 | if (fname.endswith('.so') or fname.endswith('.dll')): | |
421 | binary_file = True |
|
421 | binary_file = True | |
422 | out.writeln(header('File:\t\t')+fname) |
|
422 | out.writeln(header('File:\t\t')+fname) | |
423 | except: |
|
423 | except: | |
424 | # if anything goes wrong, we don't want to show source, so it's as |
|
424 | # if anything goes wrong, we don't want to show source, so it's as | |
425 | # if the file was binary |
|
425 | # if the file was binary | |
426 | binary_file = True |
|
426 | binary_file = True | |
427 |
|
427 | |||
428 | # reconstruct the function definition and print it: |
|
428 | # reconstruct the function definition and print it: | |
429 | defln = self._getdef(obj,oname) |
|
429 | defln = self._getdef(obj,oname) | |
430 | if defln: |
|
430 | if defln: | |
431 | out.write(header('Definition:\t')+self.format(defln)) |
|
431 | out.write(header('Definition:\t')+self.format(defln)) | |
432 |
|
432 | |||
433 | # Docstrings only in detail 0 mode, since source contains them (we |
|
433 | # Docstrings only in detail 0 mode, since source contains them (we | |
434 | # avoid repetitions). If source fails, we add them back, see below. |
|
434 | # avoid repetitions). If source fails, we add them back, see below. | |
435 | if ds and detail_level == 0: |
|
435 | if ds and detail_level == 0: | |
436 | out.writeln(header('Docstring:\n') + indent(ds)) |
|
436 | out.writeln(header('Docstring:\n') + indent(ds)) | |
437 |
|
437 | |||
438 | # Original source code for any callable |
|
438 | # Original source code for any callable | |
439 | if detail_level: |
|
439 | if detail_level: | |
440 | # Flush the source cache because inspect can return out-of-date |
|
440 | # Flush the source cache because inspect can return out-of-date | |
441 | # source |
|
441 | # source | |
442 | linecache.checkcache() |
|
442 | linecache.checkcache() | |
443 | source_success = False |
|
443 | source_success = False | |
444 | try: |
|
444 | try: | |
445 | try: |
|
445 | try: | |
446 | src = getsource(obj,binary_file) |
|
446 | src = getsource(obj,binary_file) | |
447 | except TypeError: |
|
447 | except TypeError: | |
448 | if hasattr(obj,'__class__'): |
|
448 | if hasattr(obj,'__class__'): | |
449 | src = getsource(obj.__class__,binary_file) |
|
449 | src = getsource(obj.__class__,binary_file) | |
450 | if src is not None: |
|
450 | if src is not None: | |
451 | source = self.format(src) |
|
451 | source = self.format(src) | |
452 | out.write(header('Source:\n')+source.rstrip()) |
|
452 | out.write(header('Source:\n')+source.rstrip()) | |
453 | source_success = True |
|
453 | source_success = True | |
454 | except Exception, msg: |
|
454 | except Exception, msg: | |
455 | pass |
|
455 | pass | |
456 |
|
456 | |||
457 | if ds and not source_success: |
|
457 | if ds and not source_success: | |
458 | out.writeln(header('Docstring [source file open failed]:\n') |
|
458 | out.writeln(header('Docstring [source file open failed]:\n') | |
459 | + indent(ds)) |
|
459 | + indent(ds)) | |
460 |
|
460 | |||
461 | # Constructor docstring for classes |
|
461 | # Constructor docstring for classes | |
462 | if inspect.isclass(obj): |
|
462 | if inspect.isclass(obj): | |
463 | # reconstruct the function definition and print it: |
|
463 | # reconstruct the function definition and print it: | |
464 | try: |
|
464 | try: | |
465 | obj_init = obj.__init__ |
|
465 | obj_init = obj.__init__ | |
466 | except AttributeError: |
|
466 | except AttributeError: | |
467 | init_def = init_ds = None |
|
467 | init_def = init_ds = None | |
468 | else: |
|
468 | else: | |
469 | init_def = self._getdef(obj_init,oname) |
|
469 | init_def = self._getdef(obj_init,oname) | |
470 | init_ds = getdoc(obj_init) |
|
470 | init_ds = getdoc(obj_init) | |
471 | # Skip Python's auto-generated docstrings |
|
471 | # Skip Python's auto-generated docstrings | |
472 | if init_ds and \ |
|
472 | if init_ds and \ | |
473 | init_ds.startswith('x.__init__(...) initializes'): |
|
473 | init_ds.startswith('x.__init__(...) initializes'): | |
474 | init_ds = None |
|
474 | init_ds = None | |
475 |
|
475 | |||
476 | if init_def or init_ds: |
|
476 | if init_def or init_ds: | |
477 | out.writeln(header('\nConstructor information:')) |
|
477 | out.writeln(header('\nConstructor information:')) | |
478 | if init_def: |
|
478 | if init_def: | |
479 | out.write(header('Definition:\t')+ self.format(init_def)) |
|
479 | out.write(header('Definition:\t')+ self.format(init_def)) | |
480 | if init_ds: |
|
480 | if init_ds: | |
481 | out.writeln(header('Docstring:\n') + indent(init_ds)) |
|
481 | out.writeln(header('Docstring:\n') + indent(init_ds)) | |
482 | # and class docstring for instances: |
|
482 | # and class docstring for instances: | |
483 | elif obj_type is types.InstanceType or \ |
|
483 | elif obj_type is types.InstanceType or \ | |
484 | isinstance(obj,object): |
|
484 | isinstance(obj,object): | |
485 |
|
485 | |||
486 | # First, check whether the instance docstring is identical to the |
|
486 | # First, check whether the instance docstring is identical to the | |
487 | # class one, and print it separately if they don't coincide. In |
|
487 | # class one, and print it separately if they don't coincide. In | |
488 | # most cases they will, but it's nice to print all the info for |
|
488 | # most cases they will, but it's nice to print all the info for | |
489 | # objects which use instance-customized docstrings. |
|
489 | # objects which use instance-customized docstrings. | |
490 | if ds: |
|
490 | if ds: | |
491 | try: |
|
491 | try: | |
492 | cls = getattr(obj,'__class__') |
|
492 | cls = getattr(obj,'__class__') | |
493 | except: |
|
493 | except: | |
494 | class_ds = None |
|
494 | class_ds = None | |
495 | else: |
|
495 | else: | |
496 | class_ds = getdoc(cls) |
|
496 | class_ds = getdoc(cls) | |
497 | # Skip Python's auto-generated docstrings |
|
497 | # Skip Python's auto-generated docstrings | |
498 | if class_ds and \ |
|
498 | if class_ds and \ | |
499 | (class_ds.startswith('function(code, globals[,') or \ |
|
499 | (class_ds.startswith('function(code, globals[,') or \ | |
500 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
500 | class_ds.startswith('instancemethod(function, instance,') or \ | |
501 | class_ds.startswith('module(name[,') ): |
|
501 | class_ds.startswith('module(name[,') ): | |
502 | class_ds = None |
|
502 | class_ds = None | |
503 | if class_ds and ds != class_ds: |
|
503 | if class_ds and ds != class_ds: | |
504 | out.writeln(header('Class Docstring:\n') + |
|
504 | out.writeln(header('Class Docstring:\n') + | |
505 | indent(class_ds)) |
|
505 | indent(class_ds)) | |
506 |
|
506 | |||
507 | # Next, try to show constructor docstrings |
|
507 | # Next, try to show constructor docstrings | |
508 | try: |
|
508 | try: | |
509 | init_ds = getdoc(obj.__init__) |
|
509 | init_ds = getdoc(obj.__init__) | |
510 | # Skip Python's auto-generated docstrings |
|
510 | # Skip Python's auto-generated docstrings | |
511 | if init_ds and \ |
|
511 | if init_ds and \ | |
512 | init_ds.startswith('x.__init__(...) initializes'): |
|
512 | init_ds.startswith('x.__init__(...) initializes'): | |
513 | init_ds = None |
|
513 | init_ds = None | |
514 | except AttributeError: |
|
514 | except AttributeError: | |
515 | init_ds = None |
|
515 | init_ds = None | |
516 | if init_ds: |
|
516 | if init_ds: | |
517 | out.writeln(header('Constructor Docstring:\n') + |
|
517 | out.writeln(header('Constructor Docstring:\n') + | |
518 | indent(init_ds)) |
|
518 | indent(init_ds)) | |
519 |
|
519 | |||
520 | # Call form docstring for callable instances |
|
520 | # Call form docstring for callable instances | |
521 | if hasattr(obj,'__call__'): |
|
521 | if hasattr(obj,'__call__'): | |
522 | #out.writeln(header('Callable:\t')+'Yes') |
|
522 | #out.writeln(header('Callable:\t')+'Yes') | |
523 | call_def = self._getdef(obj.__call__,oname) |
|
523 | call_def = self._getdef(obj.__call__,oname) | |
524 | #if call_def is None: |
|
524 | #if call_def is None: | |
525 | # out.writeln(header('Call def:\t')+ |
|
525 | # out.writeln(header('Call def:\t')+ | |
526 | # 'Calling definition not available.') |
|
526 | # 'Calling definition not available.') | |
527 | if call_def is not None: |
|
527 | if call_def is not None: | |
528 | out.writeln(header('Call def:\t')+self.format(call_def)) |
|
528 | out.writeln(header('Call def:\t')+self.format(call_def)) | |
529 | call_ds = getdoc(obj.__call__) |
|
529 | call_ds = getdoc(obj.__call__) | |
530 | # Skip Python's auto-generated docstrings |
|
530 | # Skip Python's auto-generated docstrings | |
531 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
531 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): | |
532 | call_ds = None |
|
532 | call_ds = None | |
533 | if call_ds: |
|
533 | if call_ds: | |
534 | out.writeln(header('Call docstring:\n') + indent(call_ds)) |
|
534 | out.writeln(header('Call docstring:\n') + indent(call_ds)) | |
535 |
|
535 | |||
536 | # Finally send to printer/pager |
|
536 | # Finally send to printer/pager | |
537 | output = out.getvalue() |
|
537 | output = out.getvalue() | |
538 | if output: |
|
538 | if output: | |
539 | page.page(output) |
|
539 | page.page(output) | |
540 | # end pinfo |
|
540 | # end pinfo | |
541 |
|
541 | |||
542 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
542 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): | |
543 | """Compute a dict with detailed information about an object. |
|
543 | """Compute a dict with detailed information about an object. | |
544 |
|
544 | |||
545 | Optional arguments: |
|
545 | Optional arguments: | |
546 |
|
546 | |||
547 | - oname: name of the variable pointing to the object. |
|
547 | - oname: name of the variable pointing to the object. | |
548 |
|
548 | |||
549 | - formatter: special formatter for docstrings (see pdoc) |
|
549 | - formatter: special formatter for docstrings (see pdoc) | |
550 |
|
550 | |||
551 | - info: a structure with some information fields which may have been |
|
551 | - info: a structure with some information fields which may have been | |
552 | precomputed already. |
|
552 | precomputed already. | |
553 |
|
553 | |||
554 | - detail_level: if set to 1, more information is given. |
|
554 | - detail_level: if set to 1, more information is given. | |
555 | """ |
|
555 | """ | |
556 |
|
556 | |||
557 | obj_type = type(obj) |
|
557 | obj_type = type(obj) | |
558 |
|
558 | |||
559 | header = self.__head |
|
559 | header = self.__head | |
560 | if info is None: |
|
560 | if info is None: | |
561 | ismagic = 0 |
|
561 | ismagic = 0 | |
562 | isalias = 0 |
|
562 | isalias = 0 | |
563 | ospace = '' |
|
563 | ospace = '' | |
564 | else: |
|
564 | else: | |
565 | ismagic = info.ismagic |
|
565 | ismagic = info.ismagic | |
566 | isalias = info.isalias |
|
566 | isalias = info.isalias | |
567 | ospace = info.namespace |
|
567 | ospace = info.namespace | |
568 | # Get docstring, special-casing aliases: |
|
568 | # Get docstring, special-casing aliases: | |
569 | if isalias: |
|
569 | if isalias: | |
570 | if not callable(obj): |
|
570 | if not callable(obj): | |
571 | try: |
|
571 | try: | |
572 | ds = "Alias to the system command:\n %s" % obj[1] |
|
572 | ds = "Alias to the system command:\n %s" % obj[1] | |
573 | except: |
|
573 | except: | |
574 | ds = "Alias: " + str(obj) |
|
574 | ds = "Alias: " + str(obj) | |
575 | else: |
|
575 | else: | |
576 | ds = "Alias to " + str(obj) |
|
576 | ds = "Alias to " + str(obj) | |
577 | if obj.__doc__: |
|
577 | if obj.__doc__: | |
578 | ds += "\nDocstring:\n" + obj.__doc__ |
|
578 | ds += "\nDocstring:\n" + obj.__doc__ | |
579 | else: |
|
579 | else: | |
580 | ds = getdoc(obj) |
|
580 | ds = getdoc(obj) | |
581 | if ds is None: |
|
581 | if ds is None: | |
582 | ds = '<no docstring>' |
|
582 | ds = '<no docstring>' | |
583 | if formatter is not None: |
|
583 | if formatter is not None: | |
584 | ds = formatter(ds) |
|
584 | ds = formatter(ds) | |
585 |
|
585 | |||
586 | # store output in a dict, we'll later convert it to an ObjectInfo. We |
|
586 | # store output in a dict, we'll later convert it to an ObjectInfo. We | |
587 | # initialize it here and fill it as we go |
|
587 | # initialize it here and fill it as we go | |
588 | out = dict(isalias=isalias, ismagic=ismagic) |
|
588 | out = dict(found=True, isalias=isalias, ismagic=ismagic) | |
589 |
|
589 | |||
590 | string_max = 200 # max size of strings to show (snipped if longer) |
|
590 | string_max = 200 # max size of strings to show (snipped if longer) | |
591 | shalf = int((string_max -5)/2) |
|
591 | shalf = int((string_max -5)/2) | |
592 |
|
592 | |||
593 | if ismagic: |
|
593 | if ismagic: | |
594 | obj_type_name = 'Magic function' |
|
594 | obj_type_name = 'Magic function' | |
595 | elif isalias: |
|
595 | elif isalias: | |
596 | obj_type_name = 'System alias' |
|
596 | obj_type_name = 'System alias' | |
597 | else: |
|
597 | else: | |
598 | obj_type_name = obj_type.__name__ |
|
598 | obj_type_name = obj_type.__name__ | |
599 | out['type_name'] = obj_type_name |
|
599 | out['type_name'] = obj_type_name | |
600 |
|
600 | |||
601 | try: |
|
601 | try: | |
602 | bclass = obj.__class__ |
|
602 | bclass = obj.__class__ | |
603 | out['base_class'] = str(bclass) |
|
603 | out['base_class'] = str(bclass) | |
604 | except: pass |
|
604 | except: pass | |
605 |
|
605 | |||
606 | # String form, but snip if too long in ? form (full in ??) |
|
606 | # String form, but snip if too long in ? form (full in ??) | |
607 | if detail_level >= self.str_detail_level: |
|
607 | if detail_level >= self.str_detail_level: | |
608 | try: |
|
608 | try: | |
609 | ostr = str(obj) |
|
609 | ostr = str(obj) | |
610 | str_head = 'string_form' |
|
610 | str_head = 'string_form' | |
611 | if not detail_level and len(ostr)>string_max: |
|
611 | if not detail_level and len(ostr)>string_max: | |
612 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
612 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
613 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
613 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
614 | join(map(string.strip,ostr.split("\n"))) |
|
614 | join(map(string.strip,ostr.split("\n"))) | |
615 | if ostr.find('\n') > -1: |
|
615 | if ostr.find('\n') > -1: | |
616 | # Print multi-line strings starting at the next line. |
|
616 | # Print multi-line strings starting at the next line. | |
617 | str_sep = '\n' |
|
617 | str_sep = '\n' | |
618 | else: |
|
618 | else: | |
619 | str_sep = '\t' |
|
619 | str_sep = '\t' | |
620 | out[str_head] = ostr |
|
620 | out[str_head] = ostr | |
621 | except: |
|
621 | except: | |
622 | pass |
|
622 | pass | |
623 |
|
623 | |||
624 | if ospace: |
|
624 | if ospace: | |
625 | out['namespace'] = ospace |
|
625 | out['namespace'] = ospace | |
626 |
|
626 | |||
627 | # Length (for strings and lists) |
|
627 | # Length (for strings and lists) | |
628 | try: |
|
628 | try: | |
629 | out['length'] = str(len(obj)) |
|
629 | out['length'] = str(len(obj)) | |
630 | except: pass |
|
630 | except: pass | |
631 |
|
631 | |||
632 | # Filename where object was defined |
|
632 | # Filename where object was defined | |
633 | binary_file = False |
|
633 | binary_file = False | |
634 | try: |
|
634 | try: | |
635 | try: |
|
635 | try: | |
636 | fname = inspect.getabsfile(obj) |
|
636 | fname = inspect.getabsfile(obj) | |
637 | except TypeError: |
|
637 | except TypeError: | |
638 | # For an instance, the file that matters is where its class was |
|
638 | # For an instance, the file that matters is where its class was | |
639 | # declared. |
|
639 | # declared. | |
640 | if hasattr(obj,'__class__'): |
|
640 | if hasattr(obj,'__class__'): | |
641 | fname = inspect.getabsfile(obj.__class__) |
|
641 | fname = inspect.getabsfile(obj.__class__) | |
642 | if fname.endswith('<string>'): |
|
642 | if fname.endswith('<string>'): | |
643 | fname = 'Dynamically generated function. No source code available.' |
|
643 | fname = 'Dynamically generated function. No source code available.' | |
644 | if (fname.endswith('.so') or fname.endswith('.dll')): |
|
644 | if (fname.endswith('.so') or fname.endswith('.dll')): | |
645 | binary_file = True |
|
645 | binary_file = True | |
646 | out['file'] = fname |
|
646 | out['file'] = fname | |
647 | except: |
|
647 | except: | |
648 | # if anything goes wrong, we don't want to show source, so it's as |
|
648 | # if anything goes wrong, we don't want to show source, so it's as | |
649 | # if the file was binary |
|
649 | # if the file was binary | |
650 | binary_file = True |
|
650 | binary_file = True | |
651 |
|
651 | |||
652 | # reconstruct the function definition and print it: |
|
652 | # reconstruct the function definition and print it: | |
653 | defln = self._getdef(obj,oname) |
|
653 | defln = self._getdef(obj,oname) | |
654 | if defln: |
|
654 | if defln: | |
655 | out['definition'] = self.format(defln) |
|
655 | out['definition'] = self.format(defln) | |
656 | args, varargs, varkw, func_defaults = getargspec(obj) |
|
656 | args, varargs, varkw, func_defaults = getargspec(obj) | |
657 | out['argspec'] = dict(args=args, varargs=varargs, |
|
657 | out['argspec'] = dict(args=args, varargs=varargs, | |
658 | varkw=varkw, func_defaults=func_defaults) |
|
658 | varkw=varkw, func_defaults=func_defaults) | |
659 |
|
659 | |||
660 | # Docstrings only in detail 0 mode, since source contains them (we |
|
660 | # Docstrings only in detail 0 mode, since source contains them (we | |
661 | # avoid repetitions). If source fails, we add them back, see below. |
|
661 | # avoid repetitions). If source fails, we add them back, see below. | |
662 | if ds and detail_level == 0: |
|
662 | if ds and detail_level == 0: | |
663 | out['docstring'] = indent(ds) |
|
663 | out['docstring'] = indent(ds) | |
664 |
|
664 | |||
665 | # Original source code for any callable |
|
665 | # Original source code for any callable | |
666 | if detail_level: |
|
666 | if detail_level: | |
667 | # Flush the source cache because inspect can return out-of-date |
|
667 | # Flush the source cache because inspect can return out-of-date | |
668 | # source |
|
668 | # source | |
669 | linecache.checkcache() |
|
669 | linecache.checkcache() | |
670 | source_success = False |
|
670 | source_success = False | |
671 | try: |
|
671 | try: | |
672 | try: |
|
672 | try: | |
673 | src = getsource(obj,binary_file) |
|
673 | src = getsource(obj,binary_file) | |
674 | except TypeError: |
|
674 | except TypeError: | |
675 | if hasattr(obj,'__class__'): |
|
675 | if hasattr(obj,'__class__'): | |
676 | src = getsource(obj.__class__,binary_file) |
|
676 | src = getsource(obj.__class__,binary_file) | |
677 | if src is not None: |
|
677 | if src is not None: | |
678 | source = self.format(src) |
|
678 | source = self.format(src) | |
679 | out['source'] = source.rstrip() |
|
679 | out['source'] = source.rstrip() | |
680 | source_success = True |
|
680 | source_success = True | |
681 | except Exception, msg: |
|
681 | except Exception, msg: | |
682 | pass |
|
682 | pass | |
683 |
|
683 | |||
684 | # Constructor docstring for classes |
|
684 | # Constructor docstring for classes | |
685 | if inspect.isclass(obj): |
|
685 | if inspect.isclass(obj): | |
686 | # reconstruct the function definition and print it: |
|
686 | # reconstruct the function definition and print it: | |
687 | try: |
|
687 | try: | |
688 | obj_init = obj.__init__ |
|
688 | obj_init = obj.__init__ | |
689 | except AttributeError: |
|
689 | except AttributeError: | |
690 | init_def = init_ds = None |
|
690 | init_def = init_ds = None | |
691 | else: |
|
691 | else: | |
692 | init_def = self._getdef(obj_init,oname) |
|
692 | init_def = self._getdef(obj_init,oname) | |
693 | init_ds = getdoc(obj_init) |
|
693 | init_ds = getdoc(obj_init) | |
694 | # Skip Python's auto-generated docstrings |
|
694 | # Skip Python's auto-generated docstrings | |
695 | if init_ds and \ |
|
695 | if init_ds and \ | |
696 | init_ds.startswith('x.__init__(...) initializes'): |
|
696 | init_ds.startswith('x.__init__(...) initializes'): | |
697 | init_ds = None |
|
697 | init_ds = None | |
698 |
|
698 | |||
699 | if init_def or init_ds: |
|
699 | if init_def or init_ds: | |
700 | if init_def: |
|
700 | if init_def: | |
701 | out['init_definition'] = self.format(init_def) |
|
701 | out['init_definition'] = self.format(init_def) | |
702 | if init_ds: |
|
702 | if init_ds: | |
703 | out['init_docstring'] = indent(init_ds) |
|
703 | out['init_docstring'] = indent(init_ds) | |
704 | # and class docstring for instances: |
|
704 | # and class docstring for instances: | |
705 | elif obj_type is types.InstanceType or \ |
|
705 | elif obj_type is types.InstanceType or \ | |
706 | isinstance(obj,object): |
|
706 | isinstance(obj,object): | |
707 |
|
707 | |||
708 | # First, check whether the instance docstring is identical to the |
|
708 | # First, check whether the instance docstring is identical to the | |
709 | # class one, and print it separately if they don't coincide. In |
|
709 | # class one, and print it separately if they don't coincide. In | |
710 | # most cases they will, but it's nice to print all the info for |
|
710 | # most cases they will, but it's nice to print all the info for | |
711 | # objects which use instance-customized docstrings. |
|
711 | # objects which use instance-customized docstrings. | |
712 | if ds: |
|
712 | if ds: | |
713 | try: |
|
713 | try: | |
714 | cls = getattr(obj,'__class__') |
|
714 | cls = getattr(obj,'__class__') | |
715 | except: |
|
715 | except: | |
716 | class_ds = None |
|
716 | class_ds = None | |
717 | else: |
|
717 | else: | |
718 | class_ds = getdoc(cls) |
|
718 | class_ds = getdoc(cls) | |
719 | # Skip Python's auto-generated docstrings |
|
719 | # Skip Python's auto-generated docstrings | |
720 | if class_ds and \ |
|
720 | if class_ds and \ | |
721 | (class_ds.startswith('function(code, globals[,') or \ |
|
721 | (class_ds.startswith('function(code, globals[,') or \ | |
722 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
722 | class_ds.startswith('instancemethod(function, instance,') or \ | |
723 | class_ds.startswith('module(name[,') ): |
|
723 | class_ds.startswith('module(name[,') ): | |
724 | class_ds = None |
|
724 | class_ds = None | |
725 | if class_ds and ds != class_ds: |
|
725 | if class_ds and ds != class_ds: | |
726 | out['class_docstring'] = indent(class_ds) |
|
726 | out['class_docstring'] = indent(class_ds) | |
727 |
|
727 | |||
728 | # Next, try to show constructor docstrings |
|
728 | # Next, try to show constructor docstrings | |
729 | try: |
|
729 | try: | |
730 | init_ds = getdoc(obj.__init__) |
|
730 | init_ds = getdoc(obj.__init__) | |
731 | # Skip Python's auto-generated docstrings |
|
731 | # Skip Python's auto-generated docstrings | |
732 | if init_ds and \ |
|
732 | if init_ds and \ | |
733 | init_ds.startswith('x.__init__(...) initializes'): |
|
733 | init_ds.startswith('x.__init__(...) initializes'): | |
734 | init_ds = None |
|
734 | init_ds = None | |
735 | except AttributeError: |
|
735 | except AttributeError: | |
736 | init_ds = None |
|
736 | init_ds = None | |
737 | if init_ds: |
|
737 | if init_ds: | |
738 | out['init_docstring'] = indent(init_ds) |
|
738 | out['init_docstring'] = indent(init_ds) | |
739 |
|
739 | |||
740 | # Call form docstring for callable instances |
|
740 | # Call form docstring for callable instances | |
741 | if hasattr(obj,'__call__'): |
|
741 | if hasattr(obj,'__call__'): | |
742 | call_def = self._getdef(obj.__call__,oname) |
|
742 | call_def = self._getdef(obj.__call__,oname) | |
743 | if call_def is not None: |
|
743 | if call_def is not None: | |
744 | out['call_def'] = self.format(call_def) |
|
744 | out['call_def'] = self.format(call_def) | |
745 | call_ds = getdoc(obj.__call__) |
|
745 | call_ds = getdoc(obj.__call__) | |
746 | # Skip Python's auto-generated docstrings |
|
746 | # Skip Python's auto-generated docstrings | |
747 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
747 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): | |
748 | call_ds = None |
|
748 | call_ds = None | |
749 | if call_ds: |
|
749 | if call_ds: | |
750 | out['call_docstring'] = indent(call_ds) |
|
750 | out['call_docstring'] = indent(call_ds) | |
751 |
|
751 | |||
752 | return mk_object_info(out) |
|
752 | return mk_object_info(out) | |
753 |
|
753 | |||
754 |
|
754 | |||
755 | def psearch(self,pattern,ns_table,ns_search=[], |
|
755 | def psearch(self,pattern,ns_table,ns_search=[], | |
756 | ignore_case=False,show_all=False): |
|
756 | ignore_case=False,show_all=False): | |
757 | """Search namespaces with wildcards for objects. |
|
757 | """Search namespaces with wildcards for objects. | |
758 |
|
758 | |||
759 | Arguments: |
|
759 | Arguments: | |
760 |
|
760 | |||
761 | - pattern: string containing shell-like wildcards to use in namespace |
|
761 | - pattern: string containing shell-like wildcards to use in namespace | |
762 | searches and optionally a type specification to narrow the search to |
|
762 | searches and optionally a type specification to narrow the search to | |
763 | objects of that type. |
|
763 | objects of that type. | |
764 |
|
764 | |||
765 | - ns_table: dict of name->namespaces for search. |
|
765 | - ns_table: dict of name->namespaces for search. | |
766 |
|
766 | |||
767 | Optional arguments: |
|
767 | Optional arguments: | |
768 |
|
768 | |||
769 | - ns_search: list of namespace names to include in search. |
|
769 | - ns_search: list of namespace names to include in search. | |
770 |
|
770 | |||
771 | - ignore_case(False): make the search case-insensitive. |
|
771 | - ignore_case(False): make the search case-insensitive. | |
772 |
|
772 | |||
773 | - show_all(False): show all names, including those starting with |
|
773 | - show_all(False): show all names, including those starting with | |
774 | underscores. |
|
774 | underscores. | |
775 | """ |
|
775 | """ | |
776 | #print 'ps pattern:<%r>' % pattern # dbg |
|
776 | #print 'ps pattern:<%r>' % pattern # dbg | |
777 |
|
777 | |||
778 | # defaults |
|
778 | # defaults | |
779 | type_pattern = 'all' |
|
779 | type_pattern = 'all' | |
780 | filter = '' |
|
780 | filter = '' | |
781 |
|
781 | |||
782 | cmds = pattern.split() |
|
782 | cmds = pattern.split() | |
783 | len_cmds = len(cmds) |
|
783 | len_cmds = len(cmds) | |
784 | if len_cmds == 1: |
|
784 | if len_cmds == 1: | |
785 | # Only filter pattern given |
|
785 | # Only filter pattern given | |
786 | filter = cmds[0] |
|
786 | filter = cmds[0] | |
787 | elif len_cmds == 2: |
|
787 | elif len_cmds == 2: | |
788 | # Both filter and type specified |
|
788 | # Both filter and type specified | |
789 | filter,type_pattern = cmds |
|
789 | filter,type_pattern = cmds | |
790 | else: |
|
790 | else: | |
791 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
791 | raise ValueError('invalid argument string for psearch: <%s>' % | |
792 | pattern) |
|
792 | pattern) | |
793 |
|
793 | |||
794 | # filter search namespaces |
|
794 | # filter search namespaces | |
795 | for name in ns_search: |
|
795 | for name in ns_search: | |
796 | if name not in ns_table: |
|
796 | if name not in ns_table: | |
797 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
797 | raise ValueError('invalid namespace <%s>. Valid names: %s' % | |
798 | (name,ns_table.keys())) |
|
798 | (name,ns_table.keys())) | |
799 |
|
799 | |||
800 | #print 'type_pattern:',type_pattern # dbg |
|
800 | #print 'type_pattern:',type_pattern # dbg | |
801 | search_result = [] |
|
801 | search_result = [] | |
802 | for ns_name in ns_search: |
|
802 | for ns_name in ns_search: | |
803 | ns = ns_table[ns_name] |
|
803 | ns = ns_table[ns_name] | |
804 | tmp_res = list(list_namespace(ns,type_pattern,filter, |
|
804 | tmp_res = list(list_namespace(ns,type_pattern,filter, | |
805 | ignore_case=ignore_case, |
|
805 | ignore_case=ignore_case, | |
806 | show_all=show_all)) |
|
806 | show_all=show_all)) | |
807 | search_result.extend(tmp_res) |
|
807 | search_result.extend(tmp_res) | |
808 | search_result.sort() |
|
808 | search_result.sort() | |
809 |
|
809 | |||
810 | page.page('\n'.join(search_result)) |
|
810 | page.page('\n'.join(search_result)) |
General Comments 0
You need to be logged in to leave comments.
Login now