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