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