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