Show More
@@ -1,2127 +1,2150 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.config.configurable import Configurable | |||
32 | from IPython.core import debugger, oinspect |
|
33 | from IPython.core import debugger, oinspect | |
33 | from IPython.core import history as ipcorehist |
|
34 | from IPython.core import history as ipcorehist | |
34 | from IPython.core import prefilter |
|
35 | from IPython.core import prefilter | |
35 | from IPython.core import shadowns |
|
36 | from IPython.core import shadowns | |
36 | from IPython.core import ultratb |
|
37 | from IPython.core import ultratb | |
37 | from IPython.core.alias import AliasManager |
|
38 | from IPython.core.alias import AliasManager | |
38 | from IPython.core.builtin_trap import BuiltinTrap |
|
39 | from IPython.core.builtin_trap import BuiltinTrap | |
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.displayhook import DisplayHook | |||
41 | from IPython.core.error import UsageError |
|
42 | from IPython.core.error import UsageError | |
42 | from IPython.core.extensions import ExtensionManager |
|
43 | from IPython.core.extensions import ExtensionManager | |
43 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
44 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
44 | from IPython.core.inputlist import InputList |
|
45 | from IPython.core.inputlist import InputList | |
45 | from IPython.core.logger import Logger |
|
46 | from IPython.core.logger import Logger | |
46 | from IPython.core.magic import Magic |
|
47 | from IPython.core.magic import Magic | |
47 | from IPython.core.payload import PayloadManager |
|
48 | from IPython.core.payload import PayloadManager | |
48 | from IPython.core.plugin import PluginManager |
|
49 | from IPython.core.plugin import PluginManager | |
49 | from IPython.core.prefilter import PrefilterManager |
|
50 | from IPython.core.prefilter import PrefilterManager | |
50 | from IPython.core.displayhook import DisplayHook |
|
|||
51 | import IPython.core.hooks |
|
|||
52 | from IPython.external.Itpl import ItplNS |
|
51 | from IPython.external.Itpl import ItplNS | |
53 | from IPython.utils import PyColorize |
|
52 | from IPython.utils import PyColorize | |
|
53 | from IPython.utils import io | |||
54 | from IPython.utils import pickleshare |
|
54 | from IPython.utils import pickleshare | |
55 | from IPython.utils.doctestreload import doctest_reload |
|
55 | from IPython.utils.doctestreload import doctest_reload | |
|
56 | from IPython.utils.io import ask_yes_no, rprint | |||
56 | from IPython.utils.ipstruct import Struct |
|
57 | from IPython.utils.ipstruct import Struct | |
57 | import IPython.utils.io |
|
|||
58 | from IPython.utils.io import ask_yes_no |
|
|||
59 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
58 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
60 | from IPython.utils.process import getoutput, getoutputerror |
|
59 | from IPython.utils.process import getoutput, getoutputerror | |
61 | from IPython.utils.strdispatch import StrDispatch |
|
60 | from IPython.utils.strdispatch import StrDispatch | |
62 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
61 | from IPython.utils.syspathcontext import prepended_to_syspath | |
63 | from IPython.utils.text import num_ini_spaces |
|
62 | from IPython.utils.text import num_ini_spaces | |
|
63 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |||
|
64 | List, Unicode, Instance, Type) | |||
64 | from IPython.utils.warn import warn, error, fatal |
|
65 | from IPython.utils.warn import warn, error, fatal | |
65 | from IPython.utils.traitlets import ( |
|
66 | import IPython.core.hooks | |
66 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance, Type |
|
|||
67 | ) |
|
|||
68 |
|
67 | |||
69 | # from IPython.utils import growl |
|
68 | # from IPython.utils import growl | |
70 | # growl.start("IPython") |
|
69 | # growl.start("IPython") | |
71 |
|
70 | |||
72 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
73 | # Globals |
|
72 | # Globals | |
74 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
75 |
|
74 | |||
76 | # compiled regexps for autoindent management |
|
75 | # compiled regexps for autoindent management | |
77 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
76 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
78 |
|
77 | |||
79 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
80 | # Utilities |
|
79 | # Utilities | |
81 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
82 |
|
81 | |||
83 | # store the builtin raw_input globally, and use this always, in case user code |
|
82 | # store the builtin raw_input globally, and use this always, in case user code | |
84 | # overwrites it (like wx.py.PyShell does) |
|
83 | # overwrites it (like wx.py.PyShell does) | |
85 | raw_input_original = raw_input |
|
84 | raw_input_original = raw_input | |
86 |
|
85 | |||
87 | def softspace(file, newvalue): |
|
86 | def softspace(file, newvalue): | |
88 | """Copied from code.py, to remove the dependency""" |
|
87 | """Copied from code.py, to remove the dependency""" | |
89 |
|
88 | |||
90 | oldvalue = 0 |
|
89 | oldvalue = 0 | |
91 | try: |
|
90 | try: | |
92 | oldvalue = file.softspace |
|
91 | oldvalue = file.softspace | |
93 | except AttributeError: |
|
92 | except AttributeError: | |
94 | pass |
|
93 | pass | |
95 | try: |
|
94 | try: | |
96 | file.softspace = newvalue |
|
95 | file.softspace = newvalue | |
97 | except (AttributeError, TypeError): |
|
96 | except (AttributeError, TypeError): | |
98 | # "attribute-less object" or "read-only attributes" |
|
97 | # "attribute-less object" or "read-only attributes" | |
99 | pass |
|
98 | pass | |
100 | return oldvalue |
|
99 | return oldvalue | |
101 |
|
100 | |||
102 |
|
101 | |||
103 | def no_op(*a, **kw): pass |
|
102 | def no_op(*a, **kw): pass | |
104 |
|
103 | |||
105 | class SpaceInInput(exceptions.Exception): pass |
|
104 | class SpaceInInput(exceptions.Exception): pass | |
106 |
|
105 | |||
107 | class Bunch: pass |
|
106 | class Bunch: pass | |
108 |
|
107 | |||
109 |
|
108 | |||
110 | def get_default_colors(): |
|
109 | def get_default_colors(): | |
111 | if sys.platform=='darwin': |
|
110 | if sys.platform=='darwin': | |
112 | return "LightBG" |
|
111 | return "LightBG" | |
113 | elif os.name=='nt': |
|
112 | elif os.name=='nt': | |
114 | return 'Linux' |
|
113 | return 'Linux' | |
115 | else: |
|
114 | else: | |
116 | return 'Linux' |
|
115 | return 'Linux' | |
117 |
|
116 | |||
118 |
|
117 | |||
119 | class SeparateStr(Str): |
|
118 | class SeparateStr(Str): | |
120 | """A Str subclass to validate separate_in, separate_out, etc. |
|
119 | """A Str subclass to validate separate_in, separate_out, etc. | |
121 |
|
120 | |||
122 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
121 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
123 | """ |
|
122 | """ | |
124 |
|
123 | |||
125 | def validate(self, obj, value): |
|
124 | def validate(self, obj, value): | |
126 | if value == '0': value = '' |
|
125 | if value == '0': value = '' | |
127 | value = value.replace('\\n','\n') |
|
126 | value = value.replace('\\n','\n') | |
128 | return super(SeparateStr, self).validate(obj, value) |
|
127 | return super(SeparateStr, self).validate(obj, value) | |
129 |
|
128 | |||
130 | class MultipleInstanceError(Exception): |
|
129 | class MultipleInstanceError(Exception): | |
131 | pass |
|
130 | pass | |
132 |
|
131 | |||
133 |
|
132 | |||
134 | #----------------------------------------------------------------------------- |
|
133 | #----------------------------------------------------------------------------- | |
135 | # Main IPython class |
|
134 | # Main IPython class | |
136 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
137 |
|
136 | |||
138 |
|
137 | |||
139 | class InteractiveShell(Configurable, Magic): |
|
138 | class InteractiveShell(Configurable, Magic): | |
140 | """An enhanced, interactive shell for Python.""" |
|
139 | """An enhanced, interactive shell for Python.""" | |
141 |
|
140 | |||
142 | _instance = None |
|
141 | _instance = None | |
143 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
142 | autocall = Enum((0,1,2), default_value=1, config=True) | |
144 | # TODO: remove all autoindent logic and put into frontends. |
|
143 | # TODO: remove all autoindent logic and put into frontends. | |
145 | # We can't do this yet because even runlines uses the autoindent. |
|
144 | # We can't do this yet because even runlines uses the autoindent. | |
146 | autoindent = CBool(True, config=True) |
|
145 | autoindent = CBool(True, config=True) | |
147 | automagic = CBool(True, config=True) |
|
146 | automagic = CBool(True, config=True) | |
148 | cache_size = Int(1000, config=True) |
|
147 | cache_size = Int(1000, config=True) | |
149 | color_info = CBool(True, config=True) |
|
148 | color_info = CBool(True, config=True) | |
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
149 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
151 | default_value=get_default_colors(), config=True) |
|
150 | default_value=get_default_colors(), config=True) | |
152 | debug = CBool(False, config=True) |
|
151 | debug = CBool(False, config=True) | |
153 | deep_reload = CBool(False, config=True) |
|
152 | deep_reload = CBool(False, config=True) | |
154 | displayhook_class = Type(DisplayHook) |
|
153 | displayhook_class = Type(DisplayHook) | |
155 | filename = Str("<ipython console>") |
|
154 | filename = Str("<ipython console>") | |
156 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
155 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
157 | logstart = CBool(False, config=True) |
|
156 | logstart = CBool(False, config=True) | |
158 | logfile = Str('', config=True) |
|
157 | logfile = Str('', config=True) | |
159 | logappend = Str('', config=True) |
|
158 | logappend = Str('', config=True) | |
160 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
159 | object_info_string_level = Enum((0,1,2), default_value=0, | |
161 | config=True) |
|
160 | config=True) | |
162 | pdb = CBool(False, config=True) |
|
161 | pdb = CBool(False, config=True) | |
163 | pprint = CBool(True, config=True) |
|
162 | pprint = CBool(True, config=True) | |
164 | profile = Str('', config=True) |
|
163 | profile = Str('', config=True) | |
165 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
164 | prompt_in1 = Str('In [\\#]: ', config=True) | |
166 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
165 | prompt_in2 = Str(' .\\D.: ', config=True) | |
167 | prompt_out = Str('Out[\\#]: ', config=True) |
|
166 | prompt_out = Str('Out[\\#]: ', config=True) | |
168 | prompts_pad_left = CBool(True, config=True) |
|
167 | prompts_pad_left = CBool(True, config=True) | |
169 | quiet = CBool(False, config=True) |
|
168 | quiet = CBool(False, config=True) | |
170 |
|
169 | |||
171 | # The readline stuff will eventually be moved to the terminal subclass |
|
170 | # The readline stuff will eventually be moved to the terminal subclass | |
172 | # but for now, we can't do that as readline is welded in everywhere. |
|
171 | # but for now, we can't do that as readline is welded in everywhere. | |
173 | readline_use = CBool(True, config=True) |
|
172 | readline_use = CBool(True, config=True) | |
174 | readline_merge_completions = CBool(True, config=True) |
|
173 | readline_merge_completions = CBool(True, config=True) | |
175 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
174 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
176 | readline_remove_delims = Str('-/~', config=True) |
|
175 | readline_remove_delims = Str('-/~', config=True) | |
177 | readline_parse_and_bind = List([ |
|
176 | readline_parse_and_bind = List([ | |
178 | 'tab: complete', |
|
177 | 'tab: complete', | |
179 | '"\C-l": clear-screen', |
|
178 | '"\C-l": clear-screen', | |
180 | 'set show-all-if-ambiguous on', |
|
179 | 'set show-all-if-ambiguous on', | |
181 | '"\C-o": tab-insert', |
|
180 | '"\C-o": tab-insert', | |
182 | '"\M-i": " "', |
|
181 | '"\M-i": " "', | |
183 | '"\M-o": "\d\d\d\d"', |
|
182 | '"\M-o": "\d\d\d\d"', | |
184 | '"\M-I": "\d\d\d\d"', |
|
183 | '"\M-I": "\d\d\d\d"', | |
185 | '"\C-r": reverse-search-history', |
|
184 | '"\C-r": reverse-search-history', | |
186 | '"\C-s": forward-search-history', |
|
185 | '"\C-s": forward-search-history', | |
187 | '"\C-p": history-search-backward', |
|
186 | '"\C-p": history-search-backward', | |
188 | '"\C-n": history-search-forward', |
|
187 | '"\C-n": history-search-forward', | |
189 | '"\e[A": history-search-backward', |
|
188 | '"\e[A": history-search-backward', | |
190 | '"\e[B": history-search-forward', |
|
189 | '"\e[B": history-search-forward', | |
191 | '"\C-k": kill-line', |
|
190 | '"\C-k": kill-line', | |
192 | '"\C-u": unix-line-discard', |
|
191 | '"\C-u": unix-line-discard', | |
193 | ], allow_none=False, config=True) |
|
192 | ], allow_none=False, config=True) | |
194 |
|
193 | |||
195 | # TODO: this part of prompt management should be moved to the frontends. |
|
194 | # TODO: this part of prompt management should be moved to the frontends. | |
196 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
195 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
197 | separate_in = SeparateStr('\n', config=True) |
|
196 | separate_in = SeparateStr('\n', config=True) | |
198 | separate_out = SeparateStr('\n', config=True) |
|
197 | separate_out = SeparateStr('\n', config=True) | |
199 | separate_out2 = SeparateStr('\n', config=True) |
|
198 | separate_out2 = SeparateStr('\n', config=True) | |
200 | system_header = Str('IPython system call: ', config=True) |
|
199 | system_header = Str('IPython system call: ', config=True) | |
201 | system_verbose = CBool(False, config=True) |
|
200 | system_verbose = CBool(False, config=True) | |
202 | wildcards_case_sensitive = CBool(True, config=True) |
|
201 | wildcards_case_sensitive = CBool(True, config=True) | |
203 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
202 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
204 | default_value='Context', config=True) |
|
203 | default_value='Context', config=True) | |
205 |
|
204 | |||
206 | # Subcomponents of InteractiveShell |
|
205 | # Subcomponents of InteractiveShell | |
207 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
206 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
208 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
207 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
209 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
208 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
210 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
209 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
211 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
210 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
212 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
211 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
213 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
212 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
214 |
|
213 | |||
215 | def __init__(self, config=None, ipython_dir=None, |
|
214 | def __init__(self, config=None, ipython_dir=None, | |
216 | user_ns=None, user_global_ns=None, |
|
215 | user_ns=None, user_global_ns=None, | |
217 | custom_exceptions=((),None)): |
|
216 | custom_exceptions=((),None)): | |
218 |
|
217 | |||
219 | # This is where traits with a config_key argument are updated |
|
218 | # This is where traits with a config_key argument are updated | |
220 | # from the values on config. |
|
219 | # from the values on config. | |
221 | super(InteractiveShell, self).__init__(config=config) |
|
220 | super(InteractiveShell, self).__init__(config=config) | |
222 |
|
221 | |||
223 | # These are relatively independent and stateless |
|
222 | # These are relatively independent and stateless | |
224 | self.init_ipython_dir(ipython_dir) |
|
223 | self.init_ipython_dir(ipython_dir) | |
225 | self.init_instance_attrs() |
|
224 | self.init_instance_attrs() | |
226 |
|
225 | |||
227 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
226 | # Create namespaces (user_ns, user_global_ns, etc.) | |
228 | self.init_create_namespaces(user_ns, user_global_ns) |
|
227 | self.init_create_namespaces(user_ns, user_global_ns) | |
229 | # This has to be done after init_create_namespaces because it uses |
|
228 | # This has to be done after init_create_namespaces because it uses | |
230 | # something in self.user_ns, but before init_sys_modules, which |
|
229 | # something in self.user_ns, but before init_sys_modules, which | |
231 | # is the first thing to modify sys. |
|
230 | # is the first thing to modify sys. | |
232 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
231 | # TODO: When we override sys.stdout and sys.stderr before this class | |
233 | # is created, we are saving the overridden ones here. Not sure if this |
|
232 | # is created, we are saving the overridden ones here. Not sure if this | |
234 | # is what we want to do. |
|
233 | # is what we want to do. | |
235 | self.save_sys_module_state() |
|
234 | self.save_sys_module_state() | |
236 | self.init_sys_modules() |
|
235 | self.init_sys_modules() | |
237 |
|
236 | |||
238 | self.init_history() |
|
237 | self.init_history() | |
239 | self.init_encoding() |
|
238 | self.init_encoding() | |
240 | self.init_prefilter() |
|
239 | self.init_prefilter() | |
241 |
|
240 | |||
242 | Magic.__init__(self, self) |
|
241 | Magic.__init__(self, self) | |
243 |
|
242 | |||
244 | self.init_syntax_highlighting() |
|
243 | self.init_syntax_highlighting() | |
245 | self.init_hooks() |
|
244 | self.init_hooks() | |
246 | self.init_pushd_popd_magic() |
|
245 | self.init_pushd_popd_magic() | |
247 | # self.init_traceback_handlers use to be here, but we moved it below |
|
246 | # self.init_traceback_handlers use to be here, but we moved it below | |
248 | # because it and init_io have to come after init_readline. |
|
247 | # because it and init_io have to come after init_readline. | |
249 | self.init_user_ns() |
|
248 | self.init_user_ns() | |
250 | self.init_logger() |
|
249 | self.init_logger() | |
251 | self.init_alias() |
|
250 | self.init_alias() | |
252 | self.init_builtins() |
|
251 | self.init_builtins() | |
253 |
|
252 | |||
254 | # pre_config_initialization |
|
253 | # pre_config_initialization | |
255 | self.init_shadow_hist() |
|
254 | self.init_shadow_hist() | |
256 |
|
255 | |||
257 | # The next section should contain averything that was in ipmaker. |
|
256 | # The next section should contain averything that was in ipmaker. | |
258 | self.init_logstart() |
|
257 | self.init_logstart() | |
259 |
|
258 | |||
260 | # The following was in post_config_initialization |
|
259 | # The following was in post_config_initialization | |
261 | self.init_inspector() |
|
260 | self.init_inspector() | |
262 | # init_readline() must come before init_io(), because init_io uses |
|
261 | # init_readline() must come before init_io(), because init_io uses | |
263 | # readline related things. |
|
262 | # readline related things. | |
264 | self.init_readline() |
|
263 | self.init_readline() | |
265 | # TODO: init_io() needs to happen before init_traceback handlers |
|
264 | # TODO: init_io() needs to happen before init_traceback handlers | |
266 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
265 | # because the traceback handlers hardcode the stdout/stderr streams. | |
267 | # This logic in in debugger.Pdb and should eventually be changed. |
|
266 | # This logic in in debugger.Pdb and should eventually be changed. | |
268 | self.init_io() |
|
267 | self.init_io() | |
269 | self.init_traceback_handlers(custom_exceptions) |
|
268 | self.init_traceback_handlers(custom_exceptions) | |
270 | self.init_prompts() |
|
269 | self.init_prompts() | |
271 | self.init_displayhook() |
|
270 | self.init_displayhook() | |
272 | self.init_reload_doctest() |
|
271 | self.init_reload_doctest() | |
273 | self.init_magics() |
|
272 | self.init_magics() | |
274 | self.init_pdb() |
|
273 | self.init_pdb() | |
275 | self.init_extension_manager() |
|
274 | self.init_extension_manager() | |
276 | self.init_plugin_manager() |
|
275 | self.init_plugin_manager() | |
277 | self.init_payload() |
|
276 | self.init_payload() | |
278 | self.hooks.late_startup_hook() |
|
277 | self.hooks.late_startup_hook() | |
279 |
|
278 | |||
280 | @classmethod |
|
279 | @classmethod | |
281 | def instance(cls, *args, **kwargs): |
|
280 | def instance(cls, *args, **kwargs): | |
282 | """Returns a global InteractiveShell instance.""" |
|
281 | """Returns a global InteractiveShell instance.""" | |
283 | if cls._instance is None: |
|
282 | if cls._instance is None: | |
284 | inst = cls(*args, **kwargs) |
|
283 | inst = cls(*args, **kwargs) | |
285 | # Now make sure that the instance will also be returned by |
|
284 | # Now make sure that the instance will also be returned by | |
286 | # the subclasses instance attribute. |
|
285 | # the subclasses instance attribute. | |
287 | for subclass in cls.mro(): |
|
286 | for subclass in cls.mro(): | |
288 | if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell): |
|
287 | if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell): | |
289 | subclass._instance = inst |
|
288 | subclass._instance = inst | |
290 | else: |
|
289 | else: | |
291 | break |
|
290 | break | |
292 | if isinstance(cls._instance, cls): |
|
291 | if isinstance(cls._instance, cls): | |
293 | return cls._instance |
|
292 | return cls._instance | |
294 | else: |
|
293 | else: | |
295 | raise MultipleInstanceError( |
|
294 | raise MultipleInstanceError( | |
296 | 'Multiple incompatible subclass instances of ' |
|
295 | 'Multiple incompatible subclass instances of ' | |
297 | 'InteractiveShell are being created.' |
|
296 | 'InteractiveShell are being created.' | |
298 | ) |
|
297 | ) | |
299 |
|
298 | |||
300 | @classmethod |
|
299 | @classmethod | |
301 | def initialized(cls): |
|
300 | def initialized(cls): | |
302 | return hasattr(cls, "_instance") |
|
301 | return hasattr(cls, "_instance") | |
303 |
|
302 | |||
304 | def get_ipython(self): |
|
303 | def get_ipython(self): | |
305 | """Return the currently running IPython instance.""" |
|
304 | """Return the currently running IPython instance.""" | |
306 | return self |
|
305 | return self | |
307 |
|
306 | |||
308 | #------------------------------------------------------------------------- |
|
307 | #------------------------------------------------------------------------- | |
309 | # Trait changed handlers |
|
308 | # Trait changed handlers | |
310 | #------------------------------------------------------------------------- |
|
309 | #------------------------------------------------------------------------- | |
311 |
|
310 | |||
312 | def _ipython_dir_changed(self, name, new): |
|
311 | def _ipython_dir_changed(self, name, new): | |
313 | if not os.path.isdir(new): |
|
312 | if not os.path.isdir(new): | |
314 | os.makedirs(new, mode = 0777) |
|
313 | os.makedirs(new, mode = 0777) | |
315 |
|
314 | |||
316 | def set_autoindent(self,value=None): |
|
315 | def set_autoindent(self,value=None): | |
317 | """Set the autoindent flag, checking for readline support. |
|
316 | """Set the autoindent flag, checking for readline support. | |
318 |
|
317 | |||
319 | If called with no arguments, it acts as a toggle.""" |
|
318 | If called with no arguments, it acts as a toggle.""" | |
320 |
|
319 | |||
321 | if not self.has_readline: |
|
320 | if not self.has_readline: | |
322 | if os.name == 'posix': |
|
321 | if os.name == 'posix': | |
323 | warn("The auto-indent feature requires the readline library") |
|
322 | warn("The auto-indent feature requires the readline library") | |
324 | self.autoindent = 0 |
|
323 | self.autoindent = 0 | |
325 | return |
|
324 | return | |
326 | if value is None: |
|
325 | if value is None: | |
327 | self.autoindent = not self.autoindent |
|
326 | self.autoindent = not self.autoindent | |
328 | else: |
|
327 | else: | |
329 | self.autoindent = value |
|
328 | self.autoindent = value | |
330 |
|
329 | |||
331 | #------------------------------------------------------------------------- |
|
330 | #------------------------------------------------------------------------- | |
332 | # init_* methods called by __init__ |
|
331 | # init_* methods called by __init__ | |
333 | #------------------------------------------------------------------------- |
|
332 | #------------------------------------------------------------------------- | |
334 |
|
333 | |||
335 | def init_ipython_dir(self, ipython_dir): |
|
334 | def init_ipython_dir(self, ipython_dir): | |
336 | if ipython_dir is not None: |
|
335 | if ipython_dir is not None: | |
337 | self.ipython_dir = ipython_dir |
|
336 | self.ipython_dir = ipython_dir | |
338 | self.config.Global.ipython_dir = self.ipython_dir |
|
337 | self.config.Global.ipython_dir = self.ipython_dir | |
339 | return |
|
338 | return | |
340 |
|
339 | |||
341 | if hasattr(self.config.Global, 'ipython_dir'): |
|
340 | if hasattr(self.config.Global, 'ipython_dir'): | |
342 | self.ipython_dir = self.config.Global.ipython_dir |
|
341 | self.ipython_dir = self.config.Global.ipython_dir | |
343 | else: |
|
342 | else: | |
344 | self.ipython_dir = get_ipython_dir() |
|
343 | self.ipython_dir = get_ipython_dir() | |
345 |
|
344 | |||
346 | # All children can just read this |
|
345 | # All children can just read this | |
347 | self.config.Global.ipython_dir = self.ipython_dir |
|
346 | self.config.Global.ipython_dir = self.ipython_dir | |
348 |
|
347 | |||
349 | def init_instance_attrs(self): |
|
348 | def init_instance_attrs(self): | |
350 | self.more = False |
|
349 | self.more = False | |
351 |
|
350 | |||
352 | # command compiler |
|
351 | # command compiler | |
353 | self.compile = codeop.CommandCompiler() |
|
352 | self.compile = codeop.CommandCompiler() | |
354 |
|
353 | |||
355 | # User input buffer |
|
354 | # User input buffer | |
356 | self.buffer = [] |
|
355 | self.buffer = [] | |
357 |
|
356 | |||
358 | # Make an empty namespace, which extension writers can rely on both |
|
357 | # Make an empty namespace, which extension writers can rely on both | |
359 | # existing and NEVER being used by ipython itself. This gives them a |
|
358 | # existing and NEVER being used by ipython itself. This gives them a | |
360 | # convenient location for storing additional information and state |
|
359 | # convenient location for storing additional information and state | |
361 | # their extensions may require, without fear of collisions with other |
|
360 | # their extensions may require, without fear of collisions with other | |
362 | # ipython names that may develop later. |
|
361 | # ipython names that may develop later. | |
363 | self.meta = Struct() |
|
362 | self.meta = Struct() | |
364 |
|
363 | |||
365 | # Object variable to store code object waiting execution. This is |
|
364 | # Object variable to store code object waiting execution. This is | |
366 | # used mainly by the multithreaded shells, but it can come in handy in |
|
365 | # used mainly by the multithreaded shells, but it can come in handy in | |
367 | # other situations. No need to use a Queue here, since it's a single |
|
366 | # other situations. No need to use a Queue here, since it's a single | |
368 | # item which gets cleared once run. |
|
367 | # item which gets cleared once run. | |
369 | self.code_to_run = None |
|
368 | self.code_to_run = None | |
370 |
|
369 | |||
371 | # Temporary files used for various purposes. Deleted at exit. |
|
370 | # Temporary files used for various purposes. Deleted at exit. | |
372 | self.tempfiles = [] |
|
371 | self.tempfiles = [] | |
373 |
|
372 | |||
374 | # Keep track of readline usage (later set by init_readline) |
|
373 | # Keep track of readline usage (later set by init_readline) | |
375 | self.has_readline = False |
|
374 | self.has_readline = False | |
376 |
|
375 | |||
377 | # keep track of where we started running (mainly for crash post-mortem) |
|
376 | # keep track of where we started running (mainly for crash post-mortem) | |
378 | # This is not being used anywhere currently. |
|
377 | # This is not being used anywhere currently. | |
379 | self.starting_dir = os.getcwd() |
|
378 | self.starting_dir = os.getcwd() | |
380 |
|
379 | |||
381 | # Indentation management |
|
380 | # Indentation management | |
382 | self.indent_current_nsp = 0 |
|
381 | self.indent_current_nsp = 0 | |
383 |
|
382 | |||
384 | def init_encoding(self): |
|
383 | def init_encoding(self): | |
385 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
384 | # Get system encoding at startup time. Certain terminals (like Emacs | |
386 | # under Win32 have it set to None, and we need to have a known valid |
|
385 | # under Win32 have it set to None, and we need to have a known valid | |
387 | # encoding to use in the raw_input() method |
|
386 | # encoding to use in the raw_input() method | |
388 | try: |
|
387 | try: | |
389 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
388 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
390 | except AttributeError: |
|
389 | except AttributeError: | |
391 | self.stdin_encoding = 'ascii' |
|
390 | self.stdin_encoding = 'ascii' | |
392 |
|
391 | |||
393 | def init_syntax_highlighting(self): |
|
392 | def init_syntax_highlighting(self): | |
394 | # Python source parser/formatter for syntax highlighting |
|
393 | # Python source parser/formatter for syntax highlighting | |
395 | pyformat = PyColorize.Parser().format |
|
394 | pyformat = PyColorize.Parser().format | |
396 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
395 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
397 |
|
396 | |||
398 | def init_pushd_popd_magic(self): |
|
397 | def init_pushd_popd_magic(self): | |
399 | # for pushd/popd management |
|
398 | # for pushd/popd management | |
400 | try: |
|
399 | try: | |
401 | self.home_dir = get_home_dir() |
|
400 | self.home_dir = get_home_dir() | |
402 | except HomeDirError, msg: |
|
401 | except HomeDirError, msg: | |
403 | fatal(msg) |
|
402 | fatal(msg) | |
404 |
|
403 | |||
405 | self.dir_stack = [] |
|
404 | self.dir_stack = [] | |
406 |
|
405 | |||
407 | def init_logger(self): |
|
406 | def init_logger(self): | |
408 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
407 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
409 | # local shortcut, this is used a LOT |
|
408 | # local shortcut, this is used a LOT | |
410 | self.log = self.logger.log |
|
409 | self.log = self.logger.log | |
411 |
|
410 | |||
412 | def init_logstart(self): |
|
411 | def init_logstart(self): | |
413 | if self.logappend: |
|
412 | if self.logappend: | |
414 | self.magic_logstart(self.logappend + ' append') |
|
413 | self.magic_logstart(self.logappend + ' append') | |
415 | elif self.logfile: |
|
414 | elif self.logfile: | |
416 | self.magic_logstart(self.logfile) |
|
415 | self.magic_logstart(self.logfile) | |
417 | elif self.logstart: |
|
416 | elif self.logstart: | |
418 | self.magic_logstart() |
|
417 | self.magic_logstart() | |
419 |
|
418 | |||
420 | def init_builtins(self): |
|
419 | def init_builtins(self): | |
421 | self.builtin_trap = BuiltinTrap(shell=self) |
|
420 | self.builtin_trap = BuiltinTrap(shell=self) | |
422 |
|
421 | |||
423 | def init_inspector(self): |
|
422 | def init_inspector(self): | |
424 | # Object inspector |
|
423 | # Object inspector | |
425 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
424 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
426 | PyColorize.ANSICodeColors, |
|
425 | PyColorize.ANSICodeColors, | |
427 | 'NoColor', |
|
426 | 'NoColor', | |
428 | self.object_info_string_level) |
|
427 | self.object_info_string_level) | |
429 |
|
428 | |||
430 | def init_io(self): |
|
429 | def init_io(self): | |
431 | import IPython.utils.io |
|
430 | import IPython.utils.io | |
432 | if sys.platform == 'win32' and self.has_readline: |
|
431 | if sys.platform == 'win32' and self.has_readline: | |
433 |
Term = |
|
432 | Term = io.IOTerm( | |
434 | cout=self.readline._outputfile,cerr=self.readline._outputfile |
|
433 | cout=self.readline._outputfile,cerr=self.readline._outputfile | |
435 | ) |
|
434 | ) | |
436 | else: |
|
435 | else: | |
437 |
Term = |
|
436 | Term = io.IOTerm() | |
438 |
|
|
437 | io.Term = Term | |
439 |
|
438 | |||
440 | def init_prompts(self): |
|
439 | def init_prompts(self): | |
441 | # TODO: This is a pass for now because the prompts are managed inside |
|
440 | # TODO: This is a pass for now because the prompts are managed inside | |
442 | # the DisplayHook. Once there is a separate prompt manager, this |
|
441 | # the DisplayHook. Once there is a separate prompt manager, this | |
443 | # will initialize that object and all prompt related information. |
|
442 | # will initialize that object and all prompt related information. | |
444 | pass |
|
443 | pass | |
445 |
|
444 | |||
446 | def init_displayhook(self): |
|
445 | def init_displayhook(self): | |
447 | # Initialize displayhook, set in/out prompts and printing system |
|
446 | # Initialize displayhook, set in/out prompts and printing system | |
448 | self.displayhook = self.displayhook_class( |
|
447 | self.displayhook = self.displayhook_class( | |
449 | shell=self, |
|
448 | shell=self, | |
450 | cache_size=self.cache_size, |
|
449 | cache_size=self.cache_size, | |
451 | input_sep = self.separate_in, |
|
450 | input_sep = self.separate_in, | |
452 | output_sep = self.separate_out, |
|
451 | output_sep = self.separate_out, | |
453 | output_sep2 = self.separate_out2, |
|
452 | output_sep2 = self.separate_out2, | |
454 | ps1 = self.prompt_in1, |
|
453 | ps1 = self.prompt_in1, | |
455 | ps2 = self.prompt_in2, |
|
454 | ps2 = self.prompt_in2, | |
456 | ps_out = self.prompt_out, |
|
455 | ps_out = self.prompt_out, | |
457 | pad_left = self.prompts_pad_left |
|
456 | pad_left = self.prompts_pad_left | |
458 | ) |
|
457 | ) | |
459 | # This is a context manager that installs/revmoes the displayhook at |
|
458 | # This is a context manager that installs/revmoes the displayhook at | |
460 | # the appropriate time. |
|
459 | # the appropriate time. | |
461 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
460 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
462 |
|
461 | |||
463 | def init_reload_doctest(self): |
|
462 | def init_reload_doctest(self): | |
464 | # Do a proper resetting of doctest, including the necessary displayhook |
|
463 | # Do a proper resetting of doctest, including the necessary displayhook | |
465 | # monkeypatching |
|
464 | # monkeypatching | |
466 | try: |
|
465 | try: | |
467 | doctest_reload() |
|
466 | doctest_reload() | |
468 | except ImportError: |
|
467 | except ImportError: | |
469 | warn("doctest module does not exist.") |
|
468 | warn("doctest module does not exist.") | |
470 |
|
469 | |||
471 | #------------------------------------------------------------------------- |
|
470 | #------------------------------------------------------------------------- | |
472 | # Things related to injections into the sys module |
|
471 | # Things related to injections into the sys module | |
473 | #------------------------------------------------------------------------- |
|
472 | #------------------------------------------------------------------------- | |
474 |
|
473 | |||
475 | def save_sys_module_state(self): |
|
474 | def save_sys_module_state(self): | |
476 | """Save the state of hooks in the sys module. |
|
475 | """Save the state of hooks in the sys module. | |
477 |
|
476 | |||
478 | This has to be called after self.user_ns is created. |
|
477 | This has to be called after self.user_ns is created. | |
479 | """ |
|
478 | """ | |
480 | self._orig_sys_module_state = {} |
|
479 | self._orig_sys_module_state = {} | |
481 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
480 | self._orig_sys_module_state['stdin'] = sys.stdin | |
482 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
481 | self._orig_sys_module_state['stdout'] = sys.stdout | |
483 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
482 | self._orig_sys_module_state['stderr'] = sys.stderr | |
484 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
483 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
485 | try: |
|
484 | try: | |
486 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
485 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
487 | except KeyError: |
|
486 | except KeyError: | |
488 | pass |
|
487 | pass | |
489 |
|
488 | |||
490 | def restore_sys_module_state(self): |
|
489 | def restore_sys_module_state(self): | |
491 | """Restore the state of the sys module.""" |
|
490 | """Restore the state of the sys module.""" | |
492 | try: |
|
491 | try: | |
493 | for k, v in self._orig_sys_module_state.items(): |
|
492 | for k, v in self._orig_sys_module_state.items(): | |
494 | setattr(sys, k, v) |
|
493 | setattr(sys, k, v) | |
495 | except AttributeError: |
|
494 | except AttributeError: | |
496 | pass |
|
495 | pass | |
497 | try: |
|
496 | try: | |
498 | delattr(sys, 'ipcompleter') |
|
497 | delattr(sys, 'ipcompleter') | |
499 | except AttributeError: |
|
498 | except AttributeError: | |
500 | pass |
|
499 | pass | |
501 | # Reset what what done in self.init_sys_modules |
|
500 | # Reset what what done in self.init_sys_modules | |
502 | try: |
|
501 | try: | |
503 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
502 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
504 | except (AttributeError, KeyError): |
|
503 | except (AttributeError, KeyError): | |
505 | pass |
|
504 | pass | |
506 |
|
505 | |||
507 | #------------------------------------------------------------------------- |
|
506 | #------------------------------------------------------------------------- | |
508 | # Things related to hooks |
|
507 | # Things related to hooks | |
509 | #------------------------------------------------------------------------- |
|
508 | #------------------------------------------------------------------------- | |
510 |
|
509 | |||
511 | def init_hooks(self): |
|
510 | def init_hooks(self): | |
512 | # hooks holds pointers used for user-side customizations |
|
511 | # hooks holds pointers used for user-side customizations | |
513 | self.hooks = Struct() |
|
512 | self.hooks = Struct() | |
514 |
|
513 | |||
515 | self.strdispatchers = {} |
|
514 | self.strdispatchers = {} | |
516 |
|
515 | |||
517 | # Set all default hooks, defined in the IPython.hooks module. |
|
516 | # Set all default hooks, defined in the IPython.hooks module. | |
518 | hooks = IPython.core.hooks |
|
517 | hooks = IPython.core.hooks | |
519 | for hook_name in hooks.__all__: |
|
518 | for hook_name in hooks.__all__: | |
520 | # default hooks have priority 100, i.e. low; user hooks should have |
|
519 | # default hooks have priority 100, i.e. low; user hooks should have | |
521 | # 0-100 priority |
|
520 | # 0-100 priority | |
522 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
521 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
523 |
|
522 | |||
524 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
523 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
525 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
524 | """set_hook(name,hook) -> sets an internal IPython hook. | |
526 |
|
525 | |||
527 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
526 | IPython exposes some of its internal API as user-modifiable hooks. By | |
528 | adding your function to one of these hooks, you can modify IPython's |
|
527 | adding your function to one of these hooks, you can modify IPython's | |
529 | behavior to call at runtime your own routines.""" |
|
528 | behavior to call at runtime your own routines.""" | |
530 |
|
529 | |||
531 | # At some point in the future, this should validate the hook before it |
|
530 | # At some point in the future, this should validate the hook before it | |
532 | # accepts it. Probably at least check that the hook takes the number |
|
531 | # accepts it. Probably at least check that the hook takes the number | |
533 | # of args it's supposed to. |
|
532 | # of args it's supposed to. | |
534 |
|
533 | |||
535 | f = new.instancemethod(hook,self,self.__class__) |
|
534 | f = new.instancemethod(hook,self,self.__class__) | |
536 |
|
535 | |||
537 | # check if the hook is for strdispatcher first |
|
536 | # check if the hook is for strdispatcher first | |
538 | if str_key is not None: |
|
537 | if str_key is not None: | |
539 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
538 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
540 | sdp.add_s(str_key, f, priority ) |
|
539 | sdp.add_s(str_key, f, priority ) | |
541 | self.strdispatchers[name] = sdp |
|
540 | self.strdispatchers[name] = sdp | |
542 | return |
|
541 | return | |
543 | if re_key is not None: |
|
542 | if re_key is not None: | |
544 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
543 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
545 | sdp.add_re(re.compile(re_key), f, priority ) |
|
544 | sdp.add_re(re.compile(re_key), f, priority ) | |
546 | self.strdispatchers[name] = sdp |
|
545 | self.strdispatchers[name] = sdp | |
547 | return |
|
546 | return | |
548 |
|
547 | |||
549 | dp = getattr(self.hooks, name, None) |
|
548 | dp = getattr(self.hooks, name, None) | |
550 | if name not in IPython.core.hooks.__all__: |
|
549 | if name not in IPython.core.hooks.__all__: | |
551 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
550 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
552 | if not dp: |
|
551 | if not dp: | |
553 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
552 | dp = IPython.core.hooks.CommandChainDispatcher() | |
554 |
|
553 | |||
555 | try: |
|
554 | try: | |
556 | dp.add(f,priority) |
|
555 | dp.add(f,priority) | |
557 | except AttributeError: |
|
556 | except AttributeError: | |
558 | # it was not commandchain, plain old func - replace |
|
557 | # it was not commandchain, plain old func - replace | |
559 | dp = f |
|
558 | dp = f | |
560 |
|
559 | |||
561 | setattr(self.hooks,name, dp) |
|
560 | setattr(self.hooks,name, dp) | |
562 |
|
561 | |||
563 | #------------------------------------------------------------------------- |
|
562 | #------------------------------------------------------------------------- | |
564 | # Things related to the "main" module |
|
563 | # Things related to the "main" module | |
565 | #------------------------------------------------------------------------- |
|
564 | #------------------------------------------------------------------------- | |
566 |
|
565 | |||
567 | def new_main_mod(self,ns=None): |
|
566 | def new_main_mod(self,ns=None): | |
568 | """Return a new 'main' module object for user code execution. |
|
567 | """Return a new 'main' module object for user code execution. | |
569 | """ |
|
568 | """ | |
570 | main_mod = self._user_main_module |
|
569 | main_mod = self._user_main_module | |
571 | init_fakemod_dict(main_mod,ns) |
|
570 | init_fakemod_dict(main_mod,ns) | |
572 | return main_mod |
|
571 | return main_mod | |
573 |
|
572 | |||
574 | def cache_main_mod(self,ns,fname): |
|
573 | def cache_main_mod(self,ns,fname): | |
575 | """Cache a main module's namespace. |
|
574 | """Cache a main module's namespace. | |
576 |
|
575 | |||
577 | When scripts are executed via %run, we must keep a reference to the |
|
576 | When scripts are executed via %run, we must keep a reference to the | |
578 | namespace of their __main__ module (a FakeModule instance) around so |
|
577 | namespace of their __main__ module (a FakeModule instance) around so | |
579 | that Python doesn't clear it, rendering objects defined therein |
|
578 | that Python doesn't clear it, rendering objects defined therein | |
580 | useless. |
|
579 | useless. | |
581 |
|
580 | |||
582 | This method keeps said reference in a private dict, keyed by the |
|
581 | This method keeps said reference in a private dict, keyed by the | |
583 | absolute path of the module object (which corresponds to the script |
|
582 | absolute path of the module object (which corresponds to the script | |
584 | path). This way, for multiple executions of the same script we only |
|
583 | path). This way, for multiple executions of the same script we only | |
585 | keep one copy of the namespace (the last one), thus preventing memory |
|
584 | keep one copy of the namespace (the last one), thus preventing memory | |
586 | leaks from old references while allowing the objects from the last |
|
585 | leaks from old references while allowing the objects from the last | |
587 | execution to be accessible. |
|
586 | execution to be accessible. | |
588 |
|
587 | |||
589 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
588 | Note: we can not allow the actual FakeModule instances to be deleted, | |
590 | because of how Python tears down modules (it hard-sets all their |
|
589 | because of how Python tears down modules (it hard-sets all their | |
591 | references to None without regard for reference counts). This method |
|
590 | references to None without regard for reference counts). This method | |
592 | must therefore make a *copy* of the given namespace, to allow the |
|
591 | must therefore make a *copy* of the given namespace, to allow the | |
593 | original module's __dict__ to be cleared and reused. |
|
592 | original module's __dict__ to be cleared and reused. | |
594 |
|
593 | |||
595 |
|
594 | |||
596 | Parameters |
|
595 | Parameters | |
597 | ---------- |
|
596 | ---------- | |
598 | ns : a namespace (a dict, typically) |
|
597 | ns : a namespace (a dict, typically) | |
599 |
|
598 | |||
600 | fname : str |
|
599 | fname : str | |
601 | Filename associated with the namespace. |
|
600 | Filename associated with the namespace. | |
602 |
|
601 | |||
603 | Examples |
|
602 | Examples | |
604 | -------- |
|
603 | -------- | |
605 |
|
604 | |||
606 | In [10]: import IPython |
|
605 | In [10]: import IPython | |
607 |
|
606 | |||
608 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
607 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
609 |
|
608 | |||
610 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
609 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
611 | Out[12]: True |
|
610 | Out[12]: True | |
612 | """ |
|
611 | """ | |
613 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
612 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
614 |
|
613 | |||
615 | def clear_main_mod_cache(self): |
|
614 | def clear_main_mod_cache(self): | |
616 | """Clear the cache of main modules. |
|
615 | """Clear the cache of main modules. | |
617 |
|
616 | |||
618 | Mainly for use by utilities like %reset. |
|
617 | Mainly for use by utilities like %reset. | |
619 |
|
618 | |||
620 | Examples |
|
619 | Examples | |
621 | -------- |
|
620 | -------- | |
622 |
|
621 | |||
623 | In [15]: import IPython |
|
622 | In [15]: import IPython | |
624 |
|
623 | |||
625 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
624 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
626 |
|
625 | |||
627 | In [17]: len(_ip._main_ns_cache) > 0 |
|
626 | In [17]: len(_ip._main_ns_cache) > 0 | |
628 | Out[17]: True |
|
627 | Out[17]: True | |
629 |
|
628 | |||
630 | In [18]: _ip.clear_main_mod_cache() |
|
629 | In [18]: _ip.clear_main_mod_cache() | |
631 |
|
630 | |||
632 | In [19]: len(_ip._main_ns_cache) == 0 |
|
631 | In [19]: len(_ip._main_ns_cache) == 0 | |
633 | Out[19]: True |
|
632 | Out[19]: True | |
634 | """ |
|
633 | """ | |
635 | self._main_ns_cache.clear() |
|
634 | self._main_ns_cache.clear() | |
636 |
|
635 | |||
637 | #------------------------------------------------------------------------- |
|
636 | #------------------------------------------------------------------------- | |
638 | # Things related to debugging |
|
637 | # Things related to debugging | |
639 | #------------------------------------------------------------------------- |
|
638 | #------------------------------------------------------------------------- | |
640 |
|
639 | |||
641 | def init_pdb(self): |
|
640 | def init_pdb(self): | |
642 | # Set calling of pdb on exceptions |
|
641 | # Set calling of pdb on exceptions | |
643 | # self.call_pdb is a property |
|
642 | # self.call_pdb is a property | |
644 | self.call_pdb = self.pdb |
|
643 | self.call_pdb = self.pdb | |
645 |
|
644 | |||
646 | def _get_call_pdb(self): |
|
645 | def _get_call_pdb(self): | |
647 | return self._call_pdb |
|
646 | return self._call_pdb | |
648 |
|
647 | |||
649 | def _set_call_pdb(self,val): |
|
648 | def _set_call_pdb(self,val): | |
650 |
|
649 | |||
651 | if val not in (0,1,False,True): |
|
650 | if val not in (0,1,False,True): | |
652 | raise ValueError,'new call_pdb value must be boolean' |
|
651 | raise ValueError,'new call_pdb value must be boolean' | |
653 |
|
652 | |||
654 | # store value in instance |
|
653 | # store value in instance | |
655 | self._call_pdb = val |
|
654 | self._call_pdb = val | |
656 |
|
655 | |||
657 | # notify the actual exception handlers |
|
656 | # notify the actual exception handlers | |
658 | self.InteractiveTB.call_pdb = val |
|
657 | self.InteractiveTB.call_pdb = val | |
659 |
|
658 | |||
660 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
659 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
661 | 'Control auto-activation of pdb at exceptions') |
|
660 | 'Control auto-activation of pdb at exceptions') | |
662 |
|
661 | |||
663 | def debugger(self,force=False): |
|
662 | def debugger(self,force=False): | |
664 | """Call the pydb/pdb debugger. |
|
663 | """Call the pydb/pdb debugger. | |
665 |
|
664 | |||
666 | Keywords: |
|
665 | Keywords: | |
667 |
|
666 | |||
668 | - force(False): by default, this routine checks the instance call_pdb |
|
667 | - force(False): by default, this routine checks the instance call_pdb | |
669 | flag and does not actually invoke the debugger if the flag is false. |
|
668 | flag and does not actually invoke the debugger if the flag is false. | |
670 | The 'force' option forces the debugger to activate even if the flag |
|
669 | The 'force' option forces the debugger to activate even if the flag | |
671 | is false. |
|
670 | is false. | |
672 | """ |
|
671 | """ | |
673 |
|
672 | |||
674 | if not (force or self.call_pdb): |
|
673 | if not (force or self.call_pdb): | |
675 | return |
|
674 | return | |
676 |
|
675 | |||
677 | if not hasattr(sys,'last_traceback'): |
|
676 | if not hasattr(sys,'last_traceback'): | |
678 | error('No traceback has been produced, nothing to debug.') |
|
677 | error('No traceback has been produced, nothing to debug.') | |
679 | return |
|
678 | return | |
680 |
|
679 | |||
681 | # use pydb if available |
|
680 | # use pydb if available | |
682 | if debugger.has_pydb: |
|
681 | if debugger.has_pydb: | |
683 | from pydb import pm |
|
682 | from pydb import pm | |
684 | else: |
|
683 | else: | |
685 | # fallback to our internal debugger |
|
684 | # fallback to our internal debugger | |
686 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
685 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
687 | self.history_saving_wrapper(pm)() |
|
686 | self.history_saving_wrapper(pm)() | |
688 |
|
687 | |||
689 | #------------------------------------------------------------------------- |
|
688 | #------------------------------------------------------------------------- | |
690 | # Things related to IPython's various namespaces |
|
689 | # Things related to IPython's various namespaces | |
691 | #------------------------------------------------------------------------- |
|
690 | #------------------------------------------------------------------------- | |
692 |
|
691 | |||
693 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
692 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
694 | # Create the namespace where the user will operate. user_ns is |
|
693 | # Create the namespace where the user will operate. user_ns is | |
695 | # normally the only one used, and it is passed to the exec calls as |
|
694 | # normally the only one used, and it is passed to the exec calls as | |
696 | # the locals argument. But we do carry a user_global_ns namespace |
|
695 | # the locals argument. But we do carry a user_global_ns namespace | |
697 | # given as the exec 'globals' argument, This is useful in embedding |
|
696 | # given as the exec 'globals' argument, This is useful in embedding | |
698 | # situations where the ipython shell opens in a context where the |
|
697 | # situations where the ipython shell opens in a context where the | |
699 | # distinction between locals and globals is meaningful. For |
|
698 | # distinction between locals and globals is meaningful. For | |
700 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
699 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
701 |
|
700 | |||
702 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
701 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
703 | # level as a dict instead of a module. This is a manual fix, but I |
|
702 | # level as a dict instead of a module. This is a manual fix, but I | |
704 | # should really track down where the problem is coming from. Alex |
|
703 | # should really track down where the problem is coming from. Alex | |
705 | # Schmolck reported this problem first. |
|
704 | # Schmolck reported this problem first. | |
706 |
|
705 | |||
707 | # A useful post by Alex Martelli on this topic: |
|
706 | # A useful post by Alex Martelli on this topic: | |
708 | # Re: inconsistent value from __builtins__ |
|
707 | # Re: inconsistent value from __builtins__ | |
709 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
708 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
710 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
709 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
711 | # Gruppen: comp.lang.python |
|
710 | # Gruppen: comp.lang.python | |
712 |
|
711 | |||
713 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
712 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
714 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
713 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
715 | # > <type 'dict'> |
|
714 | # > <type 'dict'> | |
716 | # > >>> print type(__builtins__) |
|
715 | # > >>> print type(__builtins__) | |
717 | # > <type 'module'> |
|
716 | # > <type 'module'> | |
718 | # > Is this difference in return value intentional? |
|
717 | # > Is this difference in return value intentional? | |
719 |
|
718 | |||
720 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
719 | # Well, it's documented that '__builtins__' can be either a dictionary | |
721 | # or a module, and it's been that way for a long time. Whether it's |
|
720 | # or a module, and it's been that way for a long time. Whether it's | |
722 | # intentional (or sensible), I don't know. In any case, the idea is |
|
721 | # intentional (or sensible), I don't know. In any case, the idea is | |
723 | # that if you need to access the built-in namespace directly, you |
|
722 | # that if you need to access the built-in namespace directly, you | |
724 | # should start with "import __builtin__" (note, no 's') which will |
|
723 | # should start with "import __builtin__" (note, no 's') which will | |
725 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
724 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
726 |
|
725 | |||
727 | # These routines return properly built dicts as needed by the rest of |
|
726 | # These routines return properly built dicts as needed by the rest of | |
728 | # the code, and can also be used by extension writers to generate |
|
727 | # the code, and can also be used by extension writers to generate | |
729 | # properly initialized namespaces. |
|
728 | # properly initialized namespaces. | |
730 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns) |
|
729 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns) | |
731 |
|
730 | |||
732 | # Assign namespaces |
|
731 | # Assign namespaces | |
733 | # This is the namespace where all normal user variables live |
|
732 | # This is the namespace where all normal user variables live | |
734 | self.user_ns = user_ns |
|
733 | self.user_ns = user_ns | |
735 | self.user_global_ns = user_global_ns |
|
734 | self.user_global_ns = user_global_ns | |
736 |
|
735 | |||
737 | # An auxiliary namespace that checks what parts of the user_ns were |
|
736 | # An auxiliary namespace that checks what parts of the user_ns were | |
738 | # loaded at startup, so we can list later only variables defined in |
|
737 | # loaded at startup, so we can list later only variables defined in | |
739 | # actual interactive use. Since it is always a subset of user_ns, it |
|
738 | # actual interactive use. Since it is always a subset of user_ns, it | |
740 | # doesn't need to be separately tracked in the ns_table. |
|
739 | # doesn't need to be separately tracked in the ns_table. | |
741 | self.user_ns_hidden = {} |
|
740 | self.user_ns_hidden = {} | |
742 |
|
741 | |||
743 | # A namespace to keep track of internal data structures to prevent |
|
742 | # A namespace to keep track of internal data structures to prevent | |
744 | # them from cluttering user-visible stuff. Will be updated later |
|
743 | # them from cluttering user-visible stuff. Will be updated later | |
745 | self.internal_ns = {} |
|
744 | self.internal_ns = {} | |
746 |
|
745 | |||
747 | # Now that FakeModule produces a real module, we've run into a nasty |
|
746 | # Now that FakeModule produces a real module, we've run into a nasty | |
748 | # problem: after script execution (via %run), the module where the user |
|
747 | # problem: after script execution (via %run), the module where the user | |
749 | # code ran is deleted. Now that this object is a true module (needed |
|
748 | # code ran is deleted. Now that this object is a true module (needed | |
750 | # so docetst and other tools work correctly), the Python module |
|
749 | # so docetst and other tools work correctly), the Python module | |
751 | # teardown mechanism runs over it, and sets to None every variable |
|
750 | # teardown mechanism runs over it, and sets to None every variable | |
752 | # present in that module. Top-level references to objects from the |
|
751 | # present in that module. Top-level references to objects from the | |
753 | # script survive, because the user_ns is updated with them. However, |
|
752 | # script survive, because the user_ns is updated with them. However, | |
754 | # calling functions defined in the script that use other things from |
|
753 | # calling functions defined in the script that use other things from | |
755 | # the script will fail, because the function's closure had references |
|
754 | # the script will fail, because the function's closure had references | |
756 | # to the original objects, which are now all None. So we must protect |
|
755 | # to the original objects, which are now all None. So we must protect | |
757 | # these modules from deletion by keeping a cache. |
|
756 | # these modules from deletion by keeping a cache. | |
758 | # |
|
757 | # | |
759 | # To avoid keeping stale modules around (we only need the one from the |
|
758 | # To avoid keeping stale modules around (we only need the one from the | |
760 | # last run), we use a dict keyed with the full path to the script, so |
|
759 | # last run), we use a dict keyed with the full path to the script, so | |
761 | # only the last version of the module is held in the cache. Note, |
|
760 | # only the last version of the module is held in the cache. Note, | |
762 | # however, that we must cache the module *namespace contents* (their |
|
761 | # however, that we must cache the module *namespace contents* (their | |
763 | # __dict__). Because if we try to cache the actual modules, old ones |
|
762 | # __dict__). Because if we try to cache the actual modules, old ones | |
764 | # (uncached) could be destroyed while still holding references (such as |
|
763 | # (uncached) could be destroyed while still holding references (such as | |
765 | # those held by GUI objects that tend to be long-lived)> |
|
764 | # those held by GUI objects that tend to be long-lived)> | |
766 | # |
|
765 | # | |
767 | # The %reset command will flush this cache. See the cache_main_mod() |
|
766 | # The %reset command will flush this cache. See the cache_main_mod() | |
768 | # and clear_main_mod_cache() methods for details on use. |
|
767 | # and clear_main_mod_cache() methods for details on use. | |
769 |
|
768 | |||
770 | # This is the cache used for 'main' namespaces |
|
769 | # This is the cache used for 'main' namespaces | |
771 | self._main_ns_cache = {} |
|
770 | self._main_ns_cache = {} | |
772 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
771 | # And this is the single instance of FakeModule whose __dict__ we keep | |
773 | # copying and clearing for reuse on each %run |
|
772 | # copying and clearing for reuse on each %run | |
774 | self._user_main_module = FakeModule() |
|
773 | self._user_main_module = FakeModule() | |
775 |
|
774 | |||
776 | # A table holding all the namespaces IPython deals with, so that |
|
775 | # A table holding all the namespaces IPython deals with, so that | |
777 | # introspection facilities can search easily. |
|
776 | # introspection facilities can search easily. | |
778 | self.ns_table = {'user':user_ns, |
|
777 | self.ns_table = {'user':user_ns, | |
779 | 'user_global':user_global_ns, |
|
778 | 'user_global':user_global_ns, | |
780 | 'internal':self.internal_ns, |
|
779 | 'internal':self.internal_ns, | |
781 | 'builtin':__builtin__.__dict__ |
|
780 | 'builtin':__builtin__.__dict__ | |
782 | } |
|
781 | } | |
783 |
|
782 | |||
784 | # Similarly, track all namespaces where references can be held and that |
|
783 | # Similarly, track all namespaces where references can be held and that | |
785 | # we can safely clear (so it can NOT include builtin). This one can be |
|
784 | # we can safely clear (so it can NOT include builtin). This one can be | |
786 | # a simple list. |
|
785 | # a simple list. | |
787 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, |
|
786 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, | |
788 | self.internal_ns, self._main_ns_cache ] |
|
787 | self.internal_ns, self._main_ns_cache ] | |
789 |
|
788 | |||
790 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
789 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
791 | """Return a valid local and global user interactive namespaces. |
|
790 | """Return a valid local and global user interactive namespaces. | |
792 |
|
791 | |||
793 | This builds a dict with the minimal information needed to operate as a |
|
792 | This builds a dict with the minimal information needed to operate as a | |
794 | valid IPython user namespace, which you can pass to the various |
|
793 | valid IPython user namespace, which you can pass to the various | |
795 | embedding classes in ipython. The default implementation returns the |
|
794 | embedding classes in ipython. The default implementation returns the | |
796 | same dict for both the locals and the globals to allow functions to |
|
795 | same dict for both the locals and the globals to allow functions to | |
797 | refer to variables in the namespace. Customized implementations can |
|
796 | refer to variables in the namespace. Customized implementations can | |
798 | return different dicts. The locals dictionary can actually be anything |
|
797 | return different dicts. The locals dictionary can actually be anything | |
799 | following the basic mapping protocol of a dict, but the globals dict |
|
798 | following the basic mapping protocol of a dict, but the globals dict | |
800 | must be a true dict, not even a subclass. It is recommended that any |
|
799 | must be a true dict, not even a subclass. It is recommended that any | |
801 | custom object for the locals namespace synchronize with the globals |
|
800 | custom object for the locals namespace synchronize with the globals | |
802 | dict somehow. |
|
801 | dict somehow. | |
803 |
|
802 | |||
804 | Raises TypeError if the provided globals namespace is not a true dict. |
|
803 | Raises TypeError if the provided globals namespace is not a true dict. | |
805 |
|
804 | |||
806 | Parameters |
|
805 | Parameters | |
807 | ---------- |
|
806 | ---------- | |
808 | user_ns : dict-like, optional |
|
807 | user_ns : dict-like, optional | |
809 | The current user namespace. The items in this namespace should |
|
808 | The current user namespace. The items in this namespace should | |
810 | be included in the output. If None, an appropriate blank |
|
809 | be included in the output. If None, an appropriate blank | |
811 | namespace should be created. |
|
810 | namespace should be created. | |
812 | user_global_ns : dict, optional |
|
811 | user_global_ns : dict, optional | |
813 | The current user global namespace. The items in this namespace |
|
812 | The current user global namespace. The items in this namespace | |
814 | should be included in the output. If None, an appropriate |
|
813 | should be included in the output. If None, an appropriate | |
815 | blank namespace should be created. |
|
814 | blank namespace should be created. | |
816 |
|
815 | |||
817 | Returns |
|
816 | Returns | |
818 | ------- |
|
817 | ------- | |
819 | A pair of dictionary-like object to be used as the local namespace |
|
818 | A pair of dictionary-like object to be used as the local namespace | |
820 | of the interpreter and a dict to be used as the global namespace. |
|
819 | of the interpreter and a dict to be used as the global namespace. | |
821 | """ |
|
820 | """ | |
822 |
|
821 | |||
823 |
|
822 | |||
824 | # We must ensure that __builtin__ (without the final 's') is always |
|
823 | # We must ensure that __builtin__ (without the final 's') is always | |
825 | # available and pointing to the __builtin__ *module*. For more details: |
|
824 | # available and pointing to the __builtin__ *module*. For more details: | |
826 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
825 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
827 |
|
826 | |||
828 | if user_ns is None: |
|
827 | if user_ns is None: | |
829 | # Set __name__ to __main__ to better match the behavior of the |
|
828 | # Set __name__ to __main__ to better match the behavior of the | |
830 | # normal interpreter. |
|
829 | # normal interpreter. | |
831 | user_ns = {'__name__' :'__main__', |
|
830 | user_ns = {'__name__' :'__main__', | |
832 | '__builtin__' : __builtin__, |
|
831 | '__builtin__' : __builtin__, | |
833 | '__builtins__' : __builtin__, |
|
832 | '__builtins__' : __builtin__, | |
834 | } |
|
833 | } | |
835 | else: |
|
834 | else: | |
836 | user_ns.setdefault('__name__','__main__') |
|
835 | user_ns.setdefault('__name__','__main__') | |
837 | user_ns.setdefault('__builtin__',__builtin__) |
|
836 | user_ns.setdefault('__builtin__',__builtin__) | |
838 | user_ns.setdefault('__builtins__',__builtin__) |
|
837 | user_ns.setdefault('__builtins__',__builtin__) | |
839 |
|
838 | |||
840 | if user_global_ns is None: |
|
839 | if user_global_ns is None: | |
841 | user_global_ns = user_ns |
|
840 | user_global_ns = user_ns | |
842 | if type(user_global_ns) is not dict: |
|
841 | if type(user_global_ns) is not dict: | |
843 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
842 | raise TypeError("user_global_ns must be a true dict; got %r" | |
844 | % type(user_global_ns)) |
|
843 | % type(user_global_ns)) | |
845 |
|
844 | |||
846 | return user_ns, user_global_ns |
|
845 | return user_ns, user_global_ns | |
847 |
|
846 | |||
848 | def init_sys_modules(self): |
|
847 | def init_sys_modules(self): | |
849 | # We need to insert into sys.modules something that looks like a |
|
848 | # We need to insert into sys.modules something that looks like a | |
850 | # module but which accesses the IPython namespace, for shelve and |
|
849 | # module but which accesses the IPython namespace, for shelve and | |
851 | # pickle to work interactively. Normally they rely on getting |
|
850 | # pickle to work interactively. Normally they rely on getting | |
852 | # everything out of __main__, but for embedding purposes each IPython |
|
851 | # everything out of __main__, but for embedding purposes each IPython | |
853 | # instance has its own private namespace, so we can't go shoving |
|
852 | # instance has its own private namespace, so we can't go shoving | |
854 | # everything into __main__. |
|
853 | # everything into __main__. | |
855 |
|
854 | |||
856 | # note, however, that we should only do this for non-embedded |
|
855 | # note, however, that we should only do this for non-embedded | |
857 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
856 | # ipythons, which really mimic the __main__.__dict__ with their own | |
858 | # namespace. Embedded instances, on the other hand, should not do |
|
857 | # namespace. Embedded instances, on the other hand, should not do | |
859 | # this because they need to manage the user local/global namespaces |
|
858 | # this because they need to manage the user local/global namespaces | |
860 | # only, but they live within a 'normal' __main__ (meaning, they |
|
859 | # only, but they live within a 'normal' __main__ (meaning, they | |
861 | # shouldn't overtake the execution environment of the script they're |
|
860 | # shouldn't overtake the execution environment of the script they're | |
862 | # embedded in). |
|
861 | # embedded in). | |
863 |
|
862 | |||
864 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
863 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
865 |
|
864 | |||
866 | try: |
|
865 | try: | |
867 | main_name = self.user_ns['__name__'] |
|
866 | main_name = self.user_ns['__name__'] | |
868 | except KeyError: |
|
867 | except KeyError: | |
869 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
868 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
870 | else: |
|
869 | else: | |
871 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
870 | sys.modules[main_name] = FakeModule(self.user_ns) | |
872 |
|
871 | |||
873 | def init_user_ns(self): |
|
872 | def init_user_ns(self): | |
874 | """Initialize all user-visible namespaces to their minimum defaults. |
|
873 | """Initialize all user-visible namespaces to their minimum defaults. | |
875 |
|
874 | |||
876 | Certain history lists are also initialized here, as they effectively |
|
875 | Certain history lists are also initialized here, as they effectively | |
877 | act as user namespaces. |
|
876 | act as user namespaces. | |
878 |
|
877 | |||
879 | Notes |
|
878 | Notes | |
880 | ----- |
|
879 | ----- | |
881 | All data structures here are only filled in, they are NOT reset by this |
|
880 | All data structures here are only filled in, they are NOT reset by this | |
882 | method. If they were not empty before, data will simply be added to |
|
881 | method. If they were not empty before, data will simply be added to | |
883 | therm. |
|
882 | therm. | |
884 | """ |
|
883 | """ | |
885 | # This function works in two parts: first we put a few things in |
|
884 | # This function works in two parts: first we put a few things in | |
886 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
885 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
887 | # initial variables aren't shown by %who. After the sync, we add the |
|
886 | # initial variables aren't shown by %who. After the sync, we add the | |
888 | # rest of what we *do* want the user to see with %who even on a new |
|
887 | # rest of what we *do* want the user to see with %who even on a new | |
889 | # session (probably nothing, so theye really only see their own stuff) |
|
888 | # session (probably nothing, so theye really only see their own stuff) | |
890 |
|
889 | |||
891 | # The user dict must *always* have a __builtin__ reference to the |
|
890 | # The user dict must *always* have a __builtin__ reference to the | |
892 | # Python standard __builtin__ namespace, which must be imported. |
|
891 | # Python standard __builtin__ namespace, which must be imported. | |
893 | # This is so that certain operations in prompt evaluation can be |
|
892 | # This is so that certain operations in prompt evaluation can be | |
894 | # reliably executed with builtins. Note that we can NOT use |
|
893 | # reliably executed with builtins. Note that we can NOT use | |
895 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
894 | # __builtins__ (note the 's'), because that can either be a dict or a | |
896 | # module, and can even mutate at runtime, depending on the context |
|
895 | # module, and can even mutate at runtime, depending on the context | |
897 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
896 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
898 | # always a module object, though it must be explicitly imported. |
|
897 | # always a module object, though it must be explicitly imported. | |
899 |
|
898 | |||
900 | # For more details: |
|
899 | # For more details: | |
901 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
900 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
902 | ns = dict(__builtin__ = __builtin__) |
|
901 | ns = dict(__builtin__ = __builtin__) | |
903 |
|
902 | |||
904 | # Put 'help' in the user namespace |
|
903 | # Put 'help' in the user namespace | |
905 | try: |
|
904 | try: | |
906 | from site import _Helper |
|
905 | from site import _Helper | |
907 | ns['help'] = _Helper() |
|
906 | ns['help'] = _Helper() | |
908 | except ImportError: |
|
907 | except ImportError: | |
909 | warn('help() not available - check site.py') |
|
908 | warn('help() not available - check site.py') | |
910 |
|
909 | |||
911 | # make global variables for user access to the histories |
|
910 | # make global variables for user access to the histories | |
912 | ns['_ih'] = self.input_hist |
|
911 | ns['_ih'] = self.input_hist | |
913 | ns['_oh'] = self.output_hist |
|
912 | ns['_oh'] = self.output_hist | |
914 | ns['_dh'] = self.dir_hist |
|
913 | ns['_dh'] = self.dir_hist | |
915 |
|
914 | |||
916 | ns['_sh'] = shadowns |
|
915 | ns['_sh'] = shadowns | |
917 |
|
916 | |||
918 | # user aliases to input and output histories. These shouldn't show up |
|
917 | # user aliases to input and output histories. These shouldn't show up | |
919 | # in %who, as they can have very large reprs. |
|
918 | # in %who, as they can have very large reprs. | |
920 | ns['In'] = self.input_hist |
|
919 | ns['In'] = self.input_hist | |
921 | ns['Out'] = self.output_hist |
|
920 | ns['Out'] = self.output_hist | |
922 |
|
921 | |||
923 | # Store myself as the public api!!! |
|
922 | # Store myself as the public api!!! | |
924 | ns['get_ipython'] = self.get_ipython |
|
923 | ns['get_ipython'] = self.get_ipython | |
925 |
|
924 | |||
926 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
925 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
927 | # by %who |
|
926 | # by %who | |
928 | self.user_ns_hidden.update(ns) |
|
927 | self.user_ns_hidden.update(ns) | |
929 |
|
928 | |||
930 | # Anything put into ns now would show up in %who. Think twice before |
|
929 | # Anything put into ns now would show up in %who. Think twice before | |
931 | # putting anything here, as we really want %who to show the user their |
|
930 | # putting anything here, as we really want %who to show the user their | |
932 | # stuff, not our variables. |
|
931 | # stuff, not our variables. | |
933 |
|
932 | |||
934 | # Finally, update the real user's namespace |
|
933 | # Finally, update the real user's namespace | |
935 | self.user_ns.update(ns) |
|
934 | self.user_ns.update(ns) | |
936 |
|
935 | |||
937 |
|
936 | |||
938 | def reset(self): |
|
937 | def reset(self): | |
939 | """Clear all internal namespaces. |
|
938 | """Clear all internal namespaces. | |
940 |
|
939 | |||
941 | Note that this is much more aggressive than %reset, since it clears |
|
940 | Note that this is much more aggressive than %reset, since it clears | |
942 | fully all namespaces, as well as all input/output lists. |
|
941 | fully all namespaces, as well as all input/output lists. | |
943 | """ |
|
942 | """ | |
944 | for ns in self.ns_refs_table: |
|
943 | for ns in self.ns_refs_table: | |
945 | ns.clear() |
|
944 | ns.clear() | |
946 |
|
945 | |||
947 | self.alias_manager.clear_aliases() |
|
946 | self.alias_manager.clear_aliases() | |
948 |
|
947 | |||
949 | # Clear input and output histories |
|
948 | # Clear input and output histories | |
950 | self.input_hist[:] = [] |
|
949 | self.input_hist[:] = [] | |
951 | self.input_hist_raw[:] = [] |
|
950 | self.input_hist_raw[:] = [] | |
952 | self.output_hist.clear() |
|
951 | self.output_hist.clear() | |
953 |
|
952 | |||
954 | # Restore the user namespaces to minimal usability |
|
953 | # Restore the user namespaces to minimal usability | |
955 | self.init_user_ns() |
|
954 | self.init_user_ns() | |
956 |
|
955 | |||
957 | # Restore the default and user aliases |
|
956 | # Restore the default and user aliases | |
958 | self.alias_manager.init_aliases() |
|
957 | self.alias_manager.init_aliases() | |
959 |
|
958 | |||
960 | def reset_selective(self, regex=None): |
|
959 | def reset_selective(self, regex=None): | |
961 | """Clear selective variables from internal namespaces based on a specified regular expression. |
|
960 | """Clear selective variables from internal namespaces based on a specified regular expression. | |
962 |
|
961 | |||
963 | Parameters |
|
962 | Parameters | |
964 | ---------- |
|
963 | ---------- | |
965 | regex : string or compiled pattern, optional |
|
964 | regex : string or compiled pattern, optional | |
966 | A regular expression pattern that will be used in searching variable names in the users |
|
965 | A regular expression pattern that will be used in searching variable names in the users | |
967 | namespaces. |
|
966 | namespaces. | |
968 | """ |
|
967 | """ | |
969 | if regex is not None: |
|
968 | if regex is not None: | |
970 | try: |
|
969 | try: | |
971 | m = re.compile(regex) |
|
970 | m = re.compile(regex) | |
972 | except TypeError: |
|
971 | except TypeError: | |
973 | raise TypeError('regex must be a string or compiled pattern') |
|
972 | raise TypeError('regex must be a string or compiled pattern') | |
974 | # Search for keys in each namespace that match the given regex |
|
973 | # Search for keys in each namespace that match the given regex | |
975 | # If a match is found, delete the key/value pair. |
|
974 | # If a match is found, delete the key/value pair. | |
976 | for ns in self.ns_refs_table: |
|
975 | for ns in self.ns_refs_table: | |
977 | for var in ns: |
|
976 | for var in ns: | |
978 | if m.search(var): |
|
977 | if m.search(var): | |
979 | del ns[var] |
|
978 | del ns[var] | |
980 |
|
979 | |||
981 | def push(self, variables, interactive=True): |
|
980 | def push(self, variables, interactive=True): | |
982 | """Inject a group of variables into the IPython user namespace. |
|
981 | """Inject a group of variables into the IPython user namespace. | |
983 |
|
982 | |||
984 | Parameters |
|
983 | Parameters | |
985 | ---------- |
|
984 | ---------- | |
986 | variables : dict, str or list/tuple of str |
|
985 | variables : dict, str or list/tuple of str | |
987 | The variables to inject into the user's namespace. If a dict, |
|
986 | The variables to inject into the user's namespace. If a dict, | |
988 | a simple update is done. If a str, the string is assumed to |
|
987 | a simple update is done. If a str, the string is assumed to | |
989 | have variable names separated by spaces. A list/tuple of str |
|
988 | have variable names separated by spaces. A list/tuple of str | |
990 | can also be used to give the variable names. If just the variable |
|
989 | can also be used to give the variable names. If just the variable | |
991 | names are give (list/tuple/str) then the variable values looked |
|
990 | names are give (list/tuple/str) then the variable values looked | |
992 | up in the callers frame. |
|
991 | up in the callers frame. | |
993 | interactive : bool |
|
992 | interactive : bool | |
994 | If True (default), the variables will be listed with the ``who`` |
|
993 | If True (default), the variables will be listed with the ``who`` | |
995 | magic. |
|
994 | magic. | |
996 | """ |
|
995 | """ | |
997 | vdict = None |
|
996 | vdict = None | |
998 |
|
997 | |||
999 | # We need a dict of name/value pairs to do namespace updates. |
|
998 | # We need a dict of name/value pairs to do namespace updates. | |
1000 | if isinstance(variables, dict): |
|
999 | if isinstance(variables, dict): | |
1001 | vdict = variables |
|
1000 | vdict = variables | |
1002 | elif isinstance(variables, (basestring, list, tuple)): |
|
1001 | elif isinstance(variables, (basestring, list, tuple)): | |
1003 | if isinstance(variables, basestring): |
|
1002 | if isinstance(variables, basestring): | |
1004 | vlist = variables.split() |
|
1003 | vlist = variables.split() | |
1005 | else: |
|
1004 | else: | |
1006 | vlist = variables |
|
1005 | vlist = variables | |
1007 | vdict = {} |
|
1006 | vdict = {} | |
1008 | cf = sys._getframe(1) |
|
1007 | cf = sys._getframe(1) | |
1009 | for name in vlist: |
|
1008 | for name in vlist: | |
1010 | try: |
|
1009 | try: | |
1011 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1010 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1012 | except: |
|
1011 | except: | |
1013 | print ('Could not get variable %s from %s' % |
|
1012 | print ('Could not get variable %s from %s' % | |
1014 | (name,cf.f_code.co_name)) |
|
1013 | (name,cf.f_code.co_name)) | |
1015 | else: |
|
1014 | else: | |
1016 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1015 | raise ValueError('variables must be a dict/str/list/tuple') | |
1017 |
|
1016 | |||
1018 | # Propagate variables to user namespace |
|
1017 | # Propagate variables to user namespace | |
1019 | self.user_ns.update(vdict) |
|
1018 | self.user_ns.update(vdict) | |
1020 |
|
1019 | |||
1021 | # And configure interactive visibility |
|
1020 | # And configure interactive visibility | |
1022 | config_ns = self.user_ns_hidden |
|
1021 | config_ns = self.user_ns_hidden | |
1023 | if interactive: |
|
1022 | if interactive: | |
1024 | for name, val in vdict.iteritems(): |
|
1023 | for name, val in vdict.iteritems(): | |
1025 | config_ns.pop(name, None) |
|
1024 | config_ns.pop(name, None) | |
1026 | else: |
|
1025 | else: | |
1027 | for name,val in vdict.iteritems(): |
|
1026 | for name,val in vdict.iteritems(): | |
1028 | config_ns[name] = val |
|
1027 | config_ns[name] = val | |
1029 |
|
1028 | |||
1030 | #------------------------------------------------------------------------- |
|
1029 | #------------------------------------------------------------------------- | |
1031 | # Things related to history management |
|
1030 | # Things related to history management | |
1032 | #------------------------------------------------------------------------- |
|
1031 | #------------------------------------------------------------------------- | |
1033 |
|
1032 | |||
1034 | def init_history(self): |
|
1033 | def init_history(self): | |
1035 | # List of input with multi-line handling. |
|
1034 | # List of input with multi-line handling. | |
1036 | self.input_hist = InputList() |
|
1035 | self.input_hist = InputList() | |
1037 | # This one will hold the 'raw' input history, without any |
|
1036 | # This one will hold the 'raw' input history, without any | |
1038 | # pre-processing. This will allow users to retrieve the input just as |
|
1037 | # pre-processing. This will allow users to retrieve the input just as | |
1039 | # it was exactly typed in by the user, with %hist -r. |
|
1038 | # it was exactly typed in by the user, with %hist -r. | |
1040 | self.input_hist_raw = InputList() |
|
1039 | self.input_hist_raw = InputList() | |
1041 |
|
1040 | |||
1042 | # list of visited directories |
|
1041 | # list of visited directories | |
1043 | try: |
|
1042 | try: | |
1044 | self.dir_hist = [os.getcwd()] |
|
1043 | self.dir_hist = [os.getcwd()] | |
1045 | except OSError: |
|
1044 | except OSError: | |
1046 | self.dir_hist = [] |
|
1045 | self.dir_hist = [] | |
1047 |
|
1046 | |||
1048 | # dict of output history |
|
1047 | # dict of output history | |
1049 | self.output_hist = {} |
|
1048 | self.output_hist = {} | |
1050 |
|
1049 | |||
1051 | # Now the history file |
|
1050 | # Now the history file | |
1052 | if self.profile: |
|
1051 | if self.profile: | |
1053 | histfname = 'history-%s' % self.profile |
|
1052 | histfname = 'history-%s' % self.profile | |
1054 | else: |
|
1053 | else: | |
1055 | histfname = 'history' |
|
1054 | histfname = 'history' | |
1056 | self.histfile = os.path.join(self.ipython_dir, histfname) |
|
1055 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
1057 |
|
1056 | |||
1058 | # Fill the history zero entry, user counter starts at 1 |
|
1057 | # Fill the history zero entry, user counter starts at 1 | |
1059 | self.input_hist.append('\n') |
|
1058 | self.input_hist.append('\n') | |
1060 | self.input_hist_raw.append('\n') |
|
1059 | self.input_hist_raw.append('\n') | |
1061 |
|
1060 | |||
1062 | def init_shadow_hist(self): |
|
1061 | def init_shadow_hist(self): | |
1063 | try: |
|
1062 | try: | |
1064 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1063 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1065 | except exceptions.UnicodeDecodeError: |
|
1064 | except exceptions.UnicodeDecodeError: | |
1066 | print "Your ipython_dir can't be decoded to unicode!" |
|
1065 | print "Your ipython_dir can't be decoded to unicode!" | |
1067 | print "Please set HOME environment variable to something that" |
|
1066 | print "Please set HOME environment variable to something that" | |
1068 | print r"only has ASCII characters, e.g. c:\home" |
|
1067 | print r"only has ASCII characters, e.g. c:\home" | |
1069 | print "Now it is", self.ipython_dir |
|
1068 | print "Now it is", self.ipython_dir | |
1070 | sys.exit() |
|
1069 | sys.exit() | |
1071 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1070 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1072 |
|
1071 | |||
1073 | def savehist(self): |
|
1072 | def savehist(self): | |
1074 | """Save input history to a file (via readline library).""" |
|
1073 | """Save input history to a file (via readline library).""" | |
1075 |
|
1074 | |||
1076 | try: |
|
1075 | try: | |
1077 | self.readline.write_history_file(self.histfile) |
|
1076 | self.readline.write_history_file(self.histfile) | |
1078 | except: |
|
1077 | except: | |
1079 | print 'Unable to save IPython command history to file: ' + \ |
|
1078 | print 'Unable to save IPython command history to file: ' + \ | |
1080 | `self.histfile` |
|
1079 | `self.histfile` | |
1081 |
|
1080 | |||
1082 | def reloadhist(self): |
|
1081 | def reloadhist(self): | |
1083 | """Reload the input history from disk file.""" |
|
1082 | """Reload the input history from disk file.""" | |
1084 |
|
1083 | |||
1085 | try: |
|
1084 | try: | |
1086 | self.readline.clear_history() |
|
1085 | self.readline.clear_history() | |
1087 | self.readline.read_history_file(self.shell.histfile) |
|
1086 | self.readline.read_history_file(self.shell.histfile) | |
1088 | except AttributeError: |
|
1087 | except AttributeError: | |
1089 | pass |
|
1088 | pass | |
1090 |
|
1089 | |||
1091 | def history_saving_wrapper(self, func): |
|
1090 | def history_saving_wrapper(self, func): | |
1092 | """ Wrap func for readline history saving |
|
1091 | """ Wrap func for readline history saving | |
1093 |
|
1092 | |||
1094 | Convert func into callable that saves & restores |
|
1093 | Convert func into callable that saves & restores | |
1095 | history around the call """ |
|
1094 | history around the call """ | |
1096 |
|
1095 | |||
1097 | if self.has_readline: |
|
1096 | if self.has_readline: | |
1098 | from IPython.utils import rlineimpl as readline |
|
1097 | from IPython.utils import rlineimpl as readline | |
1099 | else: |
|
1098 | else: | |
1100 | return func |
|
1099 | return func | |
1101 |
|
1100 | |||
1102 | def wrapper(): |
|
1101 | def wrapper(): | |
1103 | self.savehist() |
|
1102 | self.savehist() | |
1104 | try: |
|
1103 | try: | |
1105 | func() |
|
1104 | func() | |
1106 | finally: |
|
1105 | finally: | |
1107 | readline.read_history_file(self.histfile) |
|
1106 | readline.read_history_file(self.histfile) | |
1108 | return wrapper |
|
1107 | return wrapper | |
1109 |
|
1108 | |||
1110 | def get_history(self, index=None, raw=False, output=True): |
|
1109 | def get_history(self, index=None, raw=False, output=True): | |
1111 | """Get the history list. |
|
1110 | """Get the history list. | |
1112 |
|
1111 | |||
1113 | Get the input and output history. |
|
1112 | Get the input and output history. | |
1114 |
|
1113 | |||
1115 | Parameters |
|
1114 | Parameters | |
1116 | ---------- |
|
1115 | ---------- | |
1117 | index : n or (n1, n2) or None |
|
1116 | index : n or (n1, n2) or None | |
1118 | If n, then the last entries. If a tuple, then all in |
|
1117 | If n, then the last entries. If a tuple, then all in | |
1119 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
1118 | range(n1, n2). If None, then all entries. Raises IndexError if | |
1120 | the format of index is incorrect. |
|
1119 | the format of index is incorrect. | |
1121 | raw : bool |
|
1120 | raw : bool | |
1122 | If True, return the raw input. |
|
1121 | If True, return the raw input. | |
1123 | output : bool |
|
1122 | output : bool | |
1124 | If True, then return the output as well. |
|
1123 | If True, then return the output as well. | |
1125 |
|
1124 | |||
1126 | Returns |
|
1125 | Returns | |
1127 | ------- |
|
1126 | ------- | |
1128 | If output is True, then return a dict of tuples, keyed by the prompt |
|
1127 | If output is True, then return a dict of tuples, keyed by the prompt | |
1129 | numbers and with values of (input, output). If output is False, then |
|
1128 | numbers and with values of (input, output). If output is False, then | |
1130 | a dict, keyed by the prompt number with the values of input. Raises |
|
1129 | a dict, keyed by the prompt number with the values of input. Raises | |
1131 | IndexError if no history is found. |
|
1130 | IndexError if no history is found. | |
1132 | """ |
|
1131 | """ | |
1133 | if raw: |
|
1132 | if raw: | |
1134 | input_hist = self.input_hist_raw |
|
1133 | input_hist = self.input_hist_raw | |
1135 | else: |
|
1134 | else: | |
1136 | input_hist = self.input_hist |
|
1135 | input_hist = self.input_hist | |
1137 | if output: |
|
1136 | if output: | |
1138 | output_hist = self.user_ns['Out'] |
|
1137 | output_hist = self.user_ns['Out'] | |
1139 | n = len(input_hist) |
|
1138 | n = len(input_hist) | |
1140 | if index is None: |
|
1139 | if index is None: | |
1141 | start=0; stop=n |
|
1140 | start=0; stop=n | |
1142 | elif isinstance(index, int): |
|
1141 | elif isinstance(index, int): | |
1143 | start=n-index; stop=n |
|
1142 | start=n-index; stop=n | |
1144 | elif isinstance(index, tuple) and len(index) == 2: |
|
1143 | elif isinstance(index, tuple) and len(index) == 2: | |
1145 | start=index[0]; stop=index[1] |
|
1144 | start=index[0]; stop=index[1] | |
1146 | else: |
|
1145 | else: | |
1147 | raise IndexError('Not a valid index for the input history: %r' % index) |
|
1146 | raise IndexError('Not a valid index for the input history: %r' % index) | |
1148 | hist = {} |
|
1147 | hist = {} | |
1149 | for i in range(start, stop): |
|
1148 | for i in range(start, stop): | |
1150 | if output: |
|
1149 | if output: | |
1151 | hist[i] = (input_hist[i], output_hist.get(i)) |
|
1150 | hist[i] = (input_hist[i], output_hist.get(i)) | |
1152 | else: |
|
1151 | else: | |
1153 | hist[i] = input_hist[i] |
|
1152 | hist[i] = input_hist[i] | |
1154 | if len(hist)==0: |
|
1153 | if len(hist)==0: | |
1155 | raise IndexError('No history for range of indices: %r' % index) |
|
1154 | raise IndexError('No history for range of indices: %r' % index) | |
1156 | return hist |
|
1155 | return hist | |
1157 |
|
1156 | |||
1158 | #------------------------------------------------------------------------- |
|
1157 | #------------------------------------------------------------------------- | |
1159 | # Things related to exception handling and tracebacks (not debugging) |
|
1158 | # Things related to exception handling and tracebacks (not debugging) | |
1160 | #------------------------------------------------------------------------- |
|
1159 | #------------------------------------------------------------------------- | |
1161 |
|
1160 | |||
1162 | def init_traceback_handlers(self, custom_exceptions): |
|
1161 | def init_traceback_handlers(self, custom_exceptions): | |
1163 | # Syntax error handler. |
|
1162 | # Syntax error handler. | |
1164 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1163 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1165 |
|
1164 | |||
1166 | # The interactive one is initialized with an offset, meaning we always |
|
1165 | # The interactive one is initialized with an offset, meaning we always | |
1167 | # want to remove the topmost item in the traceback, which is our own |
|
1166 | # want to remove the topmost item in the traceback, which is our own | |
1168 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1167 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1169 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1168 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1170 | color_scheme='NoColor', |
|
1169 | color_scheme='NoColor', | |
1171 | tb_offset = 1) |
|
1170 | tb_offset = 1) | |
1172 |
|
1171 | |||
1173 | # The instance will store a pointer to the system-wide exception hook, |
|
1172 | # The instance will store a pointer to the system-wide exception hook, | |
1174 | # so that runtime code (such as magics) can access it. This is because |
|
1173 | # so that runtime code (such as magics) can access it. This is because | |
1175 | # during the read-eval loop, it may get temporarily overwritten. |
|
1174 | # during the read-eval loop, it may get temporarily overwritten. | |
1176 | self.sys_excepthook = sys.excepthook |
|
1175 | self.sys_excepthook = sys.excepthook | |
1177 |
|
1176 | |||
1178 | # and add any custom exception handlers the user may have specified |
|
1177 | # and add any custom exception handlers the user may have specified | |
1179 | self.set_custom_exc(*custom_exceptions) |
|
1178 | self.set_custom_exc(*custom_exceptions) | |
1180 |
|
1179 | |||
1181 | # Set the exception mode |
|
1180 | # Set the exception mode | |
1182 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1181 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1183 |
|
1182 | |||
1184 | def set_custom_exc(self,exc_tuple,handler): |
|
1183 | def set_custom_exc(self, exc_tuple, handler): | |
1185 | """set_custom_exc(exc_tuple,handler) |
|
1184 | """set_custom_exc(exc_tuple,handler) | |
1186 |
|
1185 | |||
1187 | Set a custom exception handler, which will be called if any of the |
|
1186 | Set a custom exception handler, which will be called if any of the | |
1188 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1187 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1189 | runcode() method. |
|
1188 | runcode() method. | |
1190 |
|
1189 | |||
1191 | Inputs: |
|
1190 | Inputs: | |
1192 |
|
1191 | |||
1193 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1192 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1194 | handler for. It is very important that you use a tuple, and NOT A |
|
1193 | handler for. It is very important that you use a tuple, and NOT A | |
1195 | LIST here, because of the way Python's except statement works. If |
|
1194 | LIST here, because of the way Python's except statement works. If | |
1196 | you only want to trap a single exception, use a singleton tuple: |
|
1195 | you only want to trap a single exception, use a singleton tuple: | |
1197 |
|
1196 | |||
1198 | exc_tuple == (MyCustomException,) |
|
1197 | exc_tuple == (MyCustomException,) | |
1199 |
|
1198 | |||
1200 | - handler: this must be defined as a function with the following |
|
1199 | - handler: this must be defined as a function with the following | |
1201 | basic interface: def my_handler(self,etype,value,tb). |
|
1200 | basic interface:: | |
|
1201 | ||||
|
1202 | def my_handler(self, etype, value, tb, tb_offset=None) | |||
|
1203 | ... | |||
|
1204 | # The return value must be | |||
|
1205 | return structured_traceback | |||
1202 |
|
1206 | |||
1203 | This will be made into an instance method (via new.instancemethod) |
|
1207 | This will be made into an instance method (via new.instancemethod) | |
1204 | of IPython itself, and it will be called if any of the exceptions |
|
1208 | of IPython itself, and it will be called if any of the exceptions | |
1205 | listed in the exc_tuple are caught. If the handler is None, an |
|
1209 | listed in the exc_tuple are caught. If the handler is None, an | |
1206 | internal basic one is used, which just prints basic info. |
|
1210 | internal basic one is used, which just prints basic info. | |
1207 |
|
1211 | |||
1208 | WARNING: by putting in your own exception handler into IPython's main |
|
1212 | WARNING: by putting in your own exception handler into IPython's main | |
1209 | execution loop, you run a very good chance of nasty crashes. This |
|
1213 | execution loop, you run a very good chance of nasty crashes. This | |
1210 | facility should only be used if you really know what you are doing.""" |
|
1214 | facility should only be used if you really know what you are doing.""" | |
1211 |
|
1215 | |||
1212 | assert type(exc_tuple)==type(()) , \ |
|
1216 | assert type(exc_tuple)==type(()) , \ | |
1213 | "The custom exceptions must be given AS A TUPLE." |
|
1217 | "The custom exceptions must be given AS A TUPLE." | |
1214 |
|
1218 | |||
1215 | def dummy_handler(self,etype,value,tb): |
|
1219 | def dummy_handler(self,etype,value,tb): | |
1216 | print '*** Simple custom exception handler ***' |
|
1220 | print '*** Simple custom exception handler ***' | |
1217 | print 'Exception type :',etype |
|
1221 | print 'Exception type :',etype | |
1218 | print 'Exception value:',value |
|
1222 | print 'Exception value:',value | |
1219 | print 'Traceback :',tb |
|
1223 | print 'Traceback :',tb | |
1220 | print 'Source code :','\n'.join(self.buffer) |
|
1224 | print 'Source code :','\n'.join(self.buffer) | |
1221 |
|
1225 | |||
1222 | if handler is None: handler = dummy_handler |
|
1226 | if handler is None: handler = dummy_handler | |
1223 |
|
1227 | |||
1224 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1228 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1225 | self.custom_exceptions = exc_tuple |
|
1229 | self.custom_exceptions = exc_tuple | |
1226 |
|
1230 | |||
1227 | def excepthook(self, etype, value, tb): |
|
1231 | def excepthook(self, etype, value, tb): | |
1228 | """One more defense for GUI apps that call sys.excepthook. |
|
1232 | """One more defense for GUI apps that call sys.excepthook. | |
1229 |
|
1233 | |||
1230 | GUI frameworks like wxPython trap exceptions and call |
|
1234 | GUI frameworks like wxPython trap exceptions and call | |
1231 | sys.excepthook themselves. I guess this is a feature that |
|
1235 | sys.excepthook themselves. I guess this is a feature that | |
1232 | enables them to keep running after exceptions that would |
|
1236 | enables them to keep running after exceptions that would | |
1233 | otherwise kill their mainloop. This is a bother for IPython |
|
1237 | otherwise kill their mainloop. This is a bother for IPython | |
1234 | which excepts to catch all of the program exceptions with a try: |
|
1238 | which excepts to catch all of the program exceptions with a try: | |
1235 | except: statement. |
|
1239 | except: statement. | |
1236 |
|
1240 | |||
1237 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1241 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1238 | any app directly invokes sys.excepthook, it will look to the user like |
|
1242 | any app directly invokes sys.excepthook, it will look to the user like | |
1239 | IPython crashed. In order to work around this, we can disable the |
|
1243 | IPython crashed. In order to work around this, we can disable the | |
1240 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1244 | CrashHandler and replace it with this excepthook instead, which prints a | |
1241 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1245 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1242 | call sys.excepthook will generate a regular-looking exception from |
|
1246 | call sys.excepthook will generate a regular-looking exception from | |
1243 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1247 | IPython, and the CrashHandler will only be triggered by real IPython | |
1244 | crashes. |
|
1248 | crashes. | |
1245 |
|
1249 | |||
1246 | This hook should be used sparingly, only in places which are not likely |
|
1250 | This hook should be used sparingly, only in places which are not likely | |
1247 | to be true IPython errors. |
|
1251 | to be true IPython errors. | |
1248 | """ |
|
1252 | """ | |
1249 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1253 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1250 |
|
1254 | |||
1251 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1255 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1252 | exception_only=False): |
|
1256 | exception_only=False): | |
1253 | """Display the exception that just occurred. |
|
1257 | """Display the exception that just occurred. | |
1254 |
|
1258 | |||
1255 | If nothing is known about the exception, this is the method which |
|
1259 | If nothing is known about the exception, this is the method which | |
1256 | should be used throughout the code for presenting user tracebacks, |
|
1260 | should be used throughout the code for presenting user tracebacks, | |
1257 | rather than directly invoking the InteractiveTB object. |
|
1261 | rather than directly invoking the InteractiveTB object. | |
1258 |
|
1262 | |||
1259 | A specific showsyntaxerror() also exists, but this method can take |
|
1263 | A specific showsyntaxerror() also exists, but this method can take | |
1260 | care of calling it if needed, so unless you are explicitly catching a |
|
1264 | care of calling it if needed, so unless you are explicitly catching a | |
1261 | SyntaxError exception, don't try to analyze the stack manually and |
|
1265 | SyntaxError exception, don't try to analyze the stack manually and | |
1262 | simply call this method.""" |
|
1266 | simply call this method.""" | |
1263 |
|
1267 | |||
1264 | try: |
|
1268 | try: | |
1265 | if exc_tuple is None: |
|
1269 | if exc_tuple is None: | |
1266 | etype, value, tb = sys.exc_info() |
|
1270 | etype, value, tb = sys.exc_info() | |
1267 | else: |
|
1271 | else: | |
1268 | etype, value, tb = exc_tuple |
|
1272 | etype, value, tb = exc_tuple | |
1269 |
|
1273 | |||
1270 | if etype is None: |
|
1274 | if etype is None: | |
1271 | if hasattr(sys, 'last_type'): |
|
1275 | if hasattr(sys, 'last_type'): | |
1272 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1276 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1273 | sys.last_traceback |
|
1277 | sys.last_traceback | |
1274 | else: |
|
1278 | else: | |
1275 | self.write('No traceback available to show.\n') |
|
1279 | self.write_err('No traceback available to show.\n') | |
1276 | return |
|
1280 | return | |
1277 |
|
1281 | |||
1278 | if etype is SyntaxError: |
|
1282 | if etype is SyntaxError: | |
1279 | # Though this won't be called by syntax errors in the input |
|
1283 | # Though this won't be called by syntax errors in the input | |
1280 | # line, there may be SyntaxError cases whith imported code. |
|
1284 | # line, there may be SyntaxError cases whith imported code. | |
1281 | self.showsyntaxerror(filename) |
|
1285 | self.showsyntaxerror(filename) | |
1282 | elif etype is UsageError: |
|
1286 | elif etype is UsageError: | |
1283 | print "UsageError:", value |
|
1287 | print "UsageError:", value | |
1284 | else: |
|
1288 | else: | |
1285 | # WARNING: these variables are somewhat deprecated and not |
|
1289 | # WARNING: these variables are somewhat deprecated and not | |
1286 | # necessarily safe to use in a threaded environment, but tools |
|
1290 | # necessarily safe to use in a threaded environment, but tools | |
1287 | # like pdb depend on their existence, so let's set them. If we |
|
1291 | # like pdb depend on their existence, so let's set them. If we | |
1288 | # find problems in the field, we'll need to revisit their use. |
|
1292 | # find problems in the field, we'll need to revisit their use. | |
1289 | sys.last_type = etype |
|
1293 | sys.last_type = etype | |
1290 | sys.last_value = value |
|
1294 | sys.last_value = value | |
1291 | sys.last_traceback = tb |
|
1295 | sys.last_traceback = tb | |
1292 |
|
1296 | |||
1293 | if etype in self.custom_exceptions: |
|
1297 | if etype in self.custom_exceptions: | |
1294 | self.CustomTB(etype,value,tb) |
|
1298 | # FIXME: Old custom traceback objects may just return a | |
|
1299 | # string, in that case we just put it into a list | |||
|
1300 | stb = self.CustomTB(etype, value, tb, tb_offset) | |||
|
1301 | if isinstance(ctb, basestring): | |||
|
1302 | stb = [stb] | |||
1295 | else: |
|
1303 | else: | |
1296 | if exception_only: |
|
1304 | if exception_only: | |
1297 |
|
|
1305 | stb = ['An exception has occurred, use %tb to see ' | |
1298 |
'full traceback.' |
|
1306 | 'the full traceback.'] | |
1299 | print m |
|
1307 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1300 | self.InteractiveTB.show_exception_only(etype, value) |
|
1308 | value)) | |
1301 | else: |
|
1309 | else: | |
1302 |
self.InteractiveTB(etype, |
|
1310 | stb = self.InteractiveTB.structured_traceback(etype, | |
|
1311 | value, tb, tb_offset=tb_offset) | |||
|
1312 | # FIXME: the pdb calling should be done by us, not by | |||
|
1313 | # the code computing the traceback. | |||
1303 | if self.InteractiveTB.call_pdb: |
|
1314 | if self.InteractiveTB.call_pdb: | |
1304 | # pdb mucks up readline, fix it back |
|
1315 | # pdb mucks up readline, fix it back | |
1305 | self.set_completer() |
|
1316 | self.set_completer() | |
1306 |
|
1317 | |||
|
1318 | # Actually show the traceback | |||
|
1319 | self._showtraceback(etype, value, stb) | |||
|
1320 | ||||
1307 | except KeyboardInterrupt: |
|
1321 | except KeyboardInterrupt: | |
1308 |
self.write("\nKeyboardInterrupt\n") |
|
1322 | self.write_err("\nKeyboardInterrupt\n") | |
1309 |
|
1323 | |||
|
1324 | def _showtraceback(self, etype, evalue, stb): | |||
|
1325 | """Actually show a traceback. | |||
|
1326 | ||||
|
1327 | Subclasses may override this method to put the traceback on a different | |||
|
1328 | place, like a side channel. | |||
|
1329 | """ | |||
|
1330 | self.write_err('\n'.join(stb)) | |||
1310 |
|
1331 | |||
1311 | def showsyntaxerror(self, filename=None): |
|
1332 | def showsyntaxerror(self, filename=None): | |
1312 | """Display the syntax error that just occurred. |
|
1333 | """Display the syntax error that just occurred. | |
1313 |
|
1334 | |||
1314 | This doesn't display a stack trace because there isn't one. |
|
1335 | This doesn't display a stack trace because there isn't one. | |
1315 |
|
1336 | |||
1316 | If a filename is given, it is stuffed in the exception instead |
|
1337 | If a filename is given, it is stuffed in the exception instead | |
1317 | of what was there before (because Python's parser always uses |
|
1338 | of what was there before (because Python's parser always uses | |
1318 | "<string>" when reading from a string). |
|
1339 | "<string>" when reading from a string). | |
1319 | """ |
|
1340 | """ | |
1320 | etype, value, last_traceback = sys.exc_info() |
|
1341 | etype, value, last_traceback = sys.exc_info() | |
1321 |
|
1342 | |||
1322 | # See note about these variables in showtraceback() above |
|
1343 | # See note about these variables in showtraceback() above | |
1323 | sys.last_type = etype |
|
1344 | sys.last_type = etype | |
1324 | sys.last_value = value |
|
1345 | sys.last_value = value | |
1325 | sys.last_traceback = last_traceback |
|
1346 | sys.last_traceback = last_traceback | |
1326 |
|
1347 | |||
1327 | if filename and etype is SyntaxError: |
|
1348 | if filename and etype is SyntaxError: | |
1328 | # Work hard to stuff the correct filename in the exception |
|
1349 | # Work hard to stuff the correct filename in the exception | |
1329 | try: |
|
1350 | try: | |
1330 | msg, (dummy_filename, lineno, offset, line) = value |
|
1351 | msg, (dummy_filename, lineno, offset, line) = value | |
1331 | except: |
|
1352 | except: | |
1332 | # Not the format we expect; leave it alone |
|
1353 | # Not the format we expect; leave it alone | |
1333 | pass |
|
1354 | pass | |
1334 | else: |
|
1355 | else: | |
1335 | # Stuff in the right filename |
|
1356 | # Stuff in the right filename | |
1336 | try: |
|
1357 | try: | |
1337 | # Assume SyntaxError is a class exception |
|
1358 | # Assume SyntaxError is a class exception | |
1338 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1359 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1339 | except: |
|
1360 | except: | |
1340 | # If that failed, assume SyntaxError is a string |
|
1361 | # If that failed, assume SyntaxError is a string | |
1341 | value = msg, (filename, lineno, offset, line) |
|
1362 | value = msg, (filename, lineno, offset, line) | |
1342 | self.SyntaxTB(etype,value,[]) |
|
1363 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
|
1364 | self._showtraceback(etype, value, stb) | |||
1343 |
|
1365 | |||
1344 | #------------------------------------------------------------------------- |
|
1366 | #------------------------------------------------------------------------- | |
1345 | # Things related to tab completion |
|
1367 | # Things related to tab completion | |
1346 | #------------------------------------------------------------------------- |
|
1368 | #------------------------------------------------------------------------- | |
1347 |
|
1369 | |||
1348 | def complete(self, text): |
|
1370 | def complete(self, text): | |
1349 | """Return a sorted list of all possible completions on text. |
|
1371 | """Return a sorted list of all possible completions on text. | |
1350 |
|
1372 | |||
1351 | Inputs: |
|
1373 | Inputs: | |
1352 |
|
1374 | |||
1353 | - text: a string of text to be completed on. |
|
1375 | - text: a string of text to be completed on. | |
1354 |
|
1376 | |||
1355 | This is a wrapper around the completion mechanism, similar to what |
|
1377 | This is a wrapper around the completion mechanism, similar to what | |
1356 | readline does at the command line when the TAB key is hit. By |
|
1378 | readline does at the command line when the TAB key is hit. By | |
1357 | exposing it as a method, it can be used by other non-readline |
|
1379 | exposing it as a method, it can be used by other non-readline | |
1358 | environments (such as GUIs) for text completion. |
|
1380 | environments (such as GUIs) for text completion. | |
1359 |
|
1381 | |||
1360 | Simple usage example: |
|
1382 | Simple usage example: | |
1361 |
|
1383 | |||
1362 | In [7]: x = 'hello' |
|
1384 | In [7]: x = 'hello' | |
1363 |
|
1385 | |||
1364 | In [8]: x |
|
1386 | In [8]: x | |
1365 | Out[8]: 'hello' |
|
1387 | Out[8]: 'hello' | |
1366 |
|
1388 | |||
1367 | In [9]: print x |
|
1389 | In [9]: print x | |
1368 | hello |
|
1390 | hello | |
1369 |
|
1391 | |||
1370 | In [10]: _ip.complete('x.l') |
|
1392 | In [10]: _ip.complete('x.l') | |
1371 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1393 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1372 | """ |
|
1394 | """ | |
1373 |
|
1395 | |||
1374 | # Inject names into __builtin__ so we can complete on the added names. |
|
1396 | # Inject names into __builtin__ so we can complete on the added names. | |
1375 | with self.builtin_trap: |
|
1397 | with self.builtin_trap: | |
1376 | complete = self.Completer.complete |
|
1398 | complete = self.Completer.complete | |
1377 | state = 0 |
|
1399 | state = 0 | |
1378 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1400 | # use a dict so we get unique keys, since ipyhton's multiple | |
1379 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1401 | # completers can return duplicates. When we make 2.4 a requirement, | |
1380 | # start using sets instead, which are faster. |
|
1402 | # start using sets instead, which are faster. | |
1381 | comps = {} |
|
1403 | comps = {} | |
1382 | while True: |
|
1404 | while True: | |
1383 | newcomp = complete(text,state,line_buffer=text) |
|
1405 | newcomp = complete(text,state,line_buffer=text) | |
1384 | if newcomp is None: |
|
1406 | if newcomp is None: | |
1385 | break |
|
1407 | break | |
1386 | comps[newcomp] = 1 |
|
1408 | comps[newcomp] = 1 | |
1387 | state += 1 |
|
1409 | state += 1 | |
1388 | outcomps = comps.keys() |
|
1410 | outcomps = comps.keys() | |
1389 | outcomps.sort() |
|
1411 | outcomps.sort() | |
1390 | #print "T:",text,"OC:",outcomps # dbg |
|
1412 | #print "T:",text,"OC:",outcomps # dbg | |
1391 | #print "vars:",self.user_ns.keys() |
|
1413 | #print "vars:",self.user_ns.keys() | |
1392 | return outcomps |
|
1414 | return outcomps | |
1393 |
|
1415 | |||
1394 | def set_custom_completer(self,completer,pos=0): |
|
1416 | def set_custom_completer(self,completer,pos=0): | |
1395 | """Adds a new custom completer function. |
|
1417 | """Adds a new custom completer function. | |
1396 |
|
1418 | |||
1397 | The position argument (defaults to 0) is the index in the completers |
|
1419 | The position argument (defaults to 0) is the index in the completers | |
1398 | list where you want the completer to be inserted.""" |
|
1420 | list where you want the completer to be inserted.""" | |
1399 |
|
1421 | |||
1400 | newcomp = new.instancemethod(completer,self.Completer, |
|
1422 | newcomp = new.instancemethod(completer,self.Completer, | |
1401 | self.Completer.__class__) |
|
1423 | self.Completer.__class__) | |
1402 | self.Completer.matchers.insert(pos,newcomp) |
|
1424 | self.Completer.matchers.insert(pos,newcomp) | |
1403 |
|
1425 | |||
1404 | def set_completer(self): |
|
1426 | def set_completer(self): | |
1405 | """Reset readline's completer to be our own.""" |
|
1427 | """Reset readline's completer to be our own.""" | |
1406 | self.readline.set_completer(self.Completer.complete) |
|
1428 | self.readline.set_completer(self.Completer.complete) | |
1407 |
|
1429 | |||
1408 | def set_completer_frame(self, frame=None): |
|
1430 | def set_completer_frame(self, frame=None): | |
1409 | """Set the frame of the completer.""" |
|
1431 | """Set the frame of the completer.""" | |
1410 | if frame: |
|
1432 | if frame: | |
1411 | self.Completer.namespace = frame.f_locals |
|
1433 | self.Completer.namespace = frame.f_locals | |
1412 | self.Completer.global_namespace = frame.f_globals |
|
1434 | self.Completer.global_namespace = frame.f_globals | |
1413 | else: |
|
1435 | else: | |
1414 | self.Completer.namespace = self.user_ns |
|
1436 | self.Completer.namespace = self.user_ns | |
1415 | self.Completer.global_namespace = self.user_global_ns |
|
1437 | self.Completer.global_namespace = self.user_global_ns | |
1416 |
|
1438 | |||
1417 | #------------------------------------------------------------------------- |
|
1439 | #------------------------------------------------------------------------- | |
1418 | # Things related to readline |
|
1440 | # Things related to readline | |
1419 | #------------------------------------------------------------------------- |
|
1441 | #------------------------------------------------------------------------- | |
1420 |
|
1442 | |||
1421 | def init_readline(self): |
|
1443 | def init_readline(self): | |
1422 | """Command history completion/saving/reloading.""" |
|
1444 | """Command history completion/saving/reloading.""" | |
1423 |
|
1445 | |||
1424 | if self.readline_use: |
|
1446 | if self.readline_use: | |
1425 | import IPython.utils.rlineimpl as readline |
|
1447 | import IPython.utils.rlineimpl as readline | |
1426 |
|
1448 | |||
1427 | self.rl_next_input = None |
|
1449 | self.rl_next_input = None | |
1428 | self.rl_do_indent = False |
|
1450 | self.rl_do_indent = False | |
1429 |
|
1451 | |||
1430 | if not self.readline_use or not readline.have_readline: |
|
1452 | if not self.readline_use or not readline.have_readline: | |
1431 | self.has_readline = False |
|
1453 | self.has_readline = False | |
1432 | self.readline = None |
|
1454 | self.readline = None | |
1433 | # Set a number of methods that depend on readline to be no-op |
|
1455 | # Set a number of methods that depend on readline to be no-op | |
1434 | self.savehist = no_op |
|
1456 | self.savehist = no_op | |
1435 | self.reloadhist = no_op |
|
1457 | self.reloadhist = no_op | |
1436 | self.set_completer = no_op |
|
1458 | self.set_completer = no_op | |
1437 | self.set_custom_completer = no_op |
|
1459 | self.set_custom_completer = no_op | |
1438 | self.set_completer_frame = no_op |
|
1460 | self.set_completer_frame = no_op | |
1439 | warn('Readline services not available or not loaded.') |
|
1461 | warn('Readline services not available or not loaded.') | |
1440 | else: |
|
1462 | else: | |
1441 | self.has_readline = True |
|
1463 | self.has_readline = True | |
1442 | self.readline = readline |
|
1464 | self.readline = readline | |
1443 | sys.modules['readline'] = readline |
|
1465 | sys.modules['readline'] = readline | |
1444 | import atexit |
|
1466 | import atexit | |
1445 | from IPython.core.completer import IPCompleter |
|
1467 | from IPython.core.completer import IPCompleter | |
1446 | self.Completer = IPCompleter(self, |
|
1468 | self.Completer = IPCompleter(self, | |
1447 | self.user_ns, |
|
1469 | self.user_ns, | |
1448 | self.user_global_ns, |
|
1470 | self.user_global_ns, | |
1449 | self.readline_omit__names, |
|
1471 | self.readline_omit__names, | |
1450 | self.alias_manager.alias_table) |
|
1472 | self.alias_manager.alias_table) | |
1451 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1473 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1452 | self.strdispatchers['complete_command'] = sdisp |
|
1474 | self.strdispatchers['complete_command'] = sdisp | |
1453 | self.Completer.custom_completers = sdisp |
|
1475 | self.Completer.custom_completers = sdisp | |
1454 | # Platform-specific configuration |
|
1476 | # Platform-specific configuration | |
1455 | if os.name == 'nt': |
|
1477 | if os.name == 'nt': | |
1456 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1478 | self.readline_startup_hook = readline.set_pre_input_hook | |
1457 | else: |
|
1479 | else: | |
1458 | self.readline_startup_hook = readline.set_startup_hook |
|
1480 | self.readline_startup_hook = readline.set_startup_hook | |
1459 |
|
1481 | |||
1460 | # Load user's initrc file (readline config) |
|
1482 | # Load user's initrc file (readline config) | |
1461 | # Or if libedit is used, load editrc. |
|
1483 | # Or if libedit is used, load editrc. | |
1462 | inputrc_name = os.environ.get('INPUTRC') |
|
1484 | inputrc_name = os.environ.get('INPUTRC') | |
1463 | if inputrc_name is None: |
|
1485 | if inputrc_name is None: | |
1464 | home_dir = get_home_dir() |
|
1486 | home_dir = get_home_dir() | |
1465 | if home_dir is not None: |
|
1487 | if home_dir is not None: | |
1466 | inputrc_name = '.inputrc' |
|
1488 | inputrc_name = '.inputrc' | |
1467 | if readline.uses_libedit: |
|
1489 | if readline.uses_libedit: | |
1468 | inputrc_name = '.editrc' |
|
1490 | inputrc_name = '.editrc' | |
1469 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1491 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1470 | if os.path.isfile(inputrc_name): |
|
1492 | if os.path.isfile(inputrc_name): | |
1471 | try: |
|
1493 | try: | |
1472 | readline.read_init_file(inputrc_name) |
|
1494 | readline.read_init_file(inputrc_name) | |
1473 | except: |
|
1495 | except: | |
1474 | warn('Problems reading readline initialization file <%s>' |
|
1496 | warn('Problems reading readline initialization file <%s>' | |
1475 | % inputrc_name) |
|
1497 | % inputrc_name) | |
1476 |
|
1498 | |||
1477 | # save this in sys so embedded copies can restore it properly |
|
1499 | # save this in sys so embedded copies can restore it properly | |
1478 | sys.ipcompleter = self.Completer.complete |
|
1500 | sys.ipcompleter = self.Completer.complete | |
1479 | self.set_completer() |
|
1501 | self.set_completer() | |
1480 |
|
1502 | |||
1481 | # Configure readline according to user's prefs |
|
1503 | # Configure readline according to user's prefs | |
1482 | # This is only done if GNU readline is being used. If libedit |
|
1504 | # This is only done if GNU readline is being used. If libedit | |
1483 | # is being used (as on Leopard) the readline config is |
|
1505 | # is being used (as on Leopard) the readline config is | |
1484 | # not run as the syntax for libedit is different. |
|
1506 | # not run as the syntax for libedit is different. | |
1485 | if not readline.uses_libedit: |
|
1507 | if not readline.uses_libedit: | |
1486 | for rlcommand in self.readline_parse_and_bind: |
|
1508 | for rlcommand in self.readline_parse_and_bind: | |
1487 | #print "loading rl:",rlcommand # dbg |
|
1509 | #print "loading rl:",rlcommand # dbg | |
1488 | readline.parse_and_bind(rlcommand) |
|
1510 | readline.parse_and_bind(rlcommand) | |
1489 |
|
1511 | |||
1490 | # Remove some chars from the delimiters list. If we encounter |
|
1512 | # Remove some chars from the delimiters list. If we encounter | |
1491 | # unicode chars, discard them. |
|
1513 | # unicode chars, discard them. | |
1492 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1514 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1493 | delims = delims.translate(string._idmap, |
|
1515 | delims = delims.translate(string._idmap, | |
1494 | self.readline_remove_delims) |
|
1516 | self.readline_remove_delims) | |
1495 | readline.set_completer_delims(delims) |
|
1517 | readline.set_completer_delims(delims) | |
1496 | # otherwise we end up with a monster history after a while: |
|
1518 | # otherwise we end up with a monster history after a while: | |
1497 | readline.set_history_length(1000) |
|
1519 | readline.set_history_length(1000) | |
1498 | try: |
|
1520 | try: | |
1499 | #print '*** Reading readline history' # dbg |
|
1521 | #print '*** Reading readline history' # dbg | |
1500 | readline.read_history_file(self.histfile) |
|
1522 | readline.read_history_file(self.histfile) | |
1501 | except IOError: |
|
1523 | except IOError: | |
1502 | pass # It doesn't exist yet. |
|
1524 | pass # It doesn't exist yet. | |
1503 |
|
1525 | |||
1504 | atexit.register(self.atexit_operations) |
|
1526 | atexit.register(self.atexit_operations) | |
1505 | del atexit |
|
1527 | del atexit | |
1506 |
|
1528 | |||
1507 | # Configure auto-indent for all platforms |
|
1529 | # Configure auto-indent for all platforms | |
1508 | self.set_autoindent(self.autoindent) |
|
1530 | self.set_autoindent(self.autoindent) | |
1509 |
|
1531 | |||
1510 | def set_next_input(self, s): |
|
1532 | def set_next_input(self, s): | |
1511 | """ Sets the 'default' input string for the next command line. |
|
1533 | """ Sets the 'default' input string for the next command line. | |
1512 |
|
1534 | |||
1513 | Requires readline. |
|
1535 | Requires readline. | |
1514 |
|
1536 | |||
1515 | Example: |
|
1537 | Example: | |
1516 |
|
1538 | |||
1517 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1539 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1518 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1540 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1519 | """ |
|
1541 | """ | |
1520 |
|
1542 | |||
1521 | self.rl_next_input = s |
|
1543 | self.rl_next_input = s | |
1522 |
|
1544 | |||
1523 | # Maybe move this to the terminal subclass? |
|
1545 | # Maybe move this to the terminal subclass? | |
1524 | def pre_readline(self): |
|
1546 | def pre_readline(self): | |
1525 | """readline hook to be used at the start of each line. |
|
1547 | """readline hook to be used at the start of each line. | |
1526 |
|
1548 | |||
1527 | Currently it handles auto-indent only.""" |
|
1549 | Currently it handles auto-indent only.""" | |
1528 |
|
1550 | |||
1529 | if self.rl_do_indent: |
|
1551 | if self.rl_do_indent: | |
1530 | self.readline.insert_text(self._indent_current_str()) |
|
1552 | self.readline.insert_text(self._indent_current_str()) | |
1531 | if self.rl_next_input is not None: |
|
1553 | if self.rl_next_input is not None: | |
1532 | self.readline.insert_text(self.rl_next_input) |
|
1554 | self.readline.insert_text(self.rl_next_input) | |
1533 | self.rl_next_input = None |
|
1555 | self.rl_next_input = None | |
1534 |
|
1556 | |||
1535 | def _indent_current_str(self): |
|
1557 | def _indent_current_str(self): | |
1536 | """return the current level of indentation as a string""" |
|
1558 | """return the current level of indentation as a string""" | |
1537 | return self.indent_current_nsp * ' ' |
|
1559 | return self.indent_current_nsp * ' ' | |
1538 |
|
1560 | |||
1539 | #------------------------------------------------------------------------- |
|
1561 | #------------------------------------------------------------------------- | |
1540 | # Things related to magics |
|
1562 | # Things related to magics | |
1541 | #------------------------------------------------------------------------- |
|
1563 | #------------------------------------------------------------------------- | |
1542 |
|
1564 | |||
1543 | def init_magics(self): |
|
1565 | def init_magics(self): | |
1544 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1566 | # FIXME: Move the color initialization to the DisplayHook, which | |
1545 | # should be split into a prompt manager and displayhook. We probably |
|
1567 | # should be split into a prompt manager and displayhook. We probably | |
1546 | # even need a centralize colors management object. |
|
1568 | # even need a centralize colors management object. | |
1547 | self.magic_colors(self.colors) |
|
1569 | self.magic_colors(self.colors) | |
1548 | # History was moved to a separate module |
|
1570 | # History was moved to a separate module | |
1549 | from . import history |
|
1571 | from . import history | |
1550 | history.init_ipython(self) |
|
1572 | history.init_ipython(self) | |
1551 |
|
1573 | |||
1552 | def magic(self,arg_s): |
|
1574 | def magic(self,arg_s): | |
1553 | """Call a magic function by name. |
|
1575 | """Call a magic function by name. | |
1554 |
|
1576 | |||
1555 | Input: a string containing the name of the magic function to call and any |
|
1577 | Input: a string containing the name of the magic function to call and any | |
1556 | additional arguments to be passed to the magic. |
|
1578 | additional arguments to be passed to the magic. | |
1557 |
|
1579 | |||
1558 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1580 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1559 | prompt: |
|
1581 | prompt: | |
1560 |
|
1582 | |||
1561 | In[1]: %name -opt foo bar |
|
1583 | In[1]: %name -opt foo bar | |
1562 |
|
1584 | |||
1563 | To call a magic without arguments, simply use magic('name'). |
|
1585 | To call a magic without arguments, simply use magic('name'). | |
1564 |
|
1586 | |||
1565 | This provides a proper Python function to call IPython's magics in any |
|
1587 | This provides a proper Python function to call IPython's magics in any | |
1566 | valid Python code you can type at the interpreter, including loops and |
|
1588 | valid Python code you can type at the interpreter, including loops and | |
1567 | compound statements. |
|
1589 | compound statements. | |
1568 | """ |
|
1590 | """ | |
1569 | args = arg_s.split(' ',1) |
|
1591 | args = arg_s.split(' ',1) | |
1570 | magic_name = args[0] |
|
1592 | magic_name = args[0] | |
1571 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1593 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1572 |
|
1594 | |||
1573 | try: |
|
1595 | try: | |
1574 | magic_args = args[1] |
|
1596 | magic_args = args[1] | |
1575 | except IndexError: |
|
1597 | except IndexError: | |
1576 | magic_args = '' |
|
1598 | magic_args = '' | |
1577 | fn = getattr(self,'magic_'+magic_name,None) |
|
1599 | fn = getattr(self,'magic_'+magic_name,None) | |
1578 | if fn is None: |
|
1600 | if fn is None: | |
1579 | error("Magic function `%s` not found." % magic_name) |
|
1601 | error("Magic function `%s` not found." % magic_name) | |
1580 | else: |
|
1602 | else: | |
1581 | magic_args = self.var_expand(magic_args,1) |
|
1603 | magic_args = self.var_expand(magic_args,1) | |
1582 | with nested(self.builtin_trap,): |
|
1604 | with nested(self.builtin_trap,): | |
1583 | result = fn(magic_args) |
|
1605 | result = fn(magic_args) | |
1584 | return result |
|
1606 | return result | |
1585 |
|
1607 | |||
1586 | def define_magic(self, magicname, func): |
|
1608 | def define_magic(self, magicname, func): | |
1587 | """Expose own function as magic function for ipython |
|
1609 | """Expose own function as magic function for ipython | |
1588 |
|
1610 | |||
1589 | def foo_impl(self,parameter_s=''): |
|
1611 | def foo_impl(self,parameter_s=''): | |
1590 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1612 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1591 | print 'Magic function. Passed parameter is between < >:' |
|
1613 | print 'Magic function. Passed parameter is between < >:' | |
1592 | print '<%s>' % parameter_s |
|
1614 | print '<%s>' % parameter_s | |
1593 | print 'The self object is:',self |
|
1615 | print 'The self object is:',self | |
1594 |
|
1616 | |||
1595 | self.define_magic('foo',foo_impl) |
|
1617 | self.define_magic('foo',foo_impl) | |
1596 | """ |
|
1618 | """ | |
1597 |
|
1619 | |||
1598 | import new |
|
1620 | import new | |
1599 | im = new.instancemethod(func,self, self.__class__) |
|
1621 | im = new.instancemethod(func,self, self.__class__) | |
1600 | old = getattr(self, "magic_" + magicname, None) |
|
1622 | old = getattr(self, "magic_" + magicname, None) | |
1601 | setattr(self, "magic_" + magicname, im) |
|
1623 | setattr(self, "magic_" + magicname, im) | |
1602 | return old |
|
1624 | return old | |
1603 |
|
1625 | |||
1604 | #------------------------------------------------------------------------- |
|
1626 | #------------------------------------------------------------------------- | |
1605 | # Things related to macros |
|
1627 | # Things related to macros | |
1606 | #------------------------------------------------------------------------- |
|
1628 | #------------------------------------------------------------------------- | |
1607 |
|
1629 | |||
1608 | def define_macro(self, name, themacro): |
|
1630 | def define_macro(self, name, themacro): | |
1609 | """Define a new macro |
|
1631 | """Define a new macro | |
1610 |
|
1632 | |||
1611 | Parameters |
|
1633 | Parameters | |
1612 | ---------- |
|
1634 | ---------- | |
1613 | name : str |
|
1635 | name : str | |
1614 | The name of the macro. |
|
1636 | The name of the macro. | |
1615 | themacro : str or Macro |
|
1637 | themacro : str or Macro | |
1616 | The action to do upon invoking the macro. If a string, a new |
|
1638 | The action to do upon invoking the macro. If a string, a new | |
1617 | Macro object is created by passing the string to it. |
|
1639 | Macro object is created by passing the string to it. | |
1618 | """ |
|
1640 | """ | |
1619 |
|
1641 | |||
1620 | from IPython.core import macro |
|
1642 | from IPython.core import macro | |
1621 |
|
1643 | |||
1622 | if isinstance(themacro, basestring): |
|
1644 | if isinstance(themacro, basestring): | |
1623 | themacro = macro.Macro(themacro) |
|
1645 | themacro = macro.Macro(themacro) | |
1624 | if not isinstance(themacro, macro.Macro): |
|
1646 | if not isinstance(themacro, macro.Macro): | |
1625 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1647 | raise ValueError('A macro must be a string or a Macro instance.') | |
1626 | self.user_ns[name] = themacro |
|
1648 | self.user_ns[name] = themacro | |
1627 |
|
1649 | |||
1628 | #------------------------------------------------------------------------- |
|
1650 | #------------------------------------------------------------------------- | |
1629 | # Things related to the running of system commands |
|
1651 | # Things related to the running of system commands | |
1630 | #------------------------------------------------------------------------- |
|
1652 | #------------------------------------------------------------------------- | |
1631 |
|
1653 | |||
1632 | def system(self, cmd): |
|
1654 | def system(self, cmd): | |
1633 | """Make a system call, using IPython.""" |
|
1655 | """Make a system call, using IPython.""" | |
1634 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1656 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
1635 |
|
1657 | |||
1636 | #------------------------------------------------------------------------- |
|
1658 | #------------------------------------------------------------------------- | |
1637 | # Things related to aliases |
|
1659 | # Things related to aliases | |
1638 | #------------------------------------------------------------------------- |
|
1660 | #------------------------------------------------------------------------- | |
1639 |
|
1661 | |||
1640 | def init_alias(self): |
|
1662 | def init_alias(self): | |
1641 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1663 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1642 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1664 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1643 |
|
1665 | |||
1644 | #------------------------------------------------------------------------- |
|
1666 | #------------------------------------------------------------------------- | |
1645 | # Things related to extensions and plugins |
|
1667 | # Things related to extensions and plugins | |
1646 | #------------------------------------------------------------------------- |
|
1668 | #------------------------------------------------------------------------- | |
1647 |
|
1669 | |||
1648 | def init_extension_manager(self): |
|
1670 | def init_extension_manager(self): | |
1649 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1671 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1650 |
|
1672 | |||
1651 | def init_plugin_manager(self): |
|
1673 | def init_plugin_manager(self): | |
1652 | self.plugin_manager = PluginManager(config=self.config) |
|
1674 | self.plugin_manager = PluginManager(config=self.config) | |
1653 |
|
1675 | |||
1654 | #------------------------------------------------------------------------- |
|
1676 | #------------------------------------------------------------------------- | |
1655 | # Things related to payloads |
|
1677 | # Things related to payloads | |
1656 | #------------------------------------------------------------------------- |
|
1678 | #------------------------------------------------------------------------- | |
1657 |
|
1679 | |||
1658 | def init_payload(self): |
|
1680 | def init_payload(self): | |
1659 | self.payload_manager = PayloadManager(config=self.config) |
|
1681 | self.payload_manager = PayloadManager(config=self.config) | |
1660 |
|
1682 | |||
1661 | #------------------------------------------------------------------------- |
|
1683 | #------------------------------------------------------------------------- | |
1662 | # Things related to the prefilter |
|
1684 | # Things related to the prefilter | |
1663 | #------------------------------------------------------------------------- |
|
1685 | #------------------------------------------------------------------------- | |
1664 |
|
1686 | |||
1665 | def init_prefilter(self): |
|
1687 | def init_prefilter(self): | |
1666 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1688 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1667 | # Ultimately this will be refactored in the new interpreter code, but |
|
1689 | # Ultimately this will be refactored in the new interpreter code, but | |
1668 | # for now, we should expose the main prefilter method (there's legacy |
|
1690 | # for now, we should expose the main prefilter method (there's legacy | |
1669 | # code out there that may rely on this). |
|
1691 | # code out there that may rely on this). | |
1670 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1692 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1671 |
|
1693 | |||
1672 | #------------------------------------------------------------------------- |
|
1694 | #------------------------------------------------------------------------- | |
1673 | # Things related to the running of code |
|
1695 | # Things related to the running of code | |
1674 | #------------------------------------------------------------------------- |
|
1696 | #------------------------------------------------------------------------- | |
1675 |
|
1697 | |||
1676 | def ex(self, cmd): |
|
1698 | def ex(self, cmd): | |
1677 | """Execute a normal python statement in user namespace.""" |
|
1699 | """Execute a normal python statement in user namespace.""" | |
1678 | with nested(self.builtin_trap,): |
|
1700 | with nested(self.builtin_trap,): | |
1679 | exec cmd in self.user_global_ns, self.user_ns |
|
1701 | exec cmd in self.user_global_ns, self.user_ns | |
1680 |
|
1702 | |||
1681 | def ev(self, expr): |
|
1703 | def ev(self, expr): | |
1682 | """Evaluate python expression expr in user namespace. |
|
1704 | """Evaluate python expression expr in user namespace. | |
1683 |
|
1705 | |||
1684 | Returns the result of evaluation |
|
1706 | Returns the result of evaluation | |
1685 | """ |
|
1707 | """ | |
1686 | with nested(self.builtin_trap,): |
|
1708 | with nested(self.builtin_trap,): | |
1687 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1709 | return eval(expr, self.user_global_ns, self.user_ns) | |
1688 |
|
1710 | |||
1689 | def safe_execfile(self, fname, *where, **kw): |
|
1711 | def safe_execfile(self, fname, *where, **kw): | |
1690 | """A safe version of the builtin execfile(). |
|
1712 | """A safe version of the builtin execfile(). | |
1691 |
|
1713 | |||
1692 | This version will never throw an exception, but instead print |
|
1714 | This version will never throw an exception, but instead print | |
1693 | helpful error messages to the screen. This only works on pure |
|
1715 | helpful error messages to the screen. This only works on pure | |
1694 | Python files with the .py extension. |
|
1716 | Python files with the .py extension. | |
1695 |
|
1717 | |||
1696 | Parameters |
|
1718 | Parameters | |
1697 | ---------- |
|
1719 | ---------- | |
1698 | fname : string |
|
1720 | fname : string | |
1699 | The name of the file to be executed. |
|
1721 | The name of the file to be executed. | |
1700 | where : tuple |
|
1722 | where : tuple | |
1701 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1723 | One or two namespaces, passed to execfile() as (globals,locals). | |
1702 | If only one is given, it is passed as both. |
|
1724 | If only one is given, it is passed as both. | |
1703 | exit_ignore : bool (False) |
|
1725 | exit_ignore : bool (False) | |
1704 | If True, then silence SystemExit for non-zero status (it is always |
|
1726 | If True, then silence SystemExit for non-zero status (it is always | |
1705 | silenced for zero status, as it is so common). |
|
1727 | silenced for zero status, as it is so common). | |
1706 | """ |
|
1728 | """ | |
1707 | kw.setdefault('exit_ignore', False) |
|
1729 | kw.setdefault('exit_ignore', False) | |
1708 |
|
1730 | |||
1709 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1731 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1710 |
|
1732 | |||
1711 | # Make sure we have a .py file |
|
1733 | # Make sure we have a .py file | |
1712 | if not fname.endswith('.py'): |
|
1734 | if not fname.endswith('.py'): | |
1713 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1735 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1714 |
|
1736 | |||
1715 | # Make sure we can open the file |
|
1737 | # Make sure we can open the file | |
1716 | try: |
|
1738 | try: | |
1717 | with open(fname) as thefile: |
|
1739 | with open(fname) as thefile: | |
1718 | pass |
|
1740 | pass | |
1719 | except: |
|
1741 | except: | |
1720 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1742 | warn('Could not open file <%s> for safe execution.' % fname) | |
1721 | return |
|
1743 | return | |
1722 |
|
1744 | |||
1723 | # Find things also in current directory. This is needed to mimic the |
|
1745 | # Find things also in current directory. This is needed to mimic the | |
1724 | # behavior of running a script from the system command line, where |
|
1746 | # behavior of running a script from the system command line, where | |
1725 | # Python inserts the script's directory into sys.path |
|
1747 | # Python inserts the script's directory into sys.path | |
1726 | dname = os.path.dirname(fname) |
|
1748 | dname = os.path.dirname(fname) | |
1727 |
|
1749 | |||
1728 | with prepended_to_syspath(dname): |
|
1750 | with prepended_to_syspath(dname): | |
1729 | try: |
|
1751 | try: | |
1730 | execfile(fname,*where) |
|
1752 | execfile(fname,*where) | |
1731 | except SystemExit, status: |
|
1753 | except SystemExit, status: | |
1732 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
1754 | # If the call was made with 0 or None exit status (sys.exit(0) | |
1733 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
1755 | # or sys.exit() ), don't bother showing a traceback, as both of | |
1734 | # these are considered normal by the OS: |
|
1756 | # these are considered normal by the OS: | |
1735 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
1757 | # > python -c'import sys;sys.exit(0)'; echo $? | |
1736 | # 0 |
|
1758 | # 0 | |
1737 | # > python -c'import sys;sys.exit()'; echo $? |
|
1759 | # > python -c'import sys;sys.exit()'; echo $? | |
1738 | # 0 |
|
1760 | # 0 | |
1739 | # For other exit status, we show the exception unless |
|
1761 | # For other exit status, we show the exception unless | |
1740 | # explicitly silenced, but only in short form. |
|
1762 | # explicitly silenced, but only in short form. | |
1741 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
1763 | if status.code not in (0, None) and not kw['exit_ignore']: | |
1742 | self.showtraceback(exception_only=True) |
|
1764 | self.showtraceback(exception_only=True) | |
1743 | except: |
|
1765 | except: | |
1744 | self.showtraceback() |
|
1766 | self.showtraceback() | |
1745 |
|
1767 | |||
1746 | def safe_execfile_ipy(self, fname): |
|
1768 | def safe_execfile_ipy(self, fname): | |
1747 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1769 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
1748 |
|
1770 | |||
1749 | Parameters |
|
1771 | Parameters | |
1750 | ---------- |
|
1772 | ---------- | |
1751 | fname : str |
|
1773 | fname : str | |
1752 | The name of the file to execute. The filename must have a |
|
1774 | The name of the file to execute. The filename must have a | |
1753 | .ipy extension. |
|
1775 | .ipy extension. | |
1754 | """ |
|
1776 | """ | |
1755 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1777 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1756 |
|
1778 | |||
1757 | # Make sure we have a .py file |
|
1779 | # Make sure we have a .py file | |
1758 | if not fname.endswith('.ipy'): |
|
1780 | if not fname.endswith('.ipy'): | |
1759 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1781 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1760 |
|
1782 | |||
1761 | # Make sure we can open the file |
|
1783 | # Make sure we can open the file | |
1762 | try: |
|
1784 | try: | |
1763 | with open(fname) as thefile: |
|
1785 | with open(fname) as thefile: | |
1764 | pass |
|
1786 | pass | |
1765 | except: |
|
1787 | except: | |
1766 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1788 | warn('Could not open file <%s> for safe execution.' % fname) | |
1767 | return |
|
1789 | return | |
1768 |
|
1790 | |||
1769 | # Find things also in current directory. This is needed to mimic the |
|
1791 | # Find things also in current directory. This is needed to mimic the | |
1770 | # behavior of running a script from the system command line, where |
|
1792 | # behavior of running a script from the system command line, where | |
1771 | # Python inserts the script's directory into sys.path |
|
1793 | # Python inserts the script's directory into sys.path | |
1772 | dname = os.path.dirname(fname) |
|
1794 | dname = os.path.dirname(fname) | |
1773 |
|
1795 | |||
1774 | with prepended_to_syspath(dname): |
|
1796 | with prepended_to_syspath(dname): | |
1775 | try: |
|
1797 | try: | |
1776 | with open(fname) as thefile: |
|
1798 | with open(fname) as thefile: | |
1777 | script = thefile.read() |
|
1799 | script = thefile.read() | |
1778 | # self.runlines currently captures all exceptions |
|
1800 | # self.runlines currently captures all exceptions | |
1779 | # raise in user code. It would be nice if there were |
|
1801 | # raise in user code. It would be nice if there were | |
1780 | # versions of runlines, execfile that did raise, so |
|
1802 | # versions of runlines, execfile that did raise, so | |
1781 | # we could catch the errors. |
|
1803 | # we could catch the errors. | |
1782 | self.runlines(script, clean=True) |
|
1804 | self.runlines(script, clean=True) | |
1783 | except: |
|
1805 | except: | |
1784 | self.showtraceback() |
|
1806 | self.showtraceback() | |
1785 | warn('Unknown failure executing file: <%s>' % fname) |
|
1807 | warn('Unknown failure executing file: <%s>' % fname) | |
1786 |
|
1808 | |||
1787 | def runlines(self, lines, clean=False): |
|
1809 | def runlines(self, lines, clean=False): | |
1788 | """Run a string of one or more lines of source. |
|
1810 | """Run a string of one or more lines of source. | |
1789 |
|
1811 | |||
1790 | This method is capable of running a string containing multiple source |
|
1812 | This method is capable of running a string containing multiple source | |
1791 | lines, as if they had been entered at the IPython prompt. Since it |
|
1813 | lines, as if they had been entered at the IPython prompt. Since it | |
1792 | exposes IPython's processing machinery, the given strings can contain |
|
1814 | exposes IPython's processing machinery, the given strings can contain | |
1793 | magic calls (%magic), special shell access (!cmd), etc. |
|
1815 | magic calls (%magic), special shell access (!cmd), etc. | |
1794 | """ |
|
1816 | """ | |
1795 |
|
1817 | |||
1796 | if isinstance(lines, (list, tuple)): |
|
1818 | if isinstance(lines, (list, tuple)): | |
1797 | lines = '\n'.join(lines) |
|
1819 | lines = '\n'.join(lines) | |
1798 |
|
1820 | |||
1799 | if clean: |
|
1821 | if clean: | |
1800 | lines = self._cleanup_ipy_script(lines) |
|
1822 | lines = self._cleanup_ipy_script(lines) | |
1801 |
|
1823 | |||
1802 | # We must start with a clean buffer, in case this is run from an |
|
1824 | # We must start with a clean buffer, in case this is run from an | |
1803 | # interactive IPython session (via a magic, for example). |
|
1825 | # interactive IPython session (via a magic, for example). | |
1804 | self.resetbuffer() |
|
1826 | self.resetbuffer() | |
1805 | lines = lines.splitlines() |
|
1827 | lines = lines.splitlines() | |
1806 | more = 0 |
|
1828 | more = 0 | |
1807 |
|
1829 | |||
1808 | with nested(self.builtin_trap, self.display_trap): |
|
1830 | with nested(self.builtin_trap, self.display_trap): | |
1809 | for line in lines: |
|
1831 | for line in lines: | |
1810 | # skip blank lines so we don't mess up the prompt counter, but do |
|
1832 | # skip blank lines so we don't mess up the prompt counter, but do | |
1811 | # NOT skip even a blank line if we are in a code block (more is |
|
1833 | # NOT skip even a blank line if we are in a code block (more is | |
1812 | # true) |
|
1834 | # true) | |
1813 |
|
1835 | |||
1814 | if line or more: |
|
1836 | if line or more: | |
1815 | # push to raw history, so hist line numbers stay in sync |
|
1837 | # push to raw history, so hist line numbers stay in sync | |
1816 | self.input_hist_raw.append("# " + line + "\n") |
|
1838 | self.input_hist_raw.append("# " + line + "\n") | |
1817 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
1839 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) | |
1818 | more = self.push_line(prefiltered) |
|
1840 | more = self.push_line(prefiltered) | |
1819 | # IPython's runsource returns None if there was an error |
|
1841 | # IPython's runsource returns None if there was an error | |
1820 | # compiling the code. This allows us to stop processing right |
|
1842 | # compiling the code. This allows us to stop processing right | |
1821 | # away, so the user gets the error message at the right place. |
|
1843 | # away, so the user gets the error message at the right place. | |
1822 | if more is None: |
|
1844 | if more is None: | |
1823 | break |
|
1845 | break | |
1824 | else: |
|
1846 | else: | |
1825 | self.input_hist_raw.append("\n") |
|
1847 | self.input_hist_raw.append("\n") | |
1826 | # final newline in case the input didn't have it, so that the code |
|
1848 | # final newline in case the input didn't have it, so that the code | |
1827 | # actually does get executed |
|
1849 | # actually does get executed | |
1828 | if more: |
|
1850 | if more: | |
1829 | self.push_line('\n') |
|
1851 | self.push_line('\n') | |
1830 |
|
1852 | |||
1831 | def runsource(self, source, filename='<input>', symbol='single'): |
|
1853 | def runsource(self, source, filename='<input>', symbol='single'): | |
1832 | """Compile and run some source in the interpreter. |
|
1854 | """Compile and run some source in the interpreter. | |
1833 |
|
1855 | |||
1834 | Arguments are as for compile_command(). |
|
1856 | Arguments are as for compile_command(). | |
1835 |
|
1857 | |||
1836 | One several things can happen: |
|
1858 | One several things can happen: | |
1837 |
|
1859 | |||
1838 | 1) The input is incorrect; compile_command() raised an |
|
1860 | 1) The input is incorrect; compile_command() raised an | |
1839 | exception (SyntaxError or OverflowError). A syntax traceback |
|
1861 | exception (SyntaxError or OverflowError). A syntax traceback | |
1840 | will be printed by calling the showsyntaxerror() method. |
|
1862 | will be printed by calling the showsyntaxerror() method. | |
1841 |
|
1863 | |||
1842 | 2) The input is incomplete, and more input is required; |
|
1864 | 2) The input is incomplete, and more input is required; | |
1843 | compile_command() returned None. Nothing happens. |
|
1865 | compile_command() returned None. Nothing happens. | |
1844 |
|
1866 | |||
1845 | 3) The input is complete; compile_command() returned a code |
|
1867 | 3) The input is complete; compile_command() returned a code | |
1846 | object. The code is executed by calling self.runcode() (which |
|
1868 | object. The code is executed by calling self.runcode() (which | |
1847 | also handles run-time exceptions, except for SystemExit). |
|
1869 | also handles run-time exceptions, except for SystemExit). | |
1848 |
|
1870 | |||
1849 | The return value is: |
|
1871 | The return value is: | |
1850 |
|
1872 | |||
1851 | - True in case 2 |
|
1873 | - True in case 2 | |
1852 |
|
1874 | |||
1853 | - False in the other cases, unless an exception is raised, where |
|
1875 | - False in the other cases, unless an exception is raised, where | |
1854 | None is returned instead. This can be used by external callers to |
|
1876 | None is returned instead. This can be used by external callers to | |
1855 | know whether to continue feeding input or not. |
|
1877 | know whether to continue feeding input or not. | |
1856 |
|
1878 | |||
1857 | The return value can be used to decide whether to use sys.ps1 or |
|
1879 | The return value can be used to decide whether to use sys.ps1 or | |
1858 | sys.ps2 to prompt the next line.""" |
|
1880 | sys.ps2 to prompt the next line.""" | |
1859 |
|
1881 | |||
1860 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
1882 | # if the source code has leading blanks, add 'if 1:\n' to it | |
1861 | # this allows execution of indented pasted code. It is tempting |
|
1883 | # this allows execution of indented pasted code. It is tempting | |
1862 | # to add '\n' at the end of source to run commands like ' a=1' |
|
1884 | # to add '\n' at the end of source to run commands like ' a=1' | |
1863 | # directly, but this fails for more complicated scenarios |
|
1885 | # directly, but this fails for more complicated scenarios | |
1864 | source=source.encode(self.stdin_encoding) |
|
1886 | source=source.encode(self.stdin_encoding) | |
1865 | if source[:1] in [' ', '\t']: |
|
1887 | if source[:1] in [' ', '\t']: | |
1866 | source = 'if 1:\n%s' % source |
|
1888 | source = 'if 1:\n%s' % source | |
1867 |
|
1889 | |||
1868 | try: |
|
1890 | try: | |
1869 | code = self.compile(source,filename,symbol) |
|
1891 | code = self.compile(source,filename,symbol) | |
1870 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
1892 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
1871 | # Case 1 |
|
1893 | # Case 1 | |
1872 | self.showsyntaxerror(filename) |
|
1894 | self.showsyntaxerror(filename) | |
1873 | return None |
|
1895 | return None | |
1874 |
|
1896 | |||
1875 | if code is None: |
|
1897 | if code is None: | |
1876 | # Case 2 |
|
1898 | # Case 2 | |
1877 | return True |
|
1899 | return True | |
1878 |
|
1900 | |||
1879 | # Case 3 |
|
1901 | # Case 3 | |
1880 | # We store the code object so that threaded shells and |
|
1902 | # We store the code object so that threaded shells and | |
1881 | # custom exception handlers can access all this info if needed. |
|
1903 | # custom exception handlers can access all this info if needed. | |
1882 | # The source corresponding to this can be obtained from the |
|
1904 | # The source corresponding to this can be obtained from the | |
1883 | # buffer attribute as '\n'.join(self.buffer). |
|
1905 | # buffer attribute as '\n'.join(self.buffer). | |
1884 | self.code_to_run = code |
|
1906 | self.code_to_run = code | |
1885 | # now actually execute the code object |
|
1907 | # now actually execute the code object | |
1886 | if self.runcode(code) == 0: |
|
1908 | if self.runcode(code) == 0: | |
1887 | return False |
|
1909 | return False | |
1888 | else: |
|
1910 | else: | |
1889 | return None |
|
1911 | return None | |
1890 |
|
1912 | |||
1891 | def runcode(self,code_obj): |
|
1913 | def runcode(self,code_obj): | |
1892 | """Execute a code object. |
|
1914 | """Execute a code object. | |
1893 |
|
1915 | |||
1894 | When an exception occurs, self.showtraceback() is called to display a |
|
1916 | When an exception occurs, self.showtraceback() is called to display a | |
1895 | traceback. |
|
1917 | traceback. | |
1896 |
|
1918 | |||
1897 | Return value: a flag indicating whether the code to be run completed |
|
1919 | Return value: a flag indicating whether the code to be run completed | |
1898 | successfully: |
|
1920 | successfully: | |
1899 |
|
1921 | |||
1900 | - 0: successful execution. |
|
1922 | - 0: successful execution. | |
1901 | - 1: an error occurred. |
|
1923 | - 1: an error occurred. | |
1902 | """ |
|
1924 | """ | |
1903 |
|
1925 | |||
1904 | # Set our own excepthook in case the user code tries to call it |
|
1926 | # Set our own excepthook in case the user code tries to call it | |
1905 | # directly, so that the IPython crash handler doesn't get triggered |
|
1927 | # directly, so that the IPython crash handler doesn't get triggered | |
1906 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
1928 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
1907 |
|
1929 | |||
1908 | # we save the original sys.excepthook in the instance, in case config |
|
1930 | # we save the original sys.excepthook in the instance, in case config | |
1909 | # code (such as magics) needs access to it. |
|
1931 | # code (such as magics) needs access to it. | |
1910 | self.sys_excepthook = old_excepthook |
|
1932 | self.sys_excepthook = old_excepthook | |
1911 | outflag = 1 # happens in more places, so it's easier as default |
|
1933 | outflag = 1 # happens in more places, so it's easier as default | |
1912 | try: |
|
1934 | try: | |
1913 | try: |
|
1935 | try: | |
1914 | self.hooks.pre_runcode_hook() |
|
1936 | self.hooks.pre_runcode_hook() | |
|
1937 | #rprint('Running code') # dbg | |||
1915 | exec code_obj in self.user_global_ns, self.user_ns |
|
1938 | exec code_obj in self.user_global_ns, self.user_ns | |
1916 | finally: |
|
1939 | finally: | |
1917 | # Reset our crash handler in place |
|
1940 | # Reset our crash handler in place | |
1918 | sys.excepthook = old_excepthook |
|
1941 | sys.excepthook = old_excepthook | |
1919 | except SystemExit: |
|
1942 | except SystemExit: | |
1920 | self.resetbuffer() |
|
1943 | self.resetbuffer() | |
1921 | self.showtraceback(exception_only=True) |
|
1944 | self.showtraceback(exception_only=True) | |
1922 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
1945 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
1923 | except self.custom_exceptions: |
|
1946 | except self.custom_exceptions: | |
1924 | etype,value,tb = sys.exc_info() |
|
1947 | etype,value,tb = sys.exc_info() | |
1925 | self.CustomTB(etype,value,tb) |
|
1948 | self.CustomTB(etype,value,tb) | |
1926 | except: |
|
1949 | except: | |
1927 | self.showtraceback() |
|
1950 | self.showtraceback() | |
1928 | else: |
|
1951 | else: | |
1929 | outflag = 0 |
|
1952 | outflag = 0 | |
1930 | if softspace(sys.stdout, 0): |
|
1953 | if softspace(sys.stdout, 0): | |
1931 |
|
1954 | |||
1932 | # Flush out code object which has been run (and source) |
|
1955 | # Flush out code object which has been run (and source) | |
1933 | self.code_to_run = None |
|
1956 | self.code_to_run = None | |
1934 | return outflag |
|
1957 | return outflag | |
1935 |
|
1958 | |||
1936 | def push_line(self, line): |
|
1959 | def push_line(self, line): | |
1937 | """Push a line to the interpreter. |
|
1960 | """Push a line to the interpreter. | |
1938 |
|
1961 | |||
1939 | The line should not have a trailing newline; it may have |
|
1962 | The line should not have a trailing newline; it may have | |
1940 | internal newlines. The line is appended to a buffer and the |
|
1963 | internal newlines. The line is appended to a buffer and the | |
1941 | interpreter's runsource() method is called with the |
|
1964 | interpreter's runsource() method is called with the | |
1942 | concatenated contents of the buffer as source. If this |
|
1965 | concatenated contents of the buffer as source. If this | |
1943 | indicates that the command was executed or invalid, the buffer |
|
1966 | indicates that the command was executed or invalid, the buffer | |
1944 | is reset; otherwise, the command is incomplete, and the buffer |
|
1967 | is reset; otherwise, the command is incomplete, and the buffer | |
1945 | is left as it was after the line was appended. The return |
|
1968 | is left as it was after the line was appended. The return | |
1946 | value is 1 if more input is required, 0 if the line was dealt |
|
1969 | value is 1 if more input is required, 0 if the line was dealt | |
1947 | with in some way (this is the same as runsource()). |
|
1970 | with in some way (this is the same as runsource()). | |
1948 | """ |
|
1971 | """ | |
1949 |
|
1972 | |||
1950 | # autoindent management should be done here, and not in the |
|
1973 | # autoindent management should be done here, and not in the | |
1951 | # interactive loop, since that one is only seen by keyboard input. We |
|
1974 | # interactive loop, since that one is only seen by keyboard input. We | |
1952 | # need this done correctly even for code run via runlines (which uses |
|
1975 | # need this done correctly even for code run via runlines (which uses | |
1953 | # push). |
|
1976 | # push). | |
1954 |
|
1977 | |||
1955 | #print 'push line: <%s>' % line # dbg |
|
1978 | #print 'push line: <%s>' % line # dbg | |
1956 | for subline in line.splitlines(): |
|
1979 | for subline in line.splitlines(): | |
1957 | self._autoindent_update(subline) |
|
1980 | self._autoindent_update(subline) | |
1958 | self.buffer.append(line) |
|
1981 | self.buffer.append(line) | |
1959 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
1982 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
1960 | if not more: |
|
1983 | if not more: | |
1961 | self.resetbuffer() |
|
1984 | self.resetbuffer() | |
1962 | return more |
|
1985 | return more | |
1963 |
|
1986 | |||
1964 | def resetbuffer(self): |
|
1987 | def resetbuffer(self): | |
1965 | """Reset the input buffer.""" |
|
1988 | """Reset the input buffer.""" | |
1966 | self.buffer[:] = [] |
|
1989 | self.buffer[:] = [] | |
1967 |
|
1990 | |||
1968 | def _is_secondary_block_start(self, s): |
|
1991 | def _is_secondary_block_start(self, s): | |
1969 | if not s.endswith(':'): |
|
1992 | if not s.endswith(':'): | |
1970 | return False |
|
1993 | return False | |
1971 | if (s.startswith('elif') or |
|
1994 | if (s.startswith('elif') or | |
1972 | s.startswith('else') or |
|
1995 | s.startswith('else') or | |
1973 | s.startswith('except') or |
|
1996 | s.startswith('except') or | |
1974 | s.startswith('finally')): |
|
1997 | s.startswith('finally')): | |
1975 | return True |
|
1998 | return True | |
1976 |
|
1999 | |||
1977 | def _cleanup_ipy_script(self, script): |
|
2000 | def _cleanup_ipy_script(self, script): | |
1978 | """Make a script safe for self.runlines() |
|
2001 | """Make a script safe for self.runlines() | |
1979 |
|
2002 | |||
1980 | Currently, IPython is lines based, with blocks being detected by |
|
2003 | Currently, IPython is lines based, with blocks being detected by | |
1981 | empty lines. This is a problem for block based scripts that may |
|
2004 | empty lines. This is a problem for block based scripts that may | |
1982 | not have empty lines after blocks. This script adds those empty |
|
2005 | not have empty lines after blocks. This script adds those empty | |
1983 | lines to make scripts safe for running in the current line based |
|
2006 | lines to make scripts safe for running in the current line based | |
1984 | IPython. |
|
2007 | IPython. | |
1985 | """ |
|
2008 | """ | |
1986 | res = [] |
|
2009 | res = [] | |
1987 | lines = script.splitlines() |
|
2010 | lines = script.splitlines() | |
1988 | level = 0 |
|
2011 | level = 0 | |
1989 |
|
2012 | |||
1990 | for l in lines: |
|
2013 | for l in lines: | |
1991 | lstripped = l.lstrip() |
|
2014 | lstripped = l.lstrip() | |
1992 | stripped = l.strip() |
|
2015 | stripped = l.strip() | |
1993 | if not stripped: |
|
2016 | if not stripped: | |
1994 | continue |
|
2017 | continue | |
1995 | newlevel = len(l) - len(lstripped) |
|
2018 | newlevel = len(l) - len(lstripped) | |
1996 | if level > 0 and newlevel == 0 and \ |
|
2019 | if level > 0 and newlevel == 0 and \ | |
1997 | not self._is_secondary_block_start(stripped): |
|
2020 | not self._is_secondary_block_start(stripped): | |
1998 | # add empty line |
|
2021 | # add empty line | |
1999 | res.append('') |
|
2022 | res.append('') | |
2000 | res.append(l) |
|
2023 | res.append(l) | |
2001 | level = newlevel |
|
2024 | level = newlevel | |
2002 |
|
2025 | |||
2003 | return '\n'.join(res) + '\n' |
|
2026 | return '\n'.join(res) + '\n' | |
2004 |
|
2027 | |||
2005 | def _autoindent_update(self,line): |
|
2028 | def _autoindent_update(self,line): | |
2006 | """Keep track of the indent level.""" |
|
2029 | """Keep track of the indent level.""" | |
2007 |
|
2030 | |||
2008 | #debugx('line') |
|
2031 | #debugx('line') | |
2009 | #debugx('self.indent_current_nsp') |
|
2032 | #debugx('self.indent_current_nsp') | |
2010 | if self.autoindent: |
|
2033 | if self.autoindent: | |
2011 | if line: |
|
2034 | if line: | |
2012 | inisp = num_ini_spaces(line) |
|
2035 | inisp = num_ini_spaces(line) | |
2013 | if inisp < self.indent_current_nsp: |
|
2036 | if inisp < self.indent_current_nsp: | |
2014 | self.indent_current_nsp = inisp |
|
2037 | self.indent_current_nsp = inisp | |
2015 |
|
2038 | |||
2016 | if line[-1] == ':': |
|
2039 | if line[-1] == ':': | |
2017 | self.indent_current_nsp += 4 |
|
2040 | self.indent_current_nsp += 4 | |
2018 | elif dedent_re.match(line): |
|
2041 | elif dedent_re.match(line): | |
2019 | self.indent_current_nsp -= 4 |
|
2042 | self.indent_current_nsp -= 4 | |
2020 | else: |
|
2043 | else: | |
2021 | self.indent_current_nsp = 0 |
|
2044 | self.indent_current_nsp = 0 | |
2022 |
|
2045 | |||
2023 | #------------------------------------------------------------------------- |
|
2046 | #------------------------------------------------------------------------- | |
2024 | # Things related to GUI support and pylab |
|
2047 | # Things related to GUI support and pylab | |
2025 | #------------------------------------------------------------------------- |
|
2048 | #------------------------------------------------------------------------- | |
2026 |
|
2049 | |||
2027 | def enable_pylab(self, gui=None): |
|
2050 | def enable_pylab(self, gui=None): | |
2028 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2051 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2029 |
|
2052 | |||
2030 | #------------------------------------------------------------------------- |
|
2053 | #------------------------------------------------------------------------- | |
2031 | # Utilities |
|
2054 | # Utilities | |
2032 | #------------------------------------------------------------------------- |
|
2055 | #------------------------------------------------------------------------- | |
2033 |
|
2056 | |||
2034 | def getoutput(self, cmd): |
|
2057 | def getoutput(self, cmd): | |
2035 | return getoutput(self.var_expand(cmd,depth=2), |
|
2058 | return getoutput(self.var_expand(cmd,depth=2), | |
2036 | header=self.system_header, |
|
2059 | header=self.system_header, | |
2037 | verbose=self.system_verbose) |
|
2060 | verbose=self.system_verbose) | |
2038 |
|
2061 | |||
2039 | def getoutputerror(self, cmd): |
|
2062 | def getoutputerror(self, cmd): | |
2040 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2063 | return getoutputerror(self.var_expand(cmd,depth=2), | |
2041 | header=self.system_header, |
|
2064 | header=self.system_header, | |
2042 | verbose=self.system_verbose) |
|
2065 | verbose=self.system_verbose) | |
2043 |
|
2066 | |||
2044 | def var_expand(self,cmd,depth=0): |
|
2067 | def var_expand(self,cmd,depth=0): | |
2045 | """Expand python variables in a string. |
|
2068 | """Expand python variables in a string. | |
2046 |
|
2069 | |||
2047 | The depth argument indicates how many frames above the caller should |
|
2070 | The depth argument indicates how many frames above the caller should | |
2048 | be walked to look for the local namespace where to expand variables. |
|
2071 | be walked to look for the local namespace where to expand variables. | |
2049 |
|
2072 | |||
2050 | The global namespace for expansion is always the user's interactive |
|
2073 | The global namespace for expansion is always the user's interactive | |
2051 | namespace. |
|
2074 | namespace. | |
2052 | """ |
|
2075 | """ | |
2053 |
|
2076 | |||
2054 | return str(ItplNS(cmd, |
|
2077 | return str(ItplNS(cmd, | |
2055 | self.user_ns, # globals |
|
2078 | self.user_ns, # globals | |
2056 | # Skip our own frame in searching for locals: |
|
2079 | # Skip our own frame in searching for locals: | |
2057 | sys._getframe(depth+1).f_locals # locals |
|
2080 | sys._getframe(depth+1).f_locals # locals | |
2058 | )) |
|
2081 | )) | |
2059 |
|
2082 | |||
2060 | def mktempfile(self,data=None): |
|
2083 | def mktempfile(self,data=None): | |
2061 | """Make a new tempfile and return its filename. |
|
2084 | """Make a new tempfile and return its filename. | |
2062 |
|
2085 | |||
2063 | This makes a call to tempfile.mktemp, but it registers the created |
|
2086 | This makes a call to tempfile.mktemp, but it registers the created | |
2064 | filename internally so ipython cleans it up at exit time. |
|
2087 | filename internally so ipython cleans it up at exit time. | |
2065 |
|
2088 | |||
2066 | Optional inputs: |
|
2089 | Optional inputs: | |
2067 |
|
2090 | |||
2068 | - data(None): if data is given, it gets written out to the temp file |
|
2091 | - data(None): if data is given, it gets written out to the temp file | |
2069 | immediately, and the file is closed again.""" |
|
2092 | immediately, and the file is closed again.""" | |
2070 |
|
2093 | |||
2071 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2094 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2072 | self.tempfiles.append(filename) |
|
2095 | self.tempfiles.append(filename) | |
2073 |
|
2096 | |||
2074 | if data: |
|
2097 | if data: | |
2075 | tmp_file = open(filename,'w') |
|
2098 | tmp_file = open(filename,'w') | |
2076 | tmp_file.write(data) |
|
2099 | tmp_file.write(data) | |
2077 | tmp_file.close() |
|
2100 | tmp_file.close() | |
2078 | return filename |
|
2101 | return filename | |
2079 |
|
2102 | |||
2080 | # TODO: This should be removed when Term is refactored. |
|
2103 | # TODO: This should be removed when Term is refactored. | |
2081 | def write(self,data): |
|
2104 | def write(self,data): | |
2082 | """Write a string to the default output""" |
|
2105 | """Write a string to the default output""" | |
2083 |
|
|
2106 | io.Term.cout.write(data) | |
2084 |
|
2107 | |||
2085 | # TODO: This should be removed when Term is refactored. |
|
2108 | # TODO: This should be removed when Term is refactored. | |
2086 | def write_err(self,data): |
|
2109 | def write_err(self,data): | |
2087 | """Write a string to the default error output""" |
|
2110 | """Write a string to the default error output""" | |
2088 |
|
|
2111 | io.Term.cerr.write(data) | |
2089 |
|
2112 | |||
2090 | def ask_yes_no(self,prompt,default=True): |
|
2113 | def ask_yes_no(self,prompt,default=True): | |
2091 | if self.quiet: |
|
2114 | if self.quiet: | |
2092 | return True |
|
2115 | return True | |
2093 | return ask_yes_no(prompt,default) |
|
2116 | return ask_yes_no(prompt,default) | |
2094 |
|
2117 | |||
2095 | #------------------------------------------------------------------------- |
|
2118 | #------------------------------------------------------------------------- | |
2096 | # Things related to IPython exiting |
|
2119 | # Things related to IPython exiting | |
2097 | #------------------------------------------------------------------------- |
|
2120 | #------------------------------------------------------------------------- | |
2098 |
|
2121 | |||
2099 | def atexit_operations(self): |
|
2122 | def atexit_operations(self): | |
2100 | """This will be executed at the time of exit. |
|
2123 | """This will be executed at the time of exit. | |
2101 |
|
2124 | |||
2102 | Saving of persistent data should be performed here. |
|
2125 | Saving of persistent data should be performed here. | |
2103 | """ |
|
2126 | """ | |
2104 | self.savehist() |
|
2127 | self.savehist() | |
2105 |
|
2128 | |||
2106 | # Cleanup all tempfiles left around |
|
2129 | # Cleanup all tempfiles left around | |
2107 | for tfile in self.tempfiles: |
|
2130 | for tfile in self.tempfiles: | |
2108 | try: |
|
2131 | try: | |
2109 | os.unlink(tfile) |
|
2132 | os.unlink(tfile) | |
2110 | except OSError: |
|
2133 | except OSError: | |
2111 | pass |
|
2134 | pass | |
2112 |
|
2135 | |||
2113 | # Clear all user namespaces to release all references cleanly. |
|
2136 | # Clear all user namespaces to release all references cleanly. | |
2114 | self.reset() |
|
2137 | self.reset() | |
2115 |
|
2138 | |||
2116 | # Run user hooks |
|
2139 | # Run user hooks | |
2117 | self.hooks.shutdown_hook() |
|
2140 | self.hooks.shutdown_hook() | |
2118 |
|
2141 | |||
2119 | def cleanup(self): |
|
2142 | def cleanup(self): | |
2120 | self.restore_sys_module_state() |
|
2143 | self.restore_sys_module_state() | |
2121 |
|
2144 | |||
2122 |
|
2145 | |||
2123 | class InteractiveShellABC(object): |
|
2146 | class InteractiveShellABC(object): | |
2124 | """An abstract base class for InteractiveShell.""" |
|
2147 | """An abstract base class for InteractiveShell.""" | |
2125 | __metaclass__ = abc.ABCMeta |
|
2148 | __metaclass__ = abc.ABCMeta | |
2126 |
|
2149 | |||
2127 | InteractiveShellABC.register(InteractiveShell) |
|
2150 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,1156 +1,1202 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | ultratb.py -- Spice up your tracebacks! |
|
3 | ultratb.py -- Spice up your tracebacks! | |
4 |
|
4 | |||
5 | * ColorTB |
|
5 | * ColorTB | |
6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
6 | I've always found it a bit hard to visually parse tracebacks in Python. The | |
7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
7 | ColorTB class is a solution to that problem. It colors the different parts of a | |
8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
8 | traceback in a manner similar to what you would expect from a syntax-highlighting | |
9 | text editor. |
|
9 | text editor. | |
10 |
|
10 | |||
11 | Installation instructions for ColorTB: |
|
11 | Installation instructions for ColorTB: | |
12 | import sys,ultratb |
|
12 | import sys,ultratb | |
13 | sys.excepthook = ultratb.ColorTB() |
|
13 | sys.excepthook = ultratb.ColorTB() | |
14 |
|
14 | |||
15 | * VerboseTB |
|
15 | * VerboseTB | |
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | |
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML | |
18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
18 | and intended it for CGI programmers, but why should they have all the fun? I | |
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, | |
20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
20 | but kind of neat, and maybe useful for long-running programs that you believe | |
21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
21 | are bug-free. If a crash *does* occur in that type of program you want details. | |
22 | Give it a shot--you'll love it or you'll hate it. |
|
22 | Give it a shot--you'll love it or you'll hate it. | |
23 |
|
23 | |||
24 | Note: |
|
24 | Note: | |
25 |
|
25 | |||
26 | The Verbose mode prints the variables currently visible where the exception |
|
26 | The Verbose mode prints the variables currently visible where the exception | |
27 | happened (shortening their strings if too long). This can potentially be |
|
27 | happened (shortening their strings if too long). This can potentially be | |
28 | very slow, if you happen to have a huge data structure whose string |
|
28 | very slow, if you happen to have a huge data structure whose string | |
29 | representation is complex to compute. Your computer may appear to freeze for |
|
29 | representation is complex to compute. Your computer may appear to freeze for | |
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback | |
31 | with Ctrl-C (maybe hitting it more than once). |
|
31 | with Ctrl-C (maybe hitting it more than once). | |
32 |
|
32 | |||
33 | If you encounter this kind of situation often, you may want to use the |
|
33 | If you encounter this kind of situation often, you may want to use the | |
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting | |
35 | variables (but otherwise includes the information and context given by |
|
35 | variables (but otherwise includes the information and context given by | |
36 | Verbose). |
|
36 | Verbose). | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | Installation instructions for ColorTB: |
|
39 | Installation instructions for ColorTB: | |
40 | import sys,ultratb |
|
40 | import sys,ultratb | |
41 | sys.excepthook = ultratb.VerboseTB() |
|
41 | sys.excepthook = ultratb.VerboseTB() | |
42 |
|
42 | |||
43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
43 | Note: Much of the code in this module was lifted verbatim from the standard | |
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | |
45 |
|
45 | |||
46 | * Color schemes |
|
46 | * Color schemes | |
47 | The colors are defined in the class TBTools through the use of the |
|
47 | The colors are defined in the class TBTools through the use of the | |
48 | ColorSchemeTable class. Currently the following exist: |
|
48 | ColorSchemeTable class. Currently the following exist: | |
49 |
|
49 | |||
50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
50 | - NoColor: allows all of this module to be used in any terminal (the color | |
51 | escapes are just dummy blank strings). |
|
51 | escapes are just dummy blank strings). | |
52 |
|
52 | |||
53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
53 | - Linux: is meant to look good in a terminal like the Linux console (black | |
54 | or very dark background). |
|
54 | or very dark background). | |
55 |
|
55 | |||
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable | |
57 | in light background terminals. |
|
57 | in light background terminals. | |
58 |
|
58 | |||
59 | You can implement other color schemes easily, the syntax is fairly |
|
59 | You can implement other color schemes easily, the syntax is fairly | |
60 | self-explanatory. Please send back new schemes you develop to the author for |
|
60 | self-explanatory. Please send back new schemes you develop to the author for | |
61 | possible inclusion in future releases. |
|
61 | possible inclusion in future releases. | |
62 | """ |
|
62 | """ | |
63 |
|
63 | |||
64 | #***************************************************************************** |
|
64 | #***************************************************************************** | |
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> | |
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
67 | # |
|
67 | # | |
68 | # Distributed under the terms of the BSD License. The full license is in |
|
68 | # Distributed under the terms of the BSD License. The full license is in | |
69 | # the file COPYING, distributed as part of this software. |
|
69 | # the file COPYING, distributed as part of this software. | |
70 | #***************************************************************************** |
|
70 | #***************************************************************************** | |
71 |
|
71 | |||
72 | from __future__ import with_statement |
|
72 | from __future__ import with_statement | |
73 |
|
73 | |||
74 | import inspect |
|
74 | import inspect | |
75 | import keyword |
|
75 | import keyword | |
76 | import linecache |
|
76 | import linecache | |
77 | import os |
|
77 | import os | |
78 | import pydoc |
|
78 | import pydoc | |
79 | import re |
|
79 | import re | |
80 | import string |
|
80 | import string | |
81 | import sys |
|
81 | import sys | |
82 | import time |
|
82 | import time | |
83 | import tokenize |
|
83 | import tokenize | |
84 | import traceback |
|
84 | import traceback | |
85 | import types |
|
85 | import types | |
86 |
|
86 | |||
87 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
87 | # For purposes of monkeypatching inspect to fix a bug in it. | |
88 | from inspect import getsourcefile, getfile, getmodule,\ |
|
88 | from inspect import getsourcefile, getfile, getmodule,\ | |
89 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
89 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode | |
90 |
|
90 | |||
91 | # IPython's own modules |
|
91 | # IPython's own modules | |
92 | # Modified pdb which doesn't damage IPython's readline handling |
|
92 | # Modified pdb which doesn't damage IPython's readline handling | |
93 | from IPython.utils import PyColorize |
|
|||
94 | from IPython.core import debugger, ipapi |
|
93 | from IPython.core import debugger, ipapi | |
95 | from IPython.core.display_trap import DisplayTrap |
|
94 | from IPython.core.display_trap import DisplayTrap | |
96 | from IPython.core.excolors import exception_colors |
|
95 | from IPython.core.excolors import exception_colors | |
|
96 | from IPython.utils import PyColorize | |||
|
97 | from IPython.utils import io | |||
97 | from IPython.utils.data import uniq_stable |
|
98 | from IPython.utils.data import uniq_stable | |
98 | import IPython.utils.io |
|
|||
99 | from IPython.utils.warn import info, error |
|
99 | from IPython.utils.warn import info, error | |
100 |
|
100 | |||
101 | # Globals |
|
101 | # Globals | |
102 | # amount of space to put line numbers before verbose tracebacks |
|
102 | # amount of space to put line numbers before verbose tracebacks | |
103 | INDENT_SIZE = 8 |
|
103 | INDENT_SIZE = 8 | |
104 |
|
104 | |||
105 | # Default color scheme. This is used, for example, by the traceback |
|
105 | # Default color scheme. This is used, for example, by the traceback | |
106 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
106 | # formatter. When running in an actual IPython instance, the user's rc.colors | |
107 | # value is used, but havinga module global makes this functionality available |
|
107 | # value is used, but havinga module global makes this functionality available | |
108 | # to users of ultratb who are NOT running inside ipython. |
|
108 | # to users of ultratb who are NOT running inside ipython. | |
109 | DEFAULT_SCHEME = 'NoColor' |
|
109 | DEFAULT_SCHEME = 'NoColor' | |
110 |
|
110 | |||
111 | #--------------------------------------------------------------------------- |
|
111 | #--------------------------------------------------------------------------- | |
112 | # Code begins |
|
112 | # Code begins | |
113 |
|
113 | |||
114 | # Utility functions |
|
114 | # Utility functions | |
115 | def inspect_error(): |
|
115 | def inspect_error(): | |
116 | """Print a message about internal inspect errors. |
|
116 | """Print a message about internal inspect errors. | |
117 |
|
117 | |||
118 | These are unfortunately quite common.""" |
|
118 | These are unfortunately quite common.""" | |
119 |
|
119 | |||
120 | error('Internal Python error in the inspect module.\n' |
|
120 | error('Internal Python error in the inspect module.\n' | |
121 | 'Below is the traceback from this internal error.\n') |
|
121 | 'Below is the traceback from this internal error.\n') | |
122 |
|
122 | |||
123 |
|
123 | |||
124 | def findsource(object): |
|
124 | def findsource(object): | |
125 | """Return the entire source file and starting line number for an object. |
|
125 | """Return the entire source file and starting line number for an object. | |
126 |
|
126 | |||
127 | The argument may be a module, class, method, function, traceback, frame, |
|
127 | The argument may be a module, class, method, function, traceback, frame, | |
128 | or code object. The source code is returned as a list of all the lines |
|
128 | or code object. The source code is returned as a list of all the lines | |
129 | in the file and the line number indexes a line in that list. An IOError |
|
129 | in the file and the line number indexes a line in that list. An IOError | |
130 | is raised if the source code cannot be retrieved. |
|
130 | is raised if the source code cannot be retrieved. | |
131 |
|
131 | |||
132 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
132 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" | |
133 |
|
133 | |||
134 | file = getsourcefile(object) or getfile(object) |
|
134 | file = getsourcefile(object) or getfile(object) | |
135 | # If the object is a frame, then trying to get the globals dict from its |
|
135 | # If the object is a frame, then trying to get the globals dict from its | |
136 | # module won't work. Instead, the frame object itself has the globals |
|
136 | # module won't work. Instead, the frame object itself has the globals | |
137 | # dictionary. |
|
137 | # dictionary. | |
138 | globals_dict = None |
|
138 | globals_dict = None | |
139 | if inspect.isframe(object): |
|
139 | if inspect.isframe(object): | |
140 | # XXX: can this ever be false? |
|
140 | # XXX: can this ever be false? | |
141 | globals_dict = object.f_globals |
|
141 | globals_dict = object.f_globals | |
142 | else: |
|
142 | else: | |
143 | module = getmodule(object, file) |
|
143 | module = getmodule(object, file) | |
144 | if module: |
|
144 | if module: | |
145 | globals_dict = module.__dict__ |
|
145 | globals_dict = module.__dict__ | |
146 | lines = linecache.getlines(file, globals_dict) |
|
146 | lines = linecache.getlines(file, globals_dict) | |
147 | if not lines: |
|
147 | if not lines: | |
148 | raise IOError('could not get source code') |
|
148 | raise IOError('could not get source code') | |
149 |
|
149 | |||
150 | if ismodule(object): |
|
150 | if ismodule(object): | |
151 | return lines, 0 |
|
151 | return lines, 0 | |
152 |
|
152 | |||
153 | if isclass(object): |
|
153 | if isclass(object): | |
154 | name = object.__name__ |
|
154 | name = object.__name__ | |
155 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
155 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') | |
156 | # make some effort to find the best matching class definition: |
|
156 | # make some effort to find the best matching class definition: | |
157 | # use the one with the least indentation, which is the one |
|
157 | # use the one with the least indentation, which is the one | |
158 | # that's most probably not inside a function definition. |
|
158 | # that's most probably not inside a function definition. | |
159 | candidates = [] |
|
159 | candidates = [] | |
160 | for i in range(len(lines)): |
|
160 | for i in range(len(lines)): | |
161 | match = pat.match(lines[i]) |
|
161 | match = pat.match(lines[i]) | |
162 | if match: |
|
162 | if match: | |
163 | # if it's at toplevel, it's already the best one |
|
163 | # if it's at toplevel, it's already the best one | |
164 | if lines[i][0] == 'c': |
|
164 | if lines[i][0] == 'c': | |
165 | return lines, i |
|
165 | return lines, i | |
166 | # else add whitespace to candidate list |
|
166 | # else add whitespace to candidate list | |
167 | candidates.append((match.group(1), i)) |
|
167 | candidates.append((match.group(1), i)) | |
168 | if candidates: |
|
168 | if candidates: | |
169 | # this will sort by whitespace, and by line number, |
|
169 | # this will sort by whitespace, and by line number, | |
170 | # less whitespace first |
|
170 | # less whitespace first | |
171 | candidates.sort() |
|
171 | candidates.sort() | |
172 | return lines, candidates[0][1] |
|
172 | return lines, candidates[0][1] | |
173 | else: |
|
173 | else: | |
174 | raise IOError('could not find class definition') |
|
174 | raise IOError('could not find class definition') | |
175 |
|
175 | |||
176 | if ismethod(object): |
|
176 | if ismethod(object): | |
177 | object = object.im_func |
|
177 | object = object.im_func | |
178 | if isfunction(object): |
|
178 | if isfunction(object): | |
179 | object = object.func_code |
|
179 | object = object.func_code | |
180 | if istraceback(object): |
|
180 | if istraceback(object): | |
181 | object = object.tb_frame |
|
181 | object = object.tb_frame | |
182 | if isframe(object): |
|
182 | if isframe(object): | |
183 | object = object.f_code |
|
183 | object = object.f_code | |
184 | if iscode(object): |
|
184 | if iscode(object): | |
185 | if not hasattr(object, 'co_firstlineno'): |
|
185 | if not hasattr(object, 'co_firstlineno'): | |
186 | raise IOError('could not find function definition') |
|
186 | raise IOError('could not find function definition') | |
187 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
187 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') | |
188 | pmatch = pat.match |
|
188 | pmatch = pat.match | |
189 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
189 | # fperez - fix: sometimes, co_firstlineno can give a number larger than | |
190 | # the length of lines, which causes an error. Safeguard against that. |
|
190 | # the length of lines, which causes an error. Safeguard against that. | |
191 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
191 | lnum = min(object.co_firstlineno,len(lines))-1 | |
192 | while lnum > 0: |
|
192 | while lnum > 0: | |
193 | if pmatch(lines[lnum]): break |
|
193 | if pmatch(lines[lnum]): break | |
194 | lnum -= 1 |
|
194 | lnum -= 1 | |
195 |
|
195 | |||
196 | return lines, lnum |
|
196 | return lines, lnum | |
197 | raise IOError('could not find code object') |
|
197 | raise IOError('could not find code object') | |
198 |
|
198 | |||
199 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
199 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 | |
200 | if sys.version_info[:2] >= (2,5): |
|
200 | if sys.version_info[:2] >= (2,5): | |
201 | inspect.findsource = findsource |
|
201 | inspect.findsource = findsource | |
202 |
|
202 | |||
203 | def fix_frame_records_filenames(records): |
|
203 | def fix_frame_records_filenames(records): | |
204 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
204 | """Try to fix the filenames in each record from inspect.getinnerframes(). | |
205 |
|
205 | |||
206 | Particularly, modules loaded from within zip files have useless filenames |
|
206 | Particularly, modules loaded from within zip files have useless filenames | |
207 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
207 | attached to their code object, and inspect.getinnerframes() just uses it. | |
208 | """ |
|
208 | """ | |
209 | fixed_records = [] |
|
209 | fixed_records = [] | |
210 | for frame, filename, line_no, func_name, lines, index in records: |
|
210 | for frame, filename, line_no, func_name, lines, index in records: | |
211 | # Look inside the frame's globals dictionary for __file__, which should |
|
211 | # Look inside the frame's globals dictionary for __file__, which should | |
212 | # be better. |
|
212 | # be better. | |
213 | better_fn = frame.f_globals.get('__file__', None) |
|
213 | better_fn = frame.f_globals.get('__file__', None) | |
214 | if isinstance(better_fn, str): |
|
214 | if isinstance(better_fn, str): | |
215 | # Check the type just in case someone did something weird with |
|
215 | # Check the type just in case someone did something weird with | |
216 | # __file__. It might also be None if the error occurred during |
|
216 | # __file__. It might also be None if the error occurred during | |
217 | # import. |
|
217 | # import. | |
218 | filename = better_fn |
|
218 | filename = better_fn | |
219 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
219 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) | |
220 | return fixed_records |
|
220 | return fixed_records | |
221 |
|
221 | |||
222 |
|
222 | |||
223 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
223 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): | |
224 | import linecache |
|
224 | import linecache | |
225 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
225 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 | |
226 |
|
226 | |||
227 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
227 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) | |
228 |
|
228 | |||
229 | # If the error is at the console, don't build any context, since it would |
|
229 | # If the error is at the console, don't build any context, since it would | |
230 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
230 | # otherwise produce 5 blank lines printed out (there is no file at the | |
231 | # console) |
|
231 | # console) | |
232 | rec_check = records[tb_offset:] |
|
232 | rec_check = records[tb_offset:] | |
233 | try: |
|
233 | try: | |
234 | rname = rec_check[0][1] |
|
234 | rname = rec_check[0][1] | |
235 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
235 | if rname == '<ipython console>' or rname.endswith('<string>'): | |
236 | return rec_check |
|
236 | return rec_check | |
237 | except IndexError: |
|
237 | except IndexError: | |
238 | pass |
|
238 | pass | |
239 |
|
239 | |||
240 | aux = traceback.extract_tb(etb) |
|
240 | aux = traceback.extract_tb(etb) | |
241 | assert len(records) == len(aux) |
|
241 | assert len(records) == len(aux) | |
242 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
242 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): | |
243 | maybeStart = lnum-1 - context//2 |
|
243 | maybeStart = lnum-1 - context//2 | |
244 | start = max(maybeStart, 0) |
|
244 | start = max(maybeStart, 0) | |
245 | end = start + context |
|
245 | end = start + context | |
246 | lines = linecache.getlines(file)[start:end] |
|
246 | lines = linecache.getlines(file)[start:end] | |
247 | # pad with empty lines if necessary |
|
247 | # pad with empty lines if necessary | |
248 | if maybeStart < 0: |
|
248 | if maybeStart < 0: | |
249 | lines = (['\n'] * -maybeStart) + lines |
|
249 | lines = (['\n'] * -maybeStart) + lines | |
250 | if len(lines) < context: |
|
250 | if len(lines) < context: | |
251 | lines += ['\n'] * (context - len(lines)) |
|
251 | lines += ['\n'] * (context - len(lines)) | |
252 | buf = list(records[i]) |
|
252 | buf = list(records[i]) | |
253 | buf[LNUM_POS] = lnum |
|
253 | buf[LNUM_POS] = lnum | |
254 | buf[INDEX_POS] = lnum - 1 - start |
|
254 | buf[INDEX_POS] = lnum - 1 - start | |
255 | buf[LINES_POS] = lines |
|
255 | buf[LINES_POS] = lines | |
256 | records[i] = tuple(buf) |
|
256 | records[i] = tuple(buf) | |
257 | return records[tb_offset:] |
|
257 | return records[tb_offset:] | |
258 |
|
258 | |||
259 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
259 | # Helper function -- largely belongs to VerboseTB, but we need the same | |
260 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
260 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they | |
261 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
261 | # can be recognized properly by ipython.el's py-traceback-line-re | |
262 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
262 | # (SyntaxErrors have to be treated specially because they have no traceback) | |
263 |
|
263 | |||
264 | _parser = PyColorize.Parser() |
|
264 | _parser = PyColorize.Parser() | |
265 |
|
265 | |||
266 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
266 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): | |
267 | numbers_width = INDENT_SIZE - 1 |
|
267 | numbers_width = INDENT_SIZE - 1 | |
268 | res = [] |
|
268 | res = [] | |
269 | i = lnum - index |
|
269 | i = lnum - index | |
270 |
|
270 | |||
271 | # This lets us get fully syntax-highlighted tracebacks. |
|
271 | # This lets us get fully syntax-highlighted tracebacks. | |
272 | if scheme is None: |
|
272 | if scheme is None: | |
273 | ipinst = ipapi.get() |
|
273 | ipinst = ipapi.get() | |
274 | if ipinst is not None: |
|
274 | if ipinst is not None: | |
275 | scheme = ipinst.colors |
|
275 | scheme = ipinst.colors | |
276 | else: |
|
276 | else: | |
277 | scheme = DEFAULT_SCHEME |
|
277 | scheme = DEFAULT_SCHEME | |
278 |
|
278 | |||
279 | _line_format = _parser.format2 |
|
279 | _line_format = _parser.format2 | |
280 |
|
280 | |||
281 | for line in lines: |
|
281 | for line in lines: | |
282 | new_line, err = _line_format(line,'str',scheme) |
|
282 | new_line, err = _line_format(line,'str',scheme) | |
283 | if not err: line = new_line |
|
283 | if not err: line = new_line | |
284 |
|
284 | |||
285 | if i == lnum: |
|
285 | if i == lnum: | |
286 | # This is the line with the error |
|
286 | # This is the line with the error | |
287 | pad = numbers_width - len(str(i)) |
|
287 | pad = numbers_width - len(str(i)) | |
288 | if pad >= 3: |
|
288 | if pad >= 3: | |
289 | marker = '-'*(pad-3) + '-> ' |
|
289 | marker = '-'*(pad-3) + '-> ' | |
290 | elif pad == 2: |
|
290 | elif pad == 2: | |
291 | marker = '> ' |
|
291 | marker = '> ' | |
292 | elif pad == 1: |
|
292 | elif pad == 1: | |
293 | marker = '>' |
|
293 | marker = '>' | |
294 | else: |
|
294 | else: | |
295 | marker = '' |
|
295 | marker = '' | |
296 | num = marker + str(i) |
|
296 | num = marker + str(i) | |
297 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
297 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, | |
298 | Colors.line, line, Colors.Normal) |
|
298 | Colors.line, line, Colors.Normal) | |
299 | else: |
|
299 | else: | |
300 | num = '%*s' % (numbers_width,i) |
|
300 | num = '%*s' % (numbers_width,i) | |
301 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
301 | line = '%s%s%s %s' %(Colors.lineno, num, | |
302 | Colors.Normal, line) |
|
302 | Colors.Normal, line) | |
303 |
|
303 | |||
304 | res.append(line) |
|
304 | res.append(line) | |
305 | if lvals and i == lnum: |
|
305 | if lvals and i == lnum: | |
306 | res.append(lvals + '\n') |
|
306 | res.append(lvals + '\n') | |
307 | i = i + 1 |
|
307 | i = i + 1 | |
308 | return res |
|
308 | return res | |
309 |
|
309 | |||
310 |
|
310 | |||
311 | #--------------------------------------------------------------------------- |
|
311 | #--------------------------------------------------------------------------- | |
312 | # Module classes |
|
312 | # Module classes | |
313 | class TBTools: |
|
313 | class TBTools(object): | |
314 | """Basic tools used by all traceback printer classes.""" |
|
314 | """Basic tools used by all traceback printer classes.""" | |
315 |
|
315 | |||
316 | # This attribute us used in globalipapp.py to have stdout used for |
|
316 | # This attribute us used in globalipapp.py to have stdout used for | |
317 | # writting exceptions. This is needed so nose can trap them. This attribute |
|
317 | # writting exceptions. This is needed so nose can trap them. This attribute | |
318 | # should be None (the default, which will use IPython.utils.io.Term) or |
|
318 | # should be None (the default, which will use IPython.utils.io.Term) or | |
319 | # the string 'stdout' which will cause the override to sys.stdout. |
|
319 | # the string 'stdout' which will cause the override to sys.stdout. | |
320 | out_stream = None |
|
320 | out_stream = None | |
321 |
|
321 | |||
|
322 | # Number of frames to skip when reporting tracebacks | |||
|
323 | tb_offset = 0 | |||
|
324 | ||||
322 | def __init__(self,color_scheme = 'NoColor',call_pdb=False): |
|
325 | def __init__(self,color_scheme = 'NoColor',call_pdb=False): | |
323 | # Whether to call the interactive pdb debugger after printing |
|
326 | # Whether to call the interactive pdb debugger after printing | |
324 | # tracebacks or not |
|
327 | # tracebacks or not | |
325 | self.call_pdb = call_pdb |
|
328 | self.call_pdb = call_pdb | |
326 |
|
329 | |||
327 | # Create color table |
|
330 | # Create color table | |
328 | self.color_scheme_table = exception_colors() |
|
331 | self.color_scheme_table = exception_colors() | |
329 |
|
332 | |||
330 | self.set_colors(color_scheme) |
|
333 | self.set_colors(color_scheme) | |
331 | self.old_scheme = color_scheme # save initial value for toggles |
|
334 | self.old_scheme = color_scheme # save initial value for toggles | |
332 |
|
335 | |||
333 | if call_pdb: |
|
336 | if call_pdb: | |
334 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
337 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) | |
335 | else: |
|
338 | else: | |
336 | self.pdb = None |
|
339 | self.pdb = None | |
337 |
|
340 | |||
338 | def set_colors(self,*args,**kw): |
|
341 | def set_colors(self,*args,**kw): | |
339 | """Shorthand access to the color table scheme selector method.""" |
|
342 | """Shorthand access to the color table scheme selector method.""" | |
340 |
|
343 | |||
341 | # Set own color table |
|
344 | # Set own color table | |
342 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
345 | self.color_scheme_table.set_active_scheme(*args,**kw) | |
343 | # for convenience, set Colors to the active scheme |
|
346 | # for convenience, set Colors to the active scheme | |
344 | self.Colors = self.color_scheme_table.active_colors |
|
347 | self.Colors = self.color_scheme_table.active_colors | |
345 | # Also set colors of debugger |
|
348 | # Also set colors of debugger | |
346 | if hasattr(self,'pdb') and self.pdb is not None: |
|
349 | if hasattr(self,'pdb') and self.pdb is not None: | |
347 | self.pdb.set_colors(*args,**kw) |
|
350 | self.pdb.set_colors(*args,**kw) | |
348 |
|
351 | |||
349 | def color_toggle(self): |
|
352 | def color_toggle(self): | |
350 | """Toggle between the currently active color scheme and NoColor.""" |
|
353 | """Toggle between the currently active color scheme and NoColor.""" | |
351 |
|
354 | |||
352 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
355 | if self.color_scheme_table.active_scheme_name == 'NoColor': | |
353 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
356 | self.color_scheme_table.set_active_scheme(self.old_scheme) | |
354 | self.Colors = self.color_scheme_table.active_colors |
|
357 | self.Colors = self.color_scheme_table.active_colors | |
355 | else: |
|
358 | else: | |
356 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
359 | self.old_scheme = self.color_scheme_table.active_scheme_name | |
357 | self.color_scheme_table.set_active_scheme('NoColor') |
|
360 | self.color_scheme_table.set_active_scheme('NoColor') | |
358 | self.Colors = self.color_scheme_table.active_colors |
|
361 | self.Colors = self.color_scheme_table.active_colors | |
359 |
|
362 | |||
|
363 | def text(self, etype, value, tb, tb_offset=None, context=5): | |||
|
364 | """Return formatted traceback. | |||
|
365 | ||||
|
366 | Subclasses may override this if they add extra arguments. | |||
|
367 | """ | |||
|
368 | tb_list = self.structured_traceback(etype, value, tb, | |||
|
369 | tb_offset, context) | |||
|
370 | return '\n'.join(tb_list) | |||
|
371 | ||||
|
372 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, | |||
|
373 | context=5, mode=None): | |||
|
374 | """Return a list of traceback frames. | |||
|
375 | ||||
|
376 | Must be implemented by each class. | |||
|
377 | """ | |||
|
378 | raise NotImplementedError() | |||
|
379 | ||||
|
380 | ||||
360 | #--------------------------------------------------------------------------- |
|
381 | #--------------------------------------------------------------------------- | |
361 | class ListTB(TBTools): |
|
382 | class ListTB(TBTools): | |
362 | """Print traceback information from a traceback list, with optional color. |
|
383 | """Print traceback information from a traceback list, with optional color. | |
363 |
|
384 | |||
364 | Calling: requires 3 arguments: |
|
385 | Calling: requires 3 arguments: | |
365 | (etype, evalue, elist) |
|
386 | (etype, evalue, elist) | |
366 | as would be obtained by: |
|
387 | as would be obtained by: | |
367 | etype, evalue, tb = sys.exc_info() |
|
388 | etype, evalue, tb = sys.exc_info() | |
368 | if tb: |
|
389 | if tb: | |
369 | elist = traceback.extract_tb(tb) |
|
390 | elist = traceback.extract_tb(tb) | |
370 | else: |
|
391 | else: | |
371 | elist = None |
|
392 | elist = None | |
372 |
|
393 | |||
373 | It can thus be used by programs which need to process the traceback before |
|
394 | It can thus be used by programs which need to process the traceback before | |
374 | printing (such as console replacements based on the code module from the |
|
395 | printing (such as console replacements based on the code module from the | |
375 | standard library). |
|
396 | standard library). | |
376 |
|
397 | |||
377 | Because they are meant to be called without a full traceback (only a |
|
398 | Because they are meant to be called without a full traceback (only a | |
378 | list), instances of this class can't call the interactive pdb debugger.""" |
|
399 | list), instances of this class can't call the interactive pdb debugger.""" | |
379 |
|
400 | |||
380 | def __init__(self,color_scheme = 'NoColor'): |
|
401 | def __init__(self,color_scheme = 'NoColor'): | |
381 | TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0) |
|
402 | TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0) | |
382 |
|
403 | |||
383 | def __call__(self, etype, value, elist): |
|
404 | def __call__(self, etype, value, elist): | |
384 |
|
|
405 | io.Term.cout.flush() | |
385 |
|
|
406 | io.Term.cerr.write(self.text(etype, value, elist)) | |
386 |
|
|
407 | io.Term.cerr.write('\n') | |
387 |
|
408 | |||
388 |
def structured_traceback(self, etype, value, elist, |
|
409 | def structured_traceback(self, etype, value, elist, tb_offset=None, | |
|
410 | context=5): | |||
389 | """Return a color formatted string with the traceback info. |
|
411 | """Return a color formatted string with the traceback info. | |
390 |
|
412 | |||
391 | Parameters |
|
413 | Parameters | |
392 | ---------- |
|
414 | ---------- | |
393 | etype : exception type |
|
415 | etype : exception type | |
394 | Type of the exception raised. |
|
416 | Type of the exception raised. | |
395 |
|
417 | |||
396 | value : object |
|
418 | value : object | |
397 | Data stored in the exception |
|
419 | Data stored in the exception | |
398 |
|
420 | |||
399 | elist : list |
|
421 | elist : list | |
400 | List of frames, see class docstring for details. |
|
422 | List of frames, see class docstring for details. | |
401 |
|
423 | |||
|
424 | tb_offset : int, optional | |||
|
425 | Number of frames in the traceback to skip. If not given, the | |||
|
426 | instance value is used (set in constructor). | |||
|
427 | ||||
|
428 | context : int, optional | |||
|
429 | Number of lines of context information to print. | |||
|
430 | ||||
402 | Returns |
|
431 | Returns | |
403 | ------- |
|
432 | ------- | |
404 | String with formatted exception. |
|
433 | String with formatted exception. | |
405 | """ |
|
434 | """ | |
406 |
|
435 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | ||
407 | Colors = self.Colors |
|
436 | Colors = self.Colors | |
408 |
out_st |
|
437 | out_list = [] | |
409 | if elist: |
|
438 | if elist: | |
410 | out_string.append('Traceback %s(most recent call last)%s:' % |
|
439 | ||
|
440 | if tb_offset and len(elist) > tb_offset: | |||
|
441 | elist = elist[tb_offset:] | |||
|
442 | ||||
|
443 | out_list.append('Traceback %s(most recent call last)%s:' % | |||
411 | (Colors.normalEm, Colors.Normal) + '\n') |
|
444 | (Colors.normalEm, Colors.Normal) + '\n') | |
412 |
out_st |
|
445 | out_list.extend(self._format_list(elist)) | |
413 | lines = self._format_exception_only(etype, value) |
|
446 | # The exception info should be a single entry in the list. | |
414 | for line in lines[:-1]: |
|
447 | lines = ''.join(self._format_exception_only(etype, value)) | |
415 |
|
|
448 | out_list.append(lines) | |
416 | out_string.append(lines[-1]) |
|
449 | ||
417 | return out_string |
|
450 | # Note: this code originally read: | |
418 |
|
451 | |||
419 | def text(self, etype, value, elist, context=5): |
|
452 | ## for line in lines[:-1]: | |
420 | out_string = ListTB.structured_traceback( |
|
453 | ## out_list.append(" "+line) | |
421 | self, etype, value, elist, context |
|
454 | ## out_list.append(lines[-1]) | |
422 | ) |
|
455 | ||
423 | return ''.join(out_string) |
|
456 | # This means it was indenting everything but the last line by a little | |
|
457 | # bit. I've disabled this for now, but if we see ugliness somewhre we | |||
|
458 | # can restore it. | |||
|
459 | ||||
|
460 | return out_list | |||
424 |
|
461 | |||
425 | def _format_list(self, extracted_list): |
|
462 | def _format_list(self, extracted_list): | |
426 | """Format a list of traceback entry tuples for printing. |
|
463 | """Format a list of traceback entry tuples for printing. | |
427 |
|
464 | |||
428 | Given a list of tuples as returned by extract_tb() or |
|
465 | Given a list of tuples as returned by extract_tb() or | |
429 | extract_stack(), return a list of strings ready for printing. |
|
466 | extract_stack(), return a list of strings ready for printing. | |
430 | Each string in the resulting list corresponds to the item with the |
|
467 | Each string in the resulting list corresponds to the item with the | |
431 | same index in the argument list. Each string ends in a newline; |
|
468 | same index in the argument list. Each string ends in a newline; | |
432 | the strings may contain internal newlines as well, for those items |
|
469 | the strings may contain internal newlines as well, for those items | |
433 | whose source text line is not None. |
|
470 | whose source text line is not None. | |
434 |
|
471 | |||
435 | Lifted almost verbatim from traceback.py |
|
472 | Lifted almost verbatim from traceback.py | |
436 | """ |
|
473 | """ | |
437 |
|
474 | |||
438 | Colors = self.Colors |
|
475 | Colors = self.Colors | |
439 | list = [] |
|
476 | list = [] | |
440 | for filename, lineno, name, line in extracted_list[:-1]: |
|
477 | for filename, lineno, name, line in extracted_list[:-1]: | |
441 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
478 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ | |
442 | (Colors.filename, filename, Colors.Normal, |
|
479 | (Colors.filename, filename, Colors.Normal, | |
443 | Colors.lineno, lineno, Colors.Normal, |
|
480 | Colors.lineno, lineno, Colors.Normal, | |
444 | Colors.name, name, Colors.Normal) |
|
481 | Colors.name, name, Colors.Normal) | |
445 | if line: |
|
482 | if line: | |
446 | item = item + ' %s\n' % line.strip() |
|
483 | item = item + ' %s\n' % line.strip() | |
447 | list.append(item) |
|
484 | list.append(item) | |
448 | # Emphasize the last entry |
|
485 | # Emphasize the last entry | |
449 | filename, lineno, name, line = extracted_list[-1] |
|
486 | filename, lineno, name, line = extracted_list[-1] | |
450 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
487 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ | |
451 | (Colors.normalEm, |
|
488 | (Colors.normalEm, | |
452 | Colors.filenameEm, filename, Colors.normalEm, |
|
489 | Colors.filenameEm, filename, Colors.normalEm, | |
453 | Colors.linenoEm, lineno, Colors.normalEm, |
|
490 | Colors.linenoEm, lineno, Colors.normalEm, | |
454 | Colors.nameEm, name, Colors.normalEm, |
|
491 | Colors.nameEm, name, Colors.normalEm, | |
455 | Colors.Normal) |
|
492 | Colors.Normal) | |
456 | if line: |
|
493 | if line: | |
457 | item = item + '%s %s%s\n' % (Colors.line, line.strip(), |
|
494 | item = item + '%s %s%s\n' % (Colors.line, line.strip(), | |
458 | Colors.Normal) |
|
495 | Colors.Normal) | |
459 | list.append(item) |
|
496 | list.append(item) | |
|
497 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg | |||
460 | return list |
|
498 | return list | |
461 |
|
499 | |||
462 | def _format_exception_only(self, etype, value): |
|
500 | def _format_exception_only(self, etype, value): | |
463 | """Format the exception part of a traceback. |
|
501 | """Format the exception part of a traceback. | |
464 |
|
502 | |||
465 | The arguments are the exception type and value such as given by |
|
503 | The arguments are the exception type and value such as given by | |
466 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
504 | sys.exc_info()[:2]. The return value is a list of strings, each ending | |
467 | in a newline. Normally, the list contains a single string; however, |
|
505 | in a newline. Normally, the list contains a single string; however, | |
468 | for SyntaxError exceptions, it contains several lines that (when |
|
506 | for SyntaxError exceptions, it contains several lines that (when | |
469 | printed) display detailed information about where the syntax error |
|
507 | printed) display detailed information about where the syntax error | |
470 | occurred. The message indicating which exception occurred is the |
|
508 | occurred. The message indicating which exception occurred is the | |
471 | always last string in the list. |
|
509 | always last string in the list. | |
472 |
|
510 | |||
473 | Also lifted nearly verbatim from traceback.py |
|
511 | Also lifted nearly verbatim from traceback.py | |
474 | """ |
|
512 | """ | |
475 |
|
513 | |||
476 | have_filedata = False |
|
514 | have_filedata = False | |
477 | Colors = self.Colors |
|
515 | Colors = self.Colors | |
478 | list = [] |
|
516 | list = [] | |
479 | try: |
|
517 | try: | |
480 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
518 | stype = Colors.excName + etype.__name__ + Colors.Normal | |
481 | except AttributeError: |
|
519 | except AttributeError: | |
482 | stype = etype # String exceptions don't get special coloring |
|
520 | stype = etype # String exceptions don't get special coloring | |
483 | if value is None: |
|
521 | if value is None: | |
484 | list.append( str(stype) + '\n') |
|
522 | list.append( str(stype) + '\n') | |
485 | else: |
|
523 | else: | |
486 | if etype is SyntaxError: |
|
524 | if etype is SyntaxError: | |
487 | try: |
|
525 | try: | |
488 | msg, (filename, lineno, offset, line) = value |
|
526 | msg, (filename, lineno, offset, line) = value | |
489 | except: |
|
527 | except: | |
490 | have_filedata = False |
|
528 | have_filedata = False | |
491 | else: |
|
529 | else: | |
492 | have_filedata = True |
|
530 | have_filedata = True | |
493 | #print 'filename is',filename # dbg |
|
531 | #print 'filename is',filename # dbg | |
494 | if not filename: filename = "<string>" |
|
532 | if not filename: filename = "<string>" | |
495 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
533 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ | |
496 | (Colors.normalEm, |
|
534 | (Colors.normalEm, | |
497 | Colors.filenameEm, filename, Colors.normalEm, |
|
535 | Colors.filenameEm, filename, Colors.normalEm, | |
498 | Colors.linenoEm, lineno, Colors.Normal )) |
|
536 | Colors.linenoEm, lineno, Colors.Normal )) | |
499 | if line is not None: |
|
537 | if line is not None: | |
500 | i = 0 |
|
538 | i = 0 | |
501 | while i < len(line) and line[i].isspace(): |
|
539 | while i < len(line) and line[i].isspace(): | |
502 | i = i+1 |
|
540 | i = i+1 | |
503 | list.append('%s %s%s\n' % (Colors.line, |
|
541 | list.append('%s %s%s\n' % (Colors.line, | |
504 | line.strip(), |
|
542 | line.strip(), | |
505 | Colors.Normal)) |
|
543 | Colors.Normal)) | |
506 | if offset is not None: |
|
544 | if offset is not None: | |
507 | s = ' ' |
|
545 | s = ' ' | |
508 | for c in line[i:offset-1]: |
|
546 | for c in line[i:offset-1]: | |
509 | if c.isspace(): |
|
547 | if c.isspace(): | |
510 | s = s + c |
|
548 | s = s + c | |
511 | else: |
|
549 | else: | |
512 | s = s + ' ' |
|
550 | s = s + ' ' | |
513 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
551 | list.append('%s%s^%s\n' % (Colors.caret, s, | |
514 | Colors.Normal) ) |
|
552 | Colors.Normal) ) | |
515 | value = msg |
|
553 | value = msg | |
516 | s = self._some_str(value) |
|
554 | s = self._some_str(value) | |
517 | if s: |
|
555 | if s: | |
518 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
556 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, | |
519 | Colors.Normal, s)) |
|
557 | Colors.Normal, s)) | |
520 | else: |
|
558 | else: | |
521 | list.append('%s\n' % str(stype)) |
|
559 | list.append('%s\n' % str(stype)) | |
522 |
|
560 | |||
523 | # sync with user hooks |
|
561 | # sync with user hooks | |
524 | if have_filedata: |
|
562 | if have_filedata: | |
525 | ipinst = ipapi.get() |
|
563 | ipinst = ipapi.get() | |
526 | if ipinst is not None: |
|
564 | if ipinst is not None: | |
527 | ipinst.hooks.synchronize_with_editor(filename, lineno, 0) |
|
565 | ipinst.hooks.synchronize_with_editor(filename, lineno, 0) | |
528 |
|
566 | |||
529 | return list |
|
567 | return list | |
530 |
|
568 | |||
|
569 | def get_exception_only(self, etype, value): | |||
|
570 | """Only print the exception type and message, without a traceback. | |||
|
571 | ||||
|
572 | Parameters | |||
|
573 | ---------- | |||
|
574 | etype : exception type | |||
|
575 | value : exception value | |||
|
576 | """ | |||
|
577 | return ListTB.structured_traceback(self, etype, value, []) | |||
|
578 | ||||
|
579 | ||||
531 | def show_exception_only(self, etype, value): |
|
580 | def show_exception_only(self, etype, value): | |
532 | """Only print the exception type and message, without a traceback. |
|
581 | """Only print the exception type and message, without a traceback. | |
533 |
|
582 | |||
534 | Parameters |
|
583 | Parameters | |
535 | ---------- |
|
584 | ---------- | |
536 | etype : exception type |
|
585 | etype : exception type | |
537 | value : exception value |
|
586 | value : exception value | |
538 | """ |
|
587 | """ | |
539 | # This method needs to use __call__ from *this* class, not the one from |
|
588 | # This method needs to use __call__ from *this* class, not the one from | |
540 | # a subclass whose signature or behavior may be different |
|
589 | # a subclass whose signature or behavior may be different | |
541 | if self.out_stream == 'stdout': |
|
590 | if self.out_stream == 'stdout': | |
542 | ostream = sys.stdout |
|
591 | ostream = sys.stdout | |
543 | else: |
|
592 | else: | |
544 |
ostream = |
|
593 | ostream = io.Term.cerr | |
545 | ostream.flush() |
|
594 | ostream.flush() | |
546 |
ostream.write( |
|
595 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) | |
547 | ostream.flush() |
|
596 | ostream.flush() | |
548 |
|
597 | |||
549 | def _some_str(self, value): |
|
598 | def _some_str(self, value): | |
550 | # Lifted from traceback.py |
|
599 | # Lifted from traceback.py | |
551 | try: |
|
600 | try: | |
552 | return str(value) |
|
601 | return str(value) | |
553 | except: |
|
602 | except: | |
554 | return '<unprintable %s object>' % type(value).__name__ |
|
603 | return '<unprintable %s object>' % type(value).__name__ | |
555 |
|
604 | |||
556 | #---------------------------------------------------------------------------- |
|
605 | #---------------------------------------------------------------------------- | |
557 | class VerboseTB(TBTools): |
|
606 | class VerboseTB(TBTools): | |
558 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
607 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead | |
559 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
608 | of HTML. Requires inspect and pydoc. Crazy, man. | |
560 |
|
609 | |||
561 | Modified version which optionally strips the topmost entries from the |
|
610 | Modified version which optionally strips the topmost entries from the | |
562 | traceback, to be used with alternate interpreters (because their own code |
|
611 | traceback, to be used with alternate interpreters (because their own code | |
563 | would appear in the traceback).""" |
|
612 | would appear in the traceback).""" | |
564 |
|
613 | |||
565 | def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0, |
|
614 | def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0, | |
566 | call_pdb = 0, include_vars=1): |
|
615 | call_pdb = 0, include_vars=1): | |
567 | """Specify traceback offset, headers and color scheme. |
|
616 | """Specify traceback offset, headers and color scheme. | |
568 |
|
617 | |||
569 | Define how many frames to drop from the tracebacks. Calling it with |
|
618 | Define how many frames to drop from the tracebacks. Calling it with | |
570 | tb_offset=1 allows use of this handler in interpreters which will have |
|
619 | tb_offset=1 allows use of this handler in interpreters which will have | |
571 | their own code at the top of the traceback (VerboseTB will first |
|
620 | their own code at the top of the traceback (VerboseTB will first | |
572 | remove that frame before printing the traceback info).""" |
|
621 | remove that frame before printing the traceback info).""" | |
573 | TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb) |
|
622 | TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb) | |
574 | self.tb_offset = tb_offset |
|
623 | self.tb_offset = tb_offset | |
575 | self.long_header = long_header |
|
624 | self.long_header = long_header | |
576 | self.include_vars = include_vars |
|
625 | self.include_vars = include_vars | |
577 |
|
626 | |||
578 |
def structured_traceback(self, etype, evalue, etb, |
|
627 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, | |
|
628 | context=5): | |||
579 | """Return a nice text document describing the traceback.""" |
|
629 | """Return a nice text document describing the traceback.""" | |
580 |
|
630 | |||
|
631 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |||
|
632 | ||||
581 | # some locals |
|
633 | # some locals | |
582 | try: |
|
634 | try: | |
583 | etype = etype.__name__ |
|
635 | etype = etype.__name__ | |
584 | except AttributeError: |
|
636 | except AttributeError: | |
585 | pass |
|
637 | pass | |
586 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
638 | Colors = self.Colors # just a shorthand + quicker name lookup | |
587 | ColorsNormal = Colors.Normal # used a lot |
|
639 | ColorsNormal = Colors.Normal # used a lot | |
588 | col_scheme = self.color_scheme_table.active_scheme_name |
|
640 | col_scheme = self.color_scheme_table.active_scheme_name | |
589 | indent = ' '*INDENT_SIZE |
|
641 | indent = ' '*INDENT_SIZE | |
590 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
642 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) | |
591 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
643 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) | |
592 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
644 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) | |
593 |
|
645 | |||
594 | # some internal-use functions |
|
646 | # some internal-use functions | |
595 | def text_repr(value): |
|
647 | def text_repr(value): | |
596 | """Hopefully pretty robust repr equivalent.""" |
|
648 | """Hopefully pretty robust repr equivalent.""" | |
597 | # this is pretty horrible but should always return *something* |
|
649 | # this is pretty horrible but should always return *something* | |
598 | try: |
|
650 | try: | |
599 | return pydoc.text.repr(value) |
|
651 | return pydoc.text.repr(value) | |
600 | except KeyboardInterrupt: |
|
652 | except KeyboardInterrupt: | |
601 | raise |
|
653 | raise | |
602 | except: |
|
654 | except: | |
603 | try: |
|
655 | try: | |
604 | return repr(value) |
|
656 | return repr(value) | |
605 | except KeyboardInterrupt: |
|
657 | except KeyboardInterrupt: | |
606 | raise |
|
658 | raise | |
607 | except: |
|
659 | except: | |
608 | try: |
|
660 | try: | |
609 | # all still in an except block so we catch |
|
661 | # all still in an except block so we catch | |
610 | # getattr raising |
|
662 | # getattr raising | |
611 | name = getattr(value, '__name__', None) |
|
663 | name = getattr(value, '__name__', None) | |
612 | if name: |
|
664 | if name: | |
613 | # ick, recursion |
|
665 | # ick, recursion | |
614 | return text_repr(name) |
|
666 | return text_repr(name) | |
615 | klass = getattr(value, '__class__', None) |
|
667 | klass = getattr(value, '__class__', None) | |
616 | if klass: |
|
668 | if klass: | |
617 | return '%s instance' % text_repr(klass) |
|
669 | return '%s instance' % text_repr(klass) | |
618 | except KeyboardInterrupt: |
|
670 | except KeyboardInterrupt: | |
619 | raise |
|
671 | raise | |
620 | except: |
|
672 | except: | |
621 | return 'UNRECOVERABLE REPR FAILURE' |
|
673 | return 'UNRECOVERABLE REPR FAILURE' | |
622 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
674 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) | |
623 | def nullrepr(value, repr=text_repr): return '' |
|
675 | def nullrepr(value, repr=text_repr): return '' | |
624 |
|
676 | |||
625 | # meat of the code begins |
|
677 | # meat of the code begins | |
626 | try: |
|
678 | try: | |
627 | etype = etype.__name__ |
|
679 | etype = etype.__name__ | |
628 | except AttributeError: |
|
680 | except AttributeError: | |
629 | pass |
|
681 | pass | |
630 |
|
682 | |||
631 | if self.long_header: |
|
683 | if self.long_header: | |
632 | # Header with the exception type, python version, and date |
|
684 | # Header with the exception type, python version, and date | |
633 | pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable |
|
685 | pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable | |
634 | date = time.ctime(time.time()) |
|
686 | date = time.ctime(time.time()) | |
635 |
|
687 | |||
636 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
688 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, | |
637 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
689 | exc, ' '*(75-len(str(etype))-len(pyver)), | |
638 | pyver, string.rjust(date, 75) ) |
|
690 | pyver, string.rjust(date, 75) ) | |
639 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
691 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ | |
640 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
692 | "\ncalls leading up to the error, with the most recent (innermost) call last." | |
641 | else: |
|
693 | else: | |
642 | # Simplified header |
|
694 | # Simplified header | |
643 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
695 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, | |
644 | string.rjust('Traceback (most recent call last)', |
|
696 | string.rjust('Traceback (most recent call last)', | |
645 | 75 - len(str(etype)) ) ) |
|
697 | 75 - len(str(etype)) ) ) | |
646 | frames = [] |
|
698 | frames = [] | |
647 | # Flush cache before calling inspect. This helps alleviate some of the |
|
699 | # Flush cache before calling inspect. This helps alleviate some of the | |
648 | # problems with python 2.3's inspect.py. |
|
700 | # problems with python 2.3's inspect.py. | |
649 | linecache.checkcache() |
|
701 | linecache.checkcache() | |
650 | # Drop topmost frames if requested |
|
702 | # Drop topmost frames if requested | |
651 | try: |
|
703 | try: | |
652 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
704 | # Try the default getinnerframes and Alex's: Alex's fixes some | |
653 | # problems, but it generates empty tracebacks for console errors |
|
705 | # problems, but it generates empty tracebacks for console errors | |
654 | # (5 blanks lines) where none should be returned. |
|
706 | # (5 blanks lines) where none should be returned. | |
655 |
#records = inspect.getinnerframes(etb, context)[ |
|
707 | #records = inspect.getinnerframes(etb, context)[tb_offset:] | |
656 | #print 'python records:', records # dbg |
|
708 | #print 'python records:', records # dbg | |
657 |
records = _fixed_getinnerframes(etb, context, |
|
709 | records = _fixed_getinnerframes(etb, context, tb_offset) | |
658 | #print 'alex records:', records # dbg |
|
710 | #print 'alex records:', records # dbg | |
659 | except: |
|
711 | except: | |
660 |
|
712 | |||
661 | # FIXME: I've been getting many crash reports from python 2.3 |
|
713 | # FIXME: I've been getting many crash reports from python 2.3 | |
662 | # users, traceable to inspect.py. If I can find a small test-case |
|
714 | # users, traceable to inspect.py. If I can find a small test-case | |
663 | # to reproduce this, I should either write a better workaround or |
|
715 | # to reproduce this, I should either write a better workaround or | |
664 | # file a bug report against inspect (if that's the real problem). |
|
716 | # file a bug report against inspect (if that's the real problem). | |
665 | # So far, I haven't been able to find an isolated example to |
|
717 | # So far, I haven't been able to find an isolated example to | |
666 | # reproduce the problem. |
|
718 | # reproduce the problem. | |
667 | inspect_error() |
|
719 | inspect_error() | |
668 |
traceback.print_exc(file= |
|
720 | traceback.print_exc(file=io.Term.cerr) | |
669 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
721 | info('\nUnfortunately, your original traceback can not be constructed.\n') | |
670 | return '' |
|
722 | return '' | |
671 |
|
723 | |||
672 | # build some color string templates outside these nested loops |
|
724 | # build some color string templates outside these nested loops | |
673 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
725 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) | |
674 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
726 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, | |
675 | ColorsNormal) |
|
727 | ColorsNormal) | |
676 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
728 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ | |
677 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
729 | (Colors.vName, Colors.valEm, ColorsNormal) | |
678 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
730 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) | |
679 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
731 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, | |
680 | Colors.vName, ColorsNormal) |
|
732 | Colors.vName, ColorsNormal) | |
681 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
733 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) | |
682 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
734 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) | |
683 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
735 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, | |
684 | ColorsNormal) |
|
736 | ColorsNormal) | |
685 |
|
737 | |||
686 | # now, loop over all records printing context and info |
|
738 | # now, loop over all records printing context and info | |
687 | abspath = os.path.abspath |
|
739 | abspath = os.path.abspath | |
688 | for frame, file, lnum, func, lines, index in records: |
|
740 | for frame, file, lnum, func, lines, index in records: | |
689 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
741 | #print '*** record:',file,lnum,func,lines,index # dbg | |
690 | try: |
|
742 | try: | |
691 | file = file and abspath(file) or '?' |
|
743 | file = file and abspath(file) or '?' | |
692 | except OSError: |
|
744 | except OSError: | |
693 | # if file is '<console>' or something not in the filesystem, |
|
745 | # if file is '<console>' or something not in the filesystem, | |
694 | # the abspath call will throw an OSError. Just ignore it and |
|
746 | # the abspath call will throw an OSError. Just ignore it and | |
695 | # keep the original file string. |
|
747 | # keep the original file string. | |
696 | pass |
|
748 | pass | |
697 | link = tpl_link % file |
|
749 | link = tpl_link % file | |
698 | try: |
|
750 | try: | |
699 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
751 | args, varargs, varkw, locals = inspect.getargvalues(frame) | |
700 | except: |
|
752 | except: | |
701 | # This can happen due to a bug in python2.3. We should be |
|
753 | # This can happen due to a bug in python2.3. We should be | |
702 | # able to remove this try/except when 2.4 becomes a |
|
754 | # able to remove this try/except when 2.4 becomes a | |
703 | # requirement. Bug details at http://python.org/sf/1005466 |
|
755 | # requirement. Bug details at http://python.org/sf/1005466 | |
704 | inspect_error() |
|
756 | inspect_error() | |
705 |
traceback.print_exc(file= |
|
757 | traceback.print_exc(file=io.Term.cerr) | |
706 | info("\nIPython's exception reporting continues...\n") |
|
758 | info("\nIPython's exception reporting continues...\n") | |
707 |
|
759 | |||
708 | if func == '?': |
|
760 | if func == '?': | |
709 | call = '' |
|
761 | call = '' | |
710 | else: |
|
762 | else: | |
711 | # Decide whether to include variable details or not |
|
763 | # Decide whether to include variable details or not | |
712 | var_repr = self.include_vars and eqrepr or nullrepr |
|
764 | var_repr = self.include_vars and eqrepr or nullrepr | |
713 | try: |
|
765 | try: | |
714 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
766 | call = tpl_call % (func,inspect.formatargvalues(args, | |
715 | varargs, varkw, |
|
767 | varargs, varkw, | |
716 | locals,formatvalue=var_repr)) |
|
768 | locals,formatvalue=var_repr)) | |
717 | except KeyError: |
|
769 | except KeyError: | |
718 | # Very odd crash from inspect.formatargvalues(). The |
|
770 | # Very odd crash from inspect.formatargvalues(). The | |
719 | # scenario under which it appeared was a call to |
|
771 | # scenario under which it appeared was a call to | |
720 | # view(array,scale) in NumTut.view.view(), where scale had |
|
772 | # view(array,scale) in NumTut.view.view(), where scale had | |
721 | # been defined as a scalar (it should be a tuple). Somehow |
|
773 | # been defined as a scalar (it should be a tuple). Somehow | |
722 | # inspect messes up resolving the argument list of view() |
|
774 | # inspect messes up resolving the argument list of view() | |
723 | # and barfs out. At some point I should dig into this one |
|
775 | # and barfs out. At some point I should dig into this one | |
724 | # and file a bug report about it. |
|
776 | # and file a bug report about it. | |
725 | inspect_error() |
|
777 | inspect_error() | |
726 |
traceback.print_exc(file= |
|
778 | traceback.print_exc(file=io.Term.cerr) | |
727 | info("\nIPython's exception reporting continues...\n") |
|
779 | info("\nIPython's exception reporting continues...\n") | |
728 | call = tpl_call_fail % func |
|
780 | call = tpl_call_fail % func | |
729 |
|
781 | |||
730 | # Initialize a list of names on the current line, which the |
|
782 | # Initialize a list of names on the current line, which the | |
731 | # tokenizer below will populate. |
|
783 | # tokenizer below will populate. | |
732 | names = [] |
|
784 | names = [] | |
733 |
|
785 | |||
734 | def tokeneater(token_type, token, start, end, line): |
|
786 | def tokeneater(token_type, token, start, end, line): | |
735 | """Stateful tokeneater which builds dotted names. |
|
787 | """Stateful tokeneater which builds dotted names. | |
736 |
|
788 | |||
737 | The list of names it appends to (from the enclosing scope) can |
|
789 | The list of names it appends to (from the enclosing scope) can | |
738 | contain repeated composite names. This is unavoidable, since |
|
790 | contain repeated composite names. This is unavoidable, since | |
739 | there is no way to disambguate partial dotted structures until |
|
791 | there is no way to disambguate partial dotted structures until | |
740 | the full list is known. The caller is responsible for pruning |
|
792 | the full list is known. The caller is responsible for pruning | |
741 | the final list of duplicates before using it.""" |
|
793 | the final list of duplicates before using it.""" | |
742 |
|
794 | |||
743 | # build composite names |
|
795 | # build composite names | |
744 | if token == '.': |
|
796 | if token == '.': | |
745 | try: |
|
797 | try: | |
746 | names[-1] += '.' |
|
798 | names[-1] += '.' | |
747 | # store state so the next token is added for x.y.z names |
|
799 | # store state so the next token is added for x.y.z names | |
748 | tokeneater.name_cont = True |
|
800 | tokeneater.name_cont = True | |
749 | return |
|
801 | return | |
750 | except IndexError: |
|
802 | except IndexError: | |
751 | pass |
|
803 | pass | |
752 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
804 | if token_type == tokenize.NAME and token not in keyword.kwlist: | |
753 | if tokeneater.name_cont: |
|
805 | if tokeneater.name_cont: | |
754 | # Dotted names |
|
806 | # Dotted names | |
755 | names[-1] += token |
|
807 | names[-1] += token | |
756 | tokeneater.name_cont = False |
|
808 | tokeneater.name_cont = False | |
757 | else: |
|
809 | else: | |
758 | # Regular new names. We append everything, the caller |
|
810 | # Regular new names. We append everything, the caller | |
759 | # will be responsible for pruning the list later. It's |
|
811 | # will be responsible for pruning the list later. It's | |
760 | # very tricky to try to prune as we go, b/c composite |
|
812 | # very tricky to try to prune as we go, b/c composite | |
761 | # names can fool us. The pruning at the end is easy |
|
813 | # names can fool us. The pruning at the end is easy | |
762 | # to do (or the caller can print a list with repeated |
|
814 | # to do (or the caller can print a list with repeated | |
763 | # names if so desired. |
|
815 | # names if so desired. | |
764 | names.append(token) |
|
816 | names.append(token) | |
765 | elif token_type == tokenize.NEWLINE: |
|
817 | elif token_type == tokenize.NEWLINE: | |
766 | raise IndexError |
|
818 | raise IndexError | |
767 | # we need to store a bit of state in the tokenizer to build |
|
819 | # we need to store a bit of state in the tokenizer to build | |
768 | # dotted names |
|
820 | # dotted names | |
769 | tokeneater.name_cont = False |
|
821 | tokeneater.name_cont = False | |
770 |
|
822 | |||
771 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
823 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): | |
772 | line = getline(file, lnum[0]) |
|
824 | line = getline(file, lnum[0]) | |
773 | lnum[0] += 1 |
|
825 | lnum[0] += 1 | |
774 | return line |
|
826 | return line | |
775 |
|
827 | |||
776 | # Build the list of names on this line of code where the exception |
|
828 | # Build the list of names on this line of code where the exception | |
777 | # occurred. |
|
829 | # occurred. | |
778 | try: |
|
830 | try: | |
779 | # This builds the names list in-place by capturing it from the |
|
831 | # This builds the names list in-place by capturing it from the | |
780 | # enclosing scope. |
|
832 | # enclosing scope. | |
781 | tokenize.tokenize(linereader, tokeneater) |
|
833 | tokenize.tokenize(linereader, tokeneater) | |
782 | except IndexError: |
|
834 | except IndexError: | |
783 | # signals exit of tokenizer |
|
835 | # signals exit of tokenizer | |
784 | pass |
|
836 | pass | |
785 | except tokenize.TokenError,msg: |
|
837 | except tokenize.TokenError,msg: | |
786 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
838 | _m = ("An unexpected error occurred while tokenizing input\n" | |
787 | "The following traceback may be corrupted or invalid\n" |
|
839 | "The following traceback may be corrupted or invalid\n" | |
788 | "The error message is: %s\n" % msg) |
|
840 | "The error message is: %s\n" % msg) | |
789 | error(_m) |
|
841 | error(_m) | |
790 |
|
842 | |||
791 | # prune names list of duplicates, but keep the right order |
|
843 | # prune names list of duplicates, but keep the right order | |
792 | unique_names = uniq_stable(names) |
|
844 | unique_names = uniq_stable(names) | |
793 |
|
845 | |||
794 | # Start loop over vars |
|
846 | # Start loop over vars | |
795 | lvals = [] |
|
847 | lvals = [] | |
796 | if self.include_vars: |
|
848 | if self.include_vars: | |
797 | for name_full in unique_names: |
|
849 | for name_full in unique_names: | |
798 | name_base = name_full.split('.',1)[0] |
|
850 | name_base = name_full.split('.',1)[0] | |
799 | if name_base in frame.f_code.co_varnames: |
|
851 | if name_base in frame.f_code.co_varnames: | |
800 | if locals.has_key(name_base): |
|
852 | if locals.has_key(name_base): | |
801 | try: |
|
853 | try: | |
802 | value = repr(eval(name_full,locals)) |
|
854 | value = repr(eval(name_full,locals)) | |
803 | except: |
|
855 | except: | |
804 | value = undefined |
|
856 | value = undefined | |
805 | else: |
|
857 | else: | |
806 | value = undefined |
|
858 | value = undefined | |
807 | name = tpl_local_var % name_full |
|
859 | name = tpl_local_var % name_full | |
808 | else: |
|
860 | else: | |
809 | if frame.f_globals.has_key(name_base): |
|
861 | if frame.f_globals.has_key(name_base): | |
810 | try: |
|
862 | try: | |
811 | value = repr(eval(name_full,frame.f_globals)) |
|
863 | value = repr(eval(name_full,frame.f_globals)) | |
812 | except: |
|
864 | except: | |
813 | value = undefined |
|
865 | value = undefined | |
814 | else: |
|
866 | else: | |
815 | value = undefined |
|
867 | value = undefined | |
816 | name = tpl_global_var % name_full |
|
868 | name = tpl_global_var % name_full | |
817 | lvals.append(tpl_name_val % (name,value)) |
|
869 | lvals.append(tpl_name_val % (name,value)) | |
818 | if lvals: |
|
870 | if lvals: | |
819 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
871 | lvals = '%s%s' % (indent,em_normal.join(lvals)) | |
820 | else: |
|
872 | else: | |
821 | lvals = '' |
|
873 | lvals = '' | |
822 |
|
874 | |||
823 | level = '%s %s\n' % (link,call) |
|
875 | level = '%s %s\n' % (link,call) | |
824 |
|
876 | |||
825 | if index is None: |
|
877 | if index is None: | |
826 | frames.append(level) |
|
878 | frames.append(level) | |
827 | else: |
|
879 | else: | |
828 | frames.append('%s%s' % (level,''.join( |
|
880 | frames.append('%s%s' % (level,''.join( | |
829 | _format_traceback_lines(lnum,index,lines,Colors,lvals, |
|
881 | _format_traceback_lines(lnum,index,lines,Colors,lvals, | |
830 | col_scheme)))) |
|
882 | col_scheme)))) | |
831 |
|
883 | |||
832 | # Get (safely) a string form of the exception info |
|
884 | # Get (safely) a string form of the exception info | |
833 | try: |
|
885 | try: | |
834 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
886 | etype_str,evalue_str = map(str,(etype,evalue)) | |
835 | except: |
|
887 | except: | |
836 | # User exception is improperly defined. |
|
888 | # User exception is improperly defined. | |
837 | etype,evalue = str,sys.exc_info()[:2] |
|
889 | etype,evalue = str,sys.exc_info()[:2] | |
838 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
890 | etype_str,evalue_str = map(str,(etype,evalue)) | |
839 | # ... and format it |
|
891 | # ... and format it | |
840 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
892 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, | |
841 | ColorsNormal, evalue_str)] |
|
893 | ColorsNormal, evalue_str)] | |
842 | if type(evalue) is types.InstanceType: |
|
894 | if type(evalue) is types.InstanceType: | |
843 | try: |
|
895 | try: | |
844 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
896 | names = [w for w in dir(evalue) if isinstance(w, basestring)] | |
845 | except: |
|
897 | except: | |
846 | # Every now and then, an object with funny inernals blows up |
|
898 | # Every now and then, an object with funny inernals blows up | |
847 | # when dir() is called on it. We do the best we can to report |
|
899 | # when dir() is called on it. We do the best we can to report | |
848 | # the problem and continue |
|
900 | # the problem and continue | |
849 | _m = '%sException reporting error (object with broken dir())%s:' |
|
901 | _m = '%sException reporting error (object with broken dir())%s:' | |
850 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
902 | exception.append(_m % (Colors.excName,ColorsNormal)) | |
851 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
903 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) | |
852 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
904 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, | |
853 | ColorsNormal, evalue_str)) |
|
905 | ColorsNormal, evalue_str)) | |
854 | names = [] |
|
906 | names = [] | |
855 | for name in names: |
|
907 | for name in names: | |
856 | value = text_repr(getattr(evalue, name)) |
|
908 | value = text_repr(getattr(evalue, name)) | |
857 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
909 | exception.append('\n%s%s = %s' % (indent, name, value)) | |
858 |
|
910 | |||
859 | # vds: >> |
|
911 | # vds: >> | |
860 | if records: |
|
912 | if records: | |
861 | filepath, lnum = records[-1][1:3] |
|
913 | filepath, lnum = records[-1][1:3] | |
862 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
914 | #print "file:", str(file), "linenb", str(lnum) # dbg | |
863 | filepath = os.path.abspath(filepath) |
|
915 | filepath = os.path.abspath(filepath) | |
864 | ipinst = ipapi.get() |
|
916 | ipinst = ipapi.get() | |
865 | if ipinst is not None: |
|
917 | if ipinst is not None: | |
866 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
918 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) | |
867 | # vds: << |
|
919 | # vds: << | |
868 |
|
920 | |||
869 | # return all our info assembled as a single string |
|
921 | # return all our info assembled as a single string | |
870 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
922 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) | |
871 | return [head] + frames + [''.join(exception[0])] |
|
923 | return [head] + frames + [''.join(exception[0])] | |
872 |
|
924 | |||
873 | def text(self, etype, evalue, etb, context=5): |
|
|||
874 | tb_list = VerboseTB.structured_traceback( |
|
|||
875 | self, etype, evalue, etb, context |
|
|||
876 | ) |
|
|||
877 | return '\n'.join(tb_list) |
|
|||
878 |
|
||||
879 | def debugger(self,force=False): |
|
925 | def debugger(self,force=False): | |
880 | """Call up the pdb debugger if desired, always clean up the tb |
|
926 | """Call up the pdb debugger if desired, always clean up the tb | |
881 | reference. |
|
927 | reference. | |
882 |
|
928 | |||
883 | Keywords: |
|
929 | Keywords: | |
884 |
|
930 | |||
885 | - force(False): by default, this routine checks the instance call_pdb |
|
931 | - force(False): by default, this routine checks the instance call_pdb | |
886 | flag and does not actually invoke the debugger if the flag is false. |
|
932 | flag and does not actually invoke the debugger if the flag is false. | |
887 | The 'force' option forces the debugger to activate even if the flag |
|
933 | The 'force' option forces the debugger to activate even if the flag | |
888 | is false. |
|
934 | is false. | |
889 |
|
935 | |||
890 | If the call_pdb flag is set, the pdb interactive debugger is |
|
936 | If the call_pdb flag is set, the pdb interactive debugger is | |
891 | invoked. In all cases, the self.tb reference to the current traceback |
|
937 | invoked. In all cases, the self.tb reference to the current traceback | |
892 | is deleted to prevent lingering references which hamper memory |
|
938 | is deleted to prevent lingering references which hamper memory | |
893 | management. |
|
939 | management. | |
894 |
|
940 | |||
895 | Note that each call to pdb() does an 'import readline', so if your app |
|
941 | Note that each call to pdb() does an 'import readline', so if your app | |
896 | requires a special setup for the readline completers, you'll have to |
|
942 | requires a special setup for the readline completers, you'll have to | |
897 | fix that by hand after invoking the exception handler.""" |
|
943 | fix that by hand after invoking the exception handler.""" | |
898 |
|
944 | |||
899 | if force or self.call_pdb: |
|
945 | if force or self.call_pdb: | |
900 | if self.pdb is None: |
|
946 | if self.pdb is None: | |
901 | self.pdb = debugger.Pdb( |
|
947 | self.pdb = debugger.Pdb( | |
902 | self.color_scheme_table.active_scheme_name) |
|
948 | self.color_scheme_table.active_scheme_name) | |
903 | # the system displayhook may have changed, restore the original |
|
949 | # the system displayhook may have changed, restore the original | |
904 | # for pdb |
|
950 | # for pdb | |
905 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
951 | display_trap = DisplayTrap(hook=sys.__displayhook__) | |
906 | with display_trap: |
|
952 | with display_trap: | |
907 | self.pdb.reset() |
|
953 | self.pdb.reset() | |
908 | # Find the right frame so we don't pop up inside ipython itself |
|
954 | # Find the right frame so we don't pop up inside ipython itself | |
909 | if hasattr(self,'tb') and self.tb is not None: |
|
955 | if hasattr(self,'tb') and self.tb is not None: | |
910 | etb = self.tb |
|
956 | etb = self.tb | |
911 | else: |
|
957 | else: | |
912 | etb = self.tb = sys.last_traceback |
|
958 | etb = self.tb = sys.last_traceback | |
913 | while self.tb is not None and self.tb.tb_next is not None: |
|
959 | while self.tb is not None and self.tb.tb_next is not None: | |
914 | self.tb = self.tb.tb_next |
|
960 | self.tb = self.tb.tb_next | |
915 | if etb and etb.tb_next: |
|
961 | if etb and etb.tb_next: | |
916 | etb = etb.tb_next |
|
962 | etb = etb.tb_next | |
917 | self.pdb.botframe = etb.tb_frame |
|
963 | self.pdb.botframe = etb.tb_frame | |
918 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
964 | self.pdb.interaction(self.tb.tb_frame, self.tb) | |
919 |
|
965 | |||
920 | if hasattr(self,'tb'): |
|
966 | if hasattr(self,'tb'): | |
921 | del self.tb |
|
967 | del self.tb | |
922 |
|
968 | |||
923 | def handler(self, info=None): |
|
969 | def handler(self, info=None): | |
924 | (etype, evalue, etb) = info or sys.exc_info() |
|
970 | (etype, evalue, etb) = info or sys.exc_info() | |
925 | self.tb = etb |
|
971 | self.tb = etb | |
926 |
|
|
972 | io.Term.cout.flush() | |
927 |
|
|
973 | io.Term.cerr.write(self.text(etype, evalue, etb)) | |
928 |
|
|
974 | io.Term.cerr.write('\n') | |
929 |
|
975 | |||
930 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
976 | # Changed so an instance can just be called as VerboseTB_inst() and print | |
931 | # out the right info on its own. |
|
977 | # out the right info on its own. | |
932 | def __call__(self, etype=None, evalue=None, etb=None): |
|
978 | def __call__(self, etype=None, evalue=None, etb=None): | |
933 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
979 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" | |
934 | if etb is None: |
|
980 | if etb is None: | |
935 | self.handler() |
|
981 | self.handler() | |
936 | else: |
|
982 | else: | |
937 | self.handler((etype, evalue, etb)) |
|
983 | self.handler((etype, evalue, etb)) | |
938 | try: |
|
984 | try: | |
939 | self.debugger() |
|
985 | self.debugger() | |
940 | except KeyboardInterrupt: |
|
986 | except KeyboardInterrupt: | |
941 | print "\nKeyboardInterrupt" |
|
987 | print "\nKeyboardInterrupt" | |
942 |
|
988 | |||
943 | #---------------------------------------------------------------------------- |
|
989 | #---------------------------------------------------------------------------- | |
944 | class FormattedTB(VerboseTB,ListTB): |
|
990 | class FormattedTB(VerboseTB, ListTB): | |
945 | """Subclass ListTB but allow calling with a traceback. |
|
991 | """Subclass ListTB but allow calling with a traceback. | |
946 |
|
992 | |||
947 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
993 | It can thus be used as a sys.excepthook for Python > 2.1. | |
948 |
|
994 | |||
949 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
995 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. | |
950 |
|
996 | |||
951 | Allows a tb_offset to be specified. This is useful for situations where |
|
997 | Allows a tb_offset to be specified. This is useful for situations where | |
952 | one needs to remove a number of topmost frames from the traceback (such as |
|
998 | one needs to remove a number of topmost frames from the traceback (such as | |
953 | occurs with python programs that themselves execute other python code, |
|
999 | occurs with python programs that themselves execute other python code, | |
954 | like Python shells). """ |
|
1000 | like Python shells). """ | |
955 |
|
1001 | |||
956 |
def __init__(self, mode |
|
1002 | def __init__(self, mode='Plain', color_scheme='Linux', | |
957 |
tb_offset |
|
1003 | tb_offset=0, long_header=0, call_pdb=0, include_vars=0): | |
958 |
|
1004 | |||
959 | # NEVER change the order of this list. Put new modes at the end: |
|
1005 | # NEVER change the order of this list. Put new modes at the end: | |
960 | self.valid_modes = ['Plain','Context','Verbose'] |
|
1006 | self.valid_modes = ['Plain','Context','Verbose'] | |
961 | self.verbose_modes = self.valid_modes[1:3] |
|
1007 | self.verbose_modes = self.valid_modes[1:3] | |
962 |
|
1008 | |||
963 | VerboseTB.__init__(self,color_scheme,tb_offset,long_header, |
|
1009 | VerboseTB.__init__(self,color_scheme,tb_offset,long_header, | |
964 | call_pdb=call_pdb,include_vars=include_vars) |
|
1010 | call_pdb=call_pdb,include_vars=include_vars) | |
965 | self.set_mode(mode) |
|
1011 | self.set_mode(mode) | |
966 |
|
1012 | |||
967 | def _extract_tb(self,tb): |
|
1013 | def _extract_tb(self,tb): | |
968 | if tb: |
|
1014 | if tb: | |
969 | return traceback.extract_tb(tb) |
|
1015 | return traceback.extract_tb(tb) | |
970 | else: |
|
1016 | else: | |
971 | return None |
|
1017 | return None | |
972 |
|
1018 | |||
973 |
def structured_traceback(self, etype, value, tb, |
|
1019 | def structured_traceback(self, etype, value, tb, tb_offset=None, | |
|
1020 | context=5, mode=None): | |||
|
1021 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |||
974 | mode = self.mode if mode is None else mode |
|
1022 | mode = self.mode if mode is None else mode | |
975 | if mode in self.verbose_modes: |
|
1023 | if mode in self.verbose_modes: | |
976 | # Verbose modes need a full traceback |
|
1024 | # Verbose modes need a full traceback | |
977 | return VerboseTB.structured_traceback( |
|
1025 | return VerboseTB.structured_traceback( | |
978 | self, etype, value, tb, context |
|
1026 | self, etype, value, tb, tb_offset, context | |
979 | ) |
|
1027 | ) | |
980 | else: |
|
1028 | else: | |
981 | # We must check the source cache because otherwise we can print |
|
1029 | # We must check the source cache because otherwise we can print | |
982 | # out-of-date source code. |
|
1030 | # out-of-date source code. | |
983 | linecache.checkcache() |
|
1031 | linecache.checkcache() | |
984 | # Now we can extract and format the exception |
|
1032 | # Now we can extract and format the exception | |
985 | elist = self._extract_tb(tb) |
|
1033 | elist = self._extract_tb(tb) | |
986 | if len(elist) > self.tb_offset: |
|
|||
987 | del elist[:self.tb_offset] |
|
|||
988 | return ListTB.structured_traceback( |
|
1034 | return ListTB.structured_traceback( | |
989 | self, etype, value, elist, context |
|
1035 | self, etype, value, elist, tb_offset, context | |
990 | ) |
|
1036 | ) | |
991 |
|
1037 | |||
992 | def text(self, etype, value, tb, context=5, mode=None): |
|
1038 | def text(self, etype, value, tb, tb_offset=None, context=5, mode=None): | |
993 | """Return formatted traceback. |
|
1039 | """Return formatted traceback. | |
994 |
|
1040 | |||
995 | If the optional mode parameter is given, it overrides the current |
|
1041 | If the optional mode parameter is given, it overrides the current | |
996 | mode.""" |
|
1042 | mode.""" | |
997 | tb_list = FormattedTB.structured_traceback( |
|
1043 | ||
998 | self, etype, value, tb, context, mode |
|
1044 | mode = self.mode if mode is None else mode | |
999 | ) |
|
1045 | tb_list = self.structured_traceback(etype, value, tb, tb_offset, | |
|
1046 | context, mode) | |||
1000 | return '\n'.join(tb_list) |
|
1047 | return '\n'.join(tb_list) | |
|
1048 | ||||
1001 |
|
1049 | |||
1002 | def set_mode(self,mode=None): |
|
1050 | def set_mode(self,mode=None): | |
1003 | """Switch to the desired mode. |
|
1051 | """Switch to the desired mode. | |
1004 |
|
1052 | |||
1005 | If mode is not specified, cycles through the available modes.""" |
|
1053 | If mode is not specified, cycles through the available modes.""" | |
1006 |
|
1054 | |||
1007 | if not mode: |
|
1055 | if not mode: | |
1008 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
1056 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ | |
1009 | len(self.valid_modes) |
|
1057 | len(self.valid_modes) | |
1010 | self.mode = self.valid_modes[new_idx] |
|
1058 | self.mode = self.valid_modes[new_idx] | |
1011 | elif mode not in self.valid_modes: |
|
1059 | elif mode not in self.valid_modes: | |
1012 | raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ |
|
1060 | raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ | |
1013 | 'Valid modes: '+str(self.valid_modes) |
|
1061 | 'Valid modes: '+str(self.valid_modes) | |
1014 | else: |
|
1062 | else: | |
1015 | self.mode = mode |
|
1063 | self.mode = mode | |
1016 | # include variable details only in 'Verbose' mode |
|
1064 | # include variable details only in 'Verbose' mode | |
1017 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1065 | self.include_vars = (self.mode == self.valid_modes[2]) | |
1018 |
|
1066 | |||
1019 | # some convenient shorcuts |
|
1067 | # some convenient shorcuts | |
1020 | def plain(self): |
|
1068 | def plain(self): | |
1021 | self.set_mode(self.valid_modes[0]) |
|
1069 | self.set_mode(self.valid_modes[0]) | |
1022 |
|
1070 | |||
1023 | def context(self): |
|
1071 | def context(self): | |
1024 | self.set_mode(self.valid_modes[1]) |
|
1072 | self.set_mode(self.valid_modes[1]) | |
1025 |
|
1073 | |||
1026 | def verbose(self): |
|
1074 | def verbose(self): | |
1027 | self.set_mode(self.valid_modes[2]) |
|
1075 | self.set_mode(self.valid_modes[2]) | |
1028 |
|
1076 | |||
1029 | #---------------------------------------------------------------------------- |
|
1077 | #---------------------------------------------------------------------------- | |
1030 | class AutoFormattedTB(FormattedTB): |
|
1078 | class AutoFormattedTB(FormattedTB): | |
1031 | """A traceback printer which can be called on the fly. |
|
1079 | """A traceback printer which can be called on the fly. | |
1032 |
|
1080 | |||
1033 | It will find out about exceptions by itself. |
|
1081 | It will find out about exceptions by itself. | |
1034 |
|
1082 | |||
1035 | A brief example: |
|
1083 | A brief example: | |
1036 |
|
1084 | |||
1037 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1085 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') | |
1038 | try: |
|
1086 | try: | |
1039 | ... |
|
1087 | ... | |
1040 | except: |
|
1088 | except: | |
1041 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1089 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object | |
1042 | """ |
|
1090 | """ | |
1043 |
|
1091 | |||
1044 | def __call__(self,etype=None,evalue=None,etb=None, |
|
1092 | def __call__(self,etype=None,evalue=None,etb=None, | |
1045 | out=None,tb_offset=None): |
|
1093 | out=None,tb_offset=None): | |
1046 | """Print out a formatted exception traceback. |
|
1094 | """Print out a formatted exception traceback. | |
1047 |
|
1095 | |||
1048 | Optional arguments: |
|
1096 | Optional arguments: | |
1049 | - out: an open file-like object to direct output to. |
|
1097 | - out: an open file-like object to direct output to. | |
1050 |
|
1098 | |||
1051 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1099 | - tb_offset: the number of frames to skip over in the stack, on a | |
1052 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1100 | per-call basis (this overrides temporarily the instance's tb_offset | |
1053 | given at initialization time. """ |
|
1101 | given at initialization time. """ | |
1054 |
|
1102 | |||
1055 | if out is None: |
|
1103 | if out is None: | |
1056 | if self.out_stream == 'stdout': |
|
1104 | if self.out_stream == 'stdout': | |
1057 | out = sys.stdout |
|
1105 | out = sys.stdout | |
1058 | else: |
|
1106 | else: | |
1059 |
out = |
|
1107 | out = io.Term.cerr | |
1060 | out.flush() |
|
1108 | out.flush() | |
1061 | if tb_offset is not None: |
|
1109 | out.write(self.text(etype, evalue, etb, tb_offset)) | |
1062 | tb_offset, self.tb_offset = self.tb_offset, tb_offset |
|
1110 | out.write('\n') | |
1063 | out.write(self.text(etype, evalue, etb)) |
|
|||
1064 | out.write('\n') |
|
|||
1065 | self.tb_offset = tb_offset |
|
|||
1066 | else: |
|
|||
1067 | out.write(self.text(etype, evalue, etb)) |
|
|||
1068 | out.write('\n') |
|
|||
1069 | out.flush() |
|
1111 | out.flush() | |
|
1112 | # FIXME: we should remove the auto pdb behavior from here and leave | |||
|
1113 | # that to the clients. | |||
1070 | try: |
|
1114 | try: | |
1071 | self.debugger() |
|
1115 | self.debugger() | |
1072 | except KeyboardInterrupt: |
|
1116 | except KeyboardInterrupt: | |
1073 | print "\nKeyboardInterrupt" |
|
1117 | print "\nKeyboardInterrupt" | |
1074 |
|
1118 | |||
1075 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1119 | def structured_traceback(self, etype=None, value=None, tb=None, | |
1076 | context=5, mode=None): |
|
1120 | tb_offset=None, context=5, mode=None): | |
1077 | if etype is None: |
|
1121 | if etype is None: | |
1078 | etype,value,tb = sys.exc_info() |
|
1122 | etype,value,tb = sys.exc_info() | |
1079 | self.tb = tb |
|
1123 | self.tb = tb | |
1080 | return FormattedTB.structured_traceback( |
|
1124 | return FormattedTB.structured_traceback( | |
1081 | self, etype, value, tb, context, mode |
|
1125 | self, etype, value, tb, tb_offset, context, mode ) | |
1082 | ) |
|
|||
1083 |
|
||||
1084 | def text(self, etype=None, value=None, tb=None, context=5, mode=None): |
|
|||
1085 | tb_list = AutoFormattedTB.structured_traceback( |
|
|||
1086 | self, etype, value, tb, context, mode |
|
|||
1087 | ) |
|
|||
1088 | return '\n'.join(tb_list) |
|
|||
1089 |
|
1126 | |||
1090 | #--------------------------------------------------------------------------- |
|
1127 | #--------------------------------------------------------------------------- | |
1091 |
|
1128 | |||
1092 | # A simple class to preserve Nathan's original functionality. |
|
1129 | # A simple class to preserve Nathan's original functionality. | |
1093 | class ColorTB(FormattedTB): |
|
1130 | class ColorTB(FormattedTB): | |
1094 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1131 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" | |
1095 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1132 | def __init__(self,color_scheme='Linux',call_pdb=0): | |
1096 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1133 | FormattedTB.__init__(self,color_scheme=color_scheme, | |
1097 | call_pdb=call_pdb) |
|
1134 | call_pdb=call_pdb) | |
1098 |
|
1135 | |||
1099 |
|
1136 | |||
1100 | class SyntaxTB(ListTB): |
|
1137 | class SyntaxTB(ListTB): | |
1101 | """Extension which holds some state: the last exception value""" |
|
1138 | """Extension which holds some state: the last exception value""" | |
1102 |
|
1139 | |||
1103 | def __init__(self,color_scheme = 'NoColor'): |
|
1140 | def __init__(self,color_scheme = 'NoColor'): | |
1104 | ListTB.__init__(self,color_scheme) |
|
1141 | ListTB.__init__(self,color_scheme) | |
1105 | self.last_syntax_error = None |
|
1142 | self.last_syntax_error = None | |
1106 |
|
1143 | |||
1107 | def __call__(self, etype, value, elist): |
|
1144 | def __call__(self, etype, value, elist): | |
1108 | self.last_syntax_error = value |
|
1145 | self.last_syntax_error = value | |
1109 | ListTB.__call__(self,etype,value,elist) |
|
1146 | ListTB.__call__(self,etype,value,elist) | |
1110 |
|
1147 | |||
1111 | def clear_err_state(self): |
|
1148 | def clear_err_state(self): | |
1112 | """Return the current error state and clear it""" |
|
1149 | """Return the current error state and clear it""" | |
1113 | e = self.last_syntax_error |
|
1150 | e = self.last_syntax_error | |
1114 | self.last_syntax_error = None |
|
1151 | self.last_syntax_error = None | |
1115 | return e |
|
1152 | return e | |
1116 |
|
1153 | |||
|
1154 | def text(self, etype, value, tb, tb_offset=None, context=5): | |||
|
1155 | """Return formatted traceback. | |||
|
1156 | ||||
|
1157 | Subclasses may override this if they add extra arguments. | |||
|
1158 | """ | |||
|
1159 | tb_list = self.structured_traceback(etype, value, tb, | |||
|
1160 | tb_offset, context) | |||
|
1161 | return ''.join(tb_list) | |||
|
1162 | ||||
1117 | #---------------------------------------------------------------------------- |
|
1163 | #---------------------------------------------------------------------------- | |
1118 | # module testing (minimal) |
|
1164 | # module testing (minimal) | |
1119 | if __name__ == "__main__": |
|
1165 | if __name__ == "__main__": | |
1120 | def spam(c, (d, e)): |
|
1166 | def spam(c, (d, e)): | |
1121 | x = c + d |
|
1167 | x = c + d | |
1122 | y = c * d |
|
1168 | y = c * d | |
1123 | foo(x, y) |
|
1169 | foo(x, y) | |
1124 |
|
1170 | |||
1125 | def foo(a, b, bar=1): |
|
1171 | def foo(a, b, bar=1): | |
1126 | eggs(a, b + bar) |
|
1172 | eggs(a, b + bar) | |
1127 |
|
1173 | |||
1128 | def eggs(f, g, z=globals()): |
|
1174 | def eggs(f, g, z=globals()): | |
1129 | h = f + g |
|
1175 | h = f + g | |
1130 | i = f - g |
|
1176 | i = f - g | |
1131 | return h / i |
|
1177 | return h / i | |
1132 |
|
1178 | |||
1133 | print '' |
|
1179 | print '' | |
1134 | print '*** Before ***' |
|
1180 | print '*** Before ***' | |
1135 | try: |
|
1181 | try: | |
1136 | print spam(1, (2, 3)) |
|
1182 | print spam(1, (2, 3)) | |
1137 | except: |
|
1183 | except: | |
1138 | traceback.print_exc() |
|
1184 | traceback.print_exc() | |
1139 | print '' |
|
1185 | print '' | |
1140 |
|
1186 | |||
1141 | handler = ColorTB() |
|
1187 | handler = ColorTB() | |
1142 | print '*** ColorTB ***' |
|
1188 | print '*** ColorTB ***' | |
1143 | try: |
|
1189 | try: | |
1144 | print spam(1, (2, 3)) |
|
1190 | print spam(1, (2, 3)) | |
1145 | except: |
|
1191 | except: | |
1146 | apply(handler, sys.exc_info() ) |
|
1192 | apply(handler, sys.exc_info() ) | |
1147 | print '' |
|
1193 | print '' | |
1148 |
|
1194 | |||
1149 | handler = VerboseTB() |
|
1195 | handler = VerboseTB() | |
1150 | print '*** VerboseTB ***' |
|
1196 | print '*** VerboseTB ***' | |
1151 | try: |
|
1197 | try: | |
1152 | print spam(1, (2, 3)) |
|
1198 | print spam(1, (2, 3)) | |
1153 | except: |
|
1199 | except: | |
1154 | apply(handler, sys.exc_info() ) |
|
1200 | apply(handler, sys.exc_info() ) | |
1155 | print '' |
|
1201 | print '' | |
1156 |
|
1202 |
@@ -1,293 +1,301 b'' | |||||
1 | # Standard library imports |
|
1 | # Standard library imports | |
2 | from subprocess import Popen |
|
2 | from subprocess import Popen | |
3 |
|
3 | |||
4 | # System library imports |
|
4 | # System library imports | |
5 | from PyQt4 import QtCore, QtGui |
|
5 | from PyQt4 import QtCore, QtGui | |
6 |
|
6 | |||
7 | # Local imports |
|
7 | # Local imports | |
8 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
8 | from IPython.core.inputsplitter import IPythonInputSplitter | |
9 | from IPython.core.usage import default_banner |
|
9 | from IPython.core.usage import default_banner | |
10 | from frontend_widget import FrontendWidget |
|
10 | from frontend_widget import FrontendWidget | |
11 |
|
11 | |||
12 |
|
12 | |||
13 | class IPythonPromptBlock(object): |
|
13 | class IPythonPromptBlock(object): | |
14 | """ An internal storage object for IPythonWidget. |
|
14 | """ An internal storage object for IPythonWidget. | |
15 | """ |
|
15 | """ | |
16 | def __init__(self, block, length, number): |
|
16 | def __init__(self, block, length, number): | |
17 | self.block = block |
|
17 | self.block = block | |
18 | self.length = length |
|
18 | self.length = length | |
19 | self.number = number |
|
19 | self.number = number | |
20 |
|
20 | |||
21 |
|
21 | |||
22 | class IPythonWidget(FrontendWidget): |
|
22 | class IPythonWidget(FrontendWidget): | |
23 | """ A FrontendWidget for an IPython kernel. |
|
23 | """ A FrontendWidget for an IPython kernel. | |
24 | """ |
|
24 | """ | |
25 |
|
25 | |||
26 | # Signal emitted when an editor is needed for a file and the editor has been |
|
26 | # Signal emitted when an editor is needed for a file and the editor has been | |
27 | # specified as 'custom'. See 'set_editor' for more information. |
|
27 | # specified as 'custom'. See 'set_editor' for more information. | |
28 | custom_edit_requested = QtCore.pyqtSignal(object, object) |
|
28 | custom_edit_requested = QtCore.pyqtSignal(object, object) | |
29 |
|
29 | |||
30 | # The default stylesheet: black text on a white background. |
|
30 | # The default stylesheet: black text on a white background. | |
31 | default_stylesheet = """ |
|
31 | default_stylesheet = """ | |
32 | .error { color: red; } |
|
32 | .error { color: red; } | |
33 | .in-prompt { color: navy; } |
|
33 | .in-prompt { color: navy; } | |
34 | .in-prompt-number { font-weight: bold; } |
|
34 | .in-prompt-number { font-weight: bold; } | |
35 | .out-prompt { color: darkred; } |
|
35 | .out-prompt { color: darkred; } | |
36 | .out-prompt-number { font-weight: bold; } |
|
36 | .out-prompt-number { font-weight: bold; } | |
37 | """ |
|
37 | """ | |
38 |
|
38 | |||
39 | # A dark stylesheet: white text on a black background. |
|
39 | # A dark stylesheet: white text on a black background. | |
40 | dark_stylesheet = """ |
|
40 | dark_stylesheet = """ | |
41 | QPlainTextEdit, QTextEdit { background-color: black; color: white } |
|
41 | QPlainTextEdit, QTextEdit { background-color: black; color: white } | |
42 | QFrame { border: 1px solid grey; } |
|
42 | QFrame { border: 1px solid grey; } | |
43 | .error { color: red; } |
|
43 | .error { color: red; } | |
44 | .in-prompt { color: lime; } |
|
44 | .in-prompt { color: lime; } | |
45 | .in-prompt-number { color: lime; font-weight: bold; } |
|
45 | .in-prompt-number { color: lime; font-weight: bold; } | |
46 | .out-prompt { color: red; } |
|
46 | .out-prompt { color: red; } | |
47 | .out-prompt-number { color: red; font-weight: bold; } |
|
47 | .out-prompt-number { color: red; font-weight: bold; } | |
48 | """ |
|
48 | """ | |
49 |
|
49 | |||
50 | # Default prompts. |
|
50 | # Default prompts. | |
51 | in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' |
|
51 | in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' | |
52 | out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' |
|
52 | out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' | |
53 |
|
53 | |||
54 | # FrontendWidget protected class variables. |
|
54 | # FrontendWidget protected class variables. | |
55 | #_input_splitter_class = IPythonInputSplitter |
|
55 | #_input_splitter_class = IPythonInputSplitter | |
56 |
|
56 | |||
57 | # IPythonWidget protected class variables. |
|
57 | # IPythonWidget protected class variables. | |
58 | _payload_source_edit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic' |
|
58 | _payload_source_edit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic' | |
59 | _payload_source_page = 'IPython.zmq.page.page' |
|
59 | _payload_source_page = 'IPython.zmq.page.page' | |
60 |
|
60 | |||
61 | #--------------------------------------------------------------------------- |
|
61 | #--------------------------------------------------------------------------- | |
62 | # 'object' interface |
|
62 | # 'object' interface | |
63 | #--------------------------------------------------------------------------- |
|
63 | #--------------------------------------------------------------------------- | |
64 |
|
64 | |||
65 | def __init__(self, *args, **kw): |
|
65 | def __init__(self, *args, **kw): | |
66 | super(IPythonWidget, self).__init__(*args, **kw) |
|
66 | super(IPythonWidget, self).__init__(*args, **kw) | |
67 |
|
67 | |||
68 | # IPythonWidget protected variables. |
|
68 | # IPythonWidget protected variables. | |
69 | self._previous_prompt_obj = None |
|
69 | self._previous_prompt_obj = None | |
70 |
|
70 | |||
71 | # Set a default editor and stylesheet. |
|
71 | # Set a default editor and stylesheet. | |
72 | self.set_editor('default') |
|
72 | self.set_editor('default') | |
73 | self.reset_styling() |
|
73 | self.reset_styling() | |
74 |
|
74 | |||
75 | #--------------------------------------------------------------------------- |
|
75 | #--------------------------------------------------------------------------- | |
76 | # 'BaseFrontendMixin' abstract interface |
|
76 | # 'BaseFrontendMixin' abstract interface | |
77 | #--------------------------------------------------------------------------- |
|
77 | #--------------------------------------------------------------------------- | |
78 |
|
78 | |||
79 | def _handle_pyout(self, msg): |
|
79 | def _handle_pyout(self, msg): | |
80 | """ Reimplemented for IPython-style "display hook". |
|
80 | """ Reimplemented for IPython-style "display hook". | |
81 | """ |
|
81 | """ | |
82 | if not self._hidden and self._is_from_this_session(msg): |
|
82 | if not self._hidden and self._is_from_this_session(msg): | |
83 | content = msg['content'] |
|
83 | content = msg['content'] | |
84 | prompt_number = content['prompt_number'] |
|
84 | prompt_number = content['prompt_number'] | |
85 | self._append_plain_text(content['output_sep']) |
|
85 | self._append_plain_text(content['output_sep']) | |
86 | self._append_html(self._make_out_prompt(prompt_number)) |
|
86 | self._append_html(self._make_out_prompt(prompt_number)) | |
87 | self._append_plain_text(content['data'] + '\n' + |
|
87 | self._append_plain_text(content['data'] + '\n' + | |
88 | content['output_sep2']) |
|
88 | content['output_sep2']) | |
89 |
|
89 | |||
90 | #--------------------------------------------------------------------------- |
|
90 | #--------------------------------------------------------------------------- | |
91 | # 'FrontendWidget' interface |
|
91 | # 'FrontendWidget' interface | |
92 | #--------------------------------------------------------------------------- |
|
92 | #--------------------------------------------------------------------------- | |
93 |
|
93 | |||
94 | def execute_file(self, path, hidden=False): |
|
94 | def execute_file(self, path, hidden=False): | |
95 | """ Reimplemented to use the 'run' magic. |
|
95 | """ Reimplemented to use the 'run' magic. | |
96 | """ |
|
96 | """ | |
97 | self.execute('run %s' % path, hidden=hidden) |
|
97 | self.execute('%%run %s' % path, hidden=hidden) | |
98 |
|
98 | |||
99 | #--------------------------------------------------------------------------- |
|
99 | #--------------------------------------------------------------------------- | |
100 | # 'FrontendWidget' protected interface |
|
100 | # 'FrontendWidget' protected interface | |
101 | #--------------------------------------------------------------------------- |
|
101 | #--------------------------------------------------------------------------- | |
102 |
|
102 | |||
103 | def _get_banner(self): |
|
103 | def _get_banner(self): | |
104 | """ Reimplemented to return IPython's default banner. |
|
104 | """ Reimplemented to return IPython's default banner. | |
105 | """ |
|
105 | """ | |
106 | return default_banner + '\n' |
|
106 | return default_banner + '\n' | |
107 |
|
107 | |||
108 | def _process_execute_error(self, msg): |
|
108 | def _process_execute_error(self, msg): | |
109 | """ Reimplemented for IPython-style traceback formatting. |
|
109 | """ Reimplemented for IPython-style traceback formatting. | |
110 | """ |
|
110 | """ | |
111 | content = msg['content'] |
|
111 | content = msg['content'] | |
112 | traceback_lines = content['traceback'][:] |
|
|||
113 | traceback = ''.join(traceback_lines) |
|
|||
114 | traceback = traceback.replace(' ', ' ') |
|
|||
115 | traceback = traceback.replace('\n', '<br/>') |
|
|||
116 |
|
112 | |||
117 |
|
|
113 | traceback = '\n'.join(content['traceback']) | |
118 | ename_styled = '<span class="error">%s</span>' % ename |
|
|||
119 | traceback = traceback.replace(ename, ename_styled) |
|
|||
120 |
|
114 | |||
121 | self._append_html(traceback) |
|
115 | if 0: | |
|
116 | # FIXME: for now, tracebacks come as plain text, so we can't use | |||
|
117 | # the html renderer yet. Once we refactor ultratb to produce | |||
|
118 | # properly styled tracebacks, this branch should be the default | |||
|
119 | traceback = traceback.replace(' ', ' ') | |||
|
120 | traceback = traceback.replace('\n', '<br/>') | |||
|
121 | ||||
|
122 | ename = content['ename'] | |||
|
123 | ename_styled = '<span class="error">%s</span>' % ename | |||
|
124 | traceback = traceback.replace(ename, ename_styled) | |||
|
125 | ||||
|
126 | self._append_html(traceback) | |||
|
127 | else: | |||
|
128 | # This is the fallback for now, using plain text with ansi escapes | |||
|
129 | self._append_plain_text(traceback) | |||
122 |
|
130 | |||
123 | def _process_execute_payload(self, item): |
|
131 | def _process_execute_payload(self, item): | |
124 | """ Reimplemented to handle %edit and paging payloads. |
|
132 | """ Reimplemented to handle %edit and paging payloads. | |
125 | """ |
|
133 | """ | |
126 | if item['source'] == self._payload_source_edit: |
|
134 | if item['source'] == self._payload_source_edit: | |
127 | self.edit(item['filename'], item['line_number']) |
|
135 | self.edit(item['filename'], item['line_number']) | |
128 | return True |
|
136 | return True | |
129 | elif item['source'] == self._payload_source_page: |
|
137 | elif item['source'] == self._payload_source_page: | |
130 | self._page(item['data']) |
|
138 | self._page(item['data']) | |
131 | return True |
|
139 | return True | |
132 | else: |
|
140 | else: | |
133 | return False |
|
141 | return False | |
134 |
|
142 | |||
135 | def _show_interpreter_prompt(self, number=None, input_sep='\n'): |
|
143 | def _show_interpreter_prompt(self, number=None, input_sep='\n'): | |
136 | """ Reimplemented for IPython-style prompts. |
|
144 | """ Reimplemented for IPython-style prompts. | |
137 | """ |
|
145 | """ | |
138 | # TODO: If a number was not specified, make a prompt number request. |
|
146 | # TODO: If a number was not specified, make a prompt number request. | |
139 | if number is None: |
|
147 | if number is None: | |
140 | number = 0 |
|
148 | number = 0 | |
141 |
|
149 | |||
142 | # Show a new prompt and save information about it so that it can be |
|
150 | # Show a new prompt and save information about it so that it can be | |
143 | # updated later if the prompt number turns out to be wrong. |
|
151 | # updated later if the prompt number turns out to be wrong. | |
144 | self._append_plain_text(input_sep) |
|
152 | self._append_plain_text(input_sep) | |
145 | self._show_prompt(self._make_in_prompt(number), html=True) |
|
153 | self._show_prompt(self._make_in_prompt(number), html=True) | |
146 | block = self._control.document().lastBlock() |
|
154 | block = self._control.document().lastBlock() | |
147 | length = len(self._prompt) |
|
155 | length = len(self._prompt) | |
148 | self._previous_prompt_obj = IPythonPromptBlock(block, length, number) |
|
156 | self._previous_prompt_obj = IPythonPromptBlock(block, length, number) | |
149 |
|
157 | |||
150 | # Update continuation prompt to reflect (possibly) new prompt length. |
|
158 | # Update continuation prompt to reflect (possibly) new prompt length. | |
151 | self._set_continuation_prompt( |
|
159 | self._set_continuation_prompt( | |
152 | self._make_continuation_prompt(self._prompt), html=True) |
|
160 | self._make_continuation_prompt(self._prompt), html=True) | |
153 |
|
161 | |||
154 | def _show_interpreter_prompt_for_reply(self, msg): |
|
162 | def _show_interpreter_prompt_for_reply(self, msg): | |
155 | """ Reimplemented for IPython-style prompts. |
|
163 | """ Reimplemented for IPython-style prompts. | |
156 | """ |
|
164 | """ | |
157 | # Update the old prompt number if necessary. |
|
165 | # Update the old prompt number if necessary. | |
158 | content = msg['content'] |
|
166 | content = msg['content'] | |
159 | previous_prompt_number = content['prompt_number'] |
|
167 | previous_prompt_number = content['prompt_number'] | |
160 | if self._previous_prompt_obj and \ |
|
168 | if self._previous_prompt_obj and \ | |
161 | self._previous_prompt_obj.number != previous_prompt_number: |
|
169 | self._previous_prompt_obj.number != previous_prompt_number: | |
162 | block = self._previous_prompt_obj.block |
|
170 | block = self._previous_prompt_obj.block | |
163 | if block.isValid(): |
|
171 | if block.isValid(): | |
164 |
|
172 | |||
165 | # Remove the old prompt and insert a new prompt. |
|
173 | # Remove the old prompt and insert a new prompt. | |
166 | cursor = QtGui.QTextCursor(block) |
|
174 | cursor = QtGui.QTextCursor(block) | |
167 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
175 | cursor.movePosition(QtGui.QTextCursor.Right, | |
168 | QtGui.QTextCursor.KeepAnchor, |
|
176 | QtGui.QTextCursor.KeepAnchor, | |
169 | self._previous_prompt_obj.length) |
|
177 | self._previous_prompt_obj.length) | |
170 | prompt = self._make_in_prompt(previous_prompt_number) |
|
178 | prompt = self._make_in_prompt(previous_prompt_number) | |
171 | self._prompt = self._insert_html_fetching_plain_text( |
|
179 | self._prompt = self._insert_html_fetching_plain_text( | |
172 | cursor, prompt) |
|
180 | cursor, prompt) | |
173 |
|
181 | |||
174 | # When the HTML is inserted, Qt blows away the syntax |
|
182 | # When the HTML is inserted, Qt blows away the syntax | |
175 | # highlighting for the line, so we need to rehighlight it. |
|
183 | # highlighting for the line, so we need to rehighlight it. | |
176 | self._highlighter.rehighlightBlock(cursor.block()) |
|
184 | self._highlighter.rehighlightBlock(cursor.block()) | |
177 |
|
185 | |||
178 | self._previous_prompt_obj = None |
|
186 | self._previous_prompt_obj = None | |
179 |
|
187 | |||
180 | # Show a new prompt with the kernel's estimated prompt number. |
|
188 | # Show a new prompt with the kernel's estimated prompt number. | |
181 | next_prompt = content['next_prompt'] |
|
189 | next_prompt = content['next_prompt'] | |
182 | self._show_interpreter_prompt(next_prompt['prompt_number'], |
|
190 | self._show_interpreter_prompt(next_prompt['prompt_number'], | |
183 | next_prompt['input_sep']) |
|
191 | next_prompt['input_sep']) | |
184 |
|
192 | |||
185 | #--------------------------------------------------------------------------- |
|
193 | #--------------------------------------------------------------------------- | |
186 | # 'IPythonWidget' interface |
|
194 | # 'IPythonWidget' interface | |
187 | #--------------------------------------------------------------------------- |
|
195 | #--------------------------------------------------------------------------- | |
188 |
|
196 | |||
189 | def edit(self, filename, line=None): |
|
197 | def edit(self, filename, line=None): | |
190 | """ Opens a Python script for editing. |
|
198 | """ Opens a Python script for editing. | |
191 |
|
199 | |||
192 | Parameters: |
|
200 | Parameters: | |
193 | ----------- |
|
201 | ----------- | |
194 | filename : str |
|
202 | filename : str | |
195 | A path to a local system file. |
|
203 | A path to a local system file. | |
196 |
|
204 | |||
197 | line : int, optional |
|
205 | line : int, optional | |
198 | A line of interest in the file. |
|
206 | A line of interest in the file. | |
199 |
|
207 | |||
200 | Raises: |
|
208 | Raises: | |
201 | ------- |
|
209 | ------- | |
202 | OSError |
|
210 | OSError | |
203 | If the editor command cannot be executed. |
|
211 | If the editor command cannot be executed. | |
204 | """ |
|
212 | """ | |
205 | if self._editor == 'default': |
|
213 | if self._editor == 'default': | |
206 | url = QtCore.QUrl.fromLocalFile(filename) |
|
214 | url = QtCore.QUrl.fromLocalFile(filename) | |
207 | if not QtGui.QDesktopServices.openUrl(url): |
|
215 | if not QtGui.QDesktopServices.openUrl(url): | |
208 | message = 'Failed to open %s with the default application' |
|
216 | message = 'Failed to open %s with the default application' | |
209 | raise OSError(message % repr(filename)) |
|
217 | raise OSError(message % repr(filename)) | |
210 | elif self._editor is None: |
|
218 | elif self._editor is None: | |
211 | self.custom_edit_requested.emit(filename, line) |
|
219 | self.custom_edit_requested.emit(filename, line) | |
212 | else: |
|
220 | else: | |
213 | Popen(self._editor + [filename]) |
|
221 | Popen(self._editor + [filename]) | |
214 |
|
222 | |||
215 | def reset_styling(self): |
|
223 | def reset_styling(self): | |
216 | """ Restores the default IPythonWidget styling. |
|
224 | """ Restores the default IPythonWidget styling. | |
217 | """ |
|
225 | """ | |
218 | self.set_styling(self.default_stylesheet, syntax_style='default') |
|
226 | self.set_styling(self.default_stylesheet, syntax_style='default') | |
219 | #self.set_styling(self.dark_stylesheet, syntax_style='monokai') |
|
227 | #self.set_styling(self.dark_stylesheet, syntax_style='monokai') | |
220 |
|
228 | |||
221 | def set_editor(self, editor): |
|
229 | def set_editor(self, editor): | |
222 | """ Sets the editor to use with the %edit magic. |
|
230 | """ Sets the editor to use with the %edit magic. | |
223 |
|
231 | |||
224 | Parameters: |
|
232 | Parameters: | |
225 | ----------- |
|
233 | ----------- | |
226 | editor : str or sequence of str |
|
234 | editor : str or sequence of str | |
227 | A command suitable for use with Popen. This command will be executed |
|
235 | A command suitable for use with Popen. This command will be executed | |
228 | with a single argument--a filename--when editing is requested. |
|
236 | with a single argument--a filename--when editing is requested. | |
229 |
|
237 | |||
230 | This parameter also takes two special values: |
|
238 | This parameter also takes two special values: | |
231 | 'default' : Files will be edited with the system default |
|
239 | 'default' : Files will be edited with the system default | |
232 | application for Python files. |
|
240 | application for Python files. | |
233 | 'custom' : Emit a 'custom_edit_requested(str, int)' signal |
|
241 | 'custom' : Emit a 'custom_edit_requested(str, int)' signal | |
234 | instead of opening an editor. |
|
242 | instead of opening an editor. | |
235 | """ |
|
243 | """ | |
236 | if editor == 'default': |
|
244 | if editor == 'default': | |
237 | self._editor = 'default' |
|
245 | self._editor = 'default' | |
238 | elif editor == 'custom': |
|
246 | elif editor == 'custom': | |
239 | self._editor = None |
|
247 | self._editor = None | |
240 | elif isinstance(editor, basestring): |
|
248 | elif isinstance(editor, basestring): | |
241 | self._editor = [ editor ] |
|
249 | self._editor = [ editor ] | |
242 | else: |
|
250 | else: | |
243 | self._editor = list(editor) |
|
251 | self._editor = list(editor) | |
244 |
|
252 | |||
245 | def set_styling(self, stylesheet, syntax_style=None): |
|
253 | def set_styling(self, stylesheet, syntax_style=None): | |
246 | """ Sets the IPythonWidget styling. |
|
254 | """ Sets the IPythonWidget styling. | |
247 |
|
255 | |||
248 | Parameters: |
|
256 | Parameters: | |
249 | ----------- |
|
257 | ----------- | |
250 | stylesheet : str |
|
258 | stylesheet : str | |
251 | A CSS stylesheet. The stylesheet can contain classes for: |
|
259 | A CSS stylesheet. The stylesheet can contain classes for: | |
252 | 1. Qt: QPlainTextEdit, QFrame, QWidget, etc |
|
260 | 1. Qt: QPlainTextEdit, QFrame, QWidget, etc | |
253 | 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) |
|
261 | 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) | |
254 | 3. IPython: .error, .in-prompt, .out-prompt, etc. |
|
262 | 3. IPython: .error, .in-prompt, .out-prompt, etc. | |
255 |
|
263 | |||
256 | syntax_style : str or None [default None] |
|
264 | syntax_style : str or None [default None] | |
257 | If specified, use the Pygments style with given name. Otherwise, |
|
265 | If specified, use the Pygments style with given name. Otherwise, | |
258 | the stylesheet is queried for Pygments style information. |
|
266 | the stylesheet is queried for Pygments style information. | |
259 | """ |
|
267 | """ | |
260 | self.setStyleSheet(stylesheet) |
|
268 | self.setStyleSheet(stylesheet) | |
261 | self._control.document().setDefaultStyleSheet(stylesheet) |
|
269 | self._control.document().setDefaultStyleSheet(stylesheet) | |
262 | if self._page_control: |
|
270 | if self._page_control: | |
263 | self._page_control.document().setDefaultStyleSheet(stylesheet) |
|
271 | self._page_control.document().setDefaultStyleSheet(stylesheet) | |
264 |
|
272 | |||
265 | if syntax_style is None: |
|
273 | if syntax_style is None: | |
266 | self._highlighter.set_style_sheet(stylesheet) |
|
274 | self._highlighter.set_style_sheet(stylesheet) | |
267 | else: |
|
275 | else: | |
268 | self._highlighter.set_style(syntax_style) |
|
276 | self._highlighter.set_style(syntax_style) | |
269 |
|
277 | |||
270 | #--------------------------------------------------------------------------- |
|
278 | #--------------------------------------------------------------------------- | |
271 | # 'IPythonWidget' protected interface |
|
279 | # 'IPythonWidget' protected interface | |
272 | #--------------------------------------------------------------------------- |
|
280 | #--------------------------------------------------------------------------- | |
273 |
|
281 | |||
274 | def _make_in_prompt(self, number): |
|
282 | def _make_in_prompt(self, number): | |
275 | """ Given a prompt number, returns an HTML In prompt. |
|
283 | """ Given a prompt number, returns an HTML In prompt. | |
276 | """ |
|
284 | """ | |
277 | body = self.in_prompt % number |
|
285 | body = self.in_prompt % number | |
278 | return '<span class="in-prompt">%s</span>' % body |
|
286 | return '<span class="in-prompt">%s</span>' % body | |
279 |
|
287 | |||
280 | def _make_continuation_prompt(self, prompt): |
|
288 | def _make_continuation_prompt(self, prompt): | |
281 | """ Given a plain text version of an In prompt, returns an HTML |
|
289 | """ Given a plain text version of an In prompt, returns an HTML | |
282 | continuation prompt. |
|
290 | continuation prompt. | |
283 | """ |
|
291 | """ | |
284 | end_chars = '...: ' |
|
292 | end_chars = '...: ' | |
285 | space_count = len(prompt.lstrip('\n')) - len(end_chars) |
|
293 | space_count = len(prompt.lstrip('\n')) - len(end_chars) | |
286 | body = ' ' * space_count + end_chars |
|
294 | body = ' ' * space_count + end_chars | |
287 | return '<span class="in-prompt">%s</span>' % body |
|
295 | return '<span class="in-prompt">%s</span>' % body | |
288 |
|
296 | |||
289 | def _make_out_prompt(self, number): |
|
297 | def _make_out_prompt(self, number): | |
290 | """ Given a prompt number, returns an HTML Out prompt. |
|
298 | """ Given a prompt number, returns an HTML Out prompt. | |
291 | """ |
|
299 | """ | |
292 | body = self.out_prompt % number |
|
300 | body = self.out_prompt % number | |
293 | return '<span class="out-prompt">%s</span>' % body |
|
301 | return '<span class="out-prompt">%s</span>' % body |
@@ -1,80 +1,84 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 |
|
2 | |||
3 | """ A minimal application using the Qt console-style IPython frontend. |
|
3 | """ A minimal application using the Qt console-style IPython frontend. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | # Systemm library imports |
|
6 | # Systemm library imports | |
7 | from PyQt4 import QtCore, QtGui |
|
7 | from PyQt4 import QtCore, QtGui | |
8 |
|
8 | |||
9 | # Local imports |
|
9 | # Local imports | |
10 | from IPython.external.argparse import ArgumentParser |
|
10 | from IPython.external.argparse import ArgumentParser | |
11 | from IPython.frontend.qt.console.frontend_widget import FrontendWidget |
|
11 | from IPython.frontend.qt.console.frontend_widget import FrontendWidget | |
12 | from IPython.frontend.qt.console.ipython_widget import IPythonWidget |
|
12 | from IPython.frontend.qt.console.ipython_widget import IPythonWidget | |
13 | from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget |
|
13 | from IPython.frontend.qt.console.rich_ipython_widget import RichIPythonWidget | |
14 | from IPython.frontend.qt.kernelmanager import QtKernelManager |
|
14 | from IPython.frontend.qt.kernelmanager import QtKernelManager | |
15 |
|
15 | |||
16 | # Constants |
|
16 | # Constants | |
17 | LOCALHOST = '127.0.0.1' |
|
17 | LOCALHOST = '127.0.0.1' | |
18 |
|
18 | |||
19 |
|
19 | |||
20 | def main(): |
|
20 | def main(): | |
21 | """ Entry point for application. |
|
21 | """ Entry point for application. | |
22 | """ |
|
22 | """ | |
23 | # Parse command line arguments. |
|
23 | # Parse command line arguments. | |
24 | parser = ArgumentParser() |
|
24 | parser = ArgumentParser() | |
25 | parser.add_argument('-e', '--existing', action='store_true', |
|
25 | parser.add_argument('-e', '--existing', action='store_true', | |
26 | help='connect to an existing kernel') |
|
26 | help='connect to an existing kernel') | |
27 | parser.add_argument('--ip', type=str, default=LOCALHOST, |
|
27 | parser.add_argument('--ip', type=str, default=LOCALHOST, | |
28 | help='set the kernel\'s IP address [default localhost]') |
|
28 | help='set the kernel\'s IP address [default localhost]') | |
29 | parser.add_argument('--xreq', type=int, metavar='PORT', default=0, |
|
29 | parser.add_argument('--xreq', type=int, metavar='PORT', default=0, | |
30 | help='set the XREQ channel port [default random]') |
|
30 | help='set the XREQ channel port [default random]') | |
31 | parser.add_argument('--sub', type=int, metavar='PORT', default=0, |
|
31 | parser.add_argument('--sub', type=int, metavar='PORT', default=0, | |
32 | help='set the SUB channel port [default random]') |
|
32 | help='set the SUB channel port [default random]') | |
33 | parser.add_argument('--rep', type=int, metavar='PORT', default=0, |
|
33 | parser.add_argument('--rep', type=int, metavar='PORT', default=0, | |
34 | help='set the REP channel port [default random]') |
|
34 | help='set the REP channel port [default random]') | |
35 | group = parser.add_mutually_exclusive_group() |
|
35 | group = parser.add_mutually_exclusive_group() | |
36 | group.add_argument('--pure', action='store_true', help = \ |
|
36 | group.add_argument('--pure', action='store_true', help = \ | |
37 | 'use a pure Python kernel instead of an IPython kernel') |
|
37 | 'use a pure Python kernel instead of an IPython kernel') | |
38 | group.add_argument('--pylab', action='store_true', |
|
38 | group.add_argument('--pylab', action='store_true', | |
39 | help='use a kernel with PyLab enabled') |
|
39 | help='use a kernel with PyLab enabled') | |
40 | parser.add_argument('--rich', action='store_true', |
|
40 | parser.add_argument('--rich', action='store_true', | |
41 | help='use a rich text frontend') |
|
41 | help='use a rich text frontend') | |
42 | args = parser.parse_args() |
|
42 | args = parser.parse_args() | |
43 |
|
43 | |||
44 | # Don't let Qt or ZMQ swallow KeyboardInterupts. |
|
44 | # Don't let Qt or ZMQ swallow KeyboardInterupts. | |
45 | import signal |
|
45 | import signal | |
46 | signal.signal(signal.SIGINT, signal.SIG_DFL) |
|
46 | signal.signal(signal.SIGINT, signal.SIG_DFL) | |
47 |
|
47 | |||
48 | # Create a KernelManager and start a kernel. |
|
48 | # Create a KernelManager and start a kernel. | |
49 | kernel_manager = QtKernelManager(xreq_address=(args.ip, args.xreq), |
|
49 | kernel_manager = QtKernelManager(xreq_address=(args.ip, args.xreq), | |
50 | sub_address=(args.ip, args.sub), |
|
50 | sub_address=(args.ip, args.sub), | |
51 | rep_address=(args.ip, args.rep)) |
|
51 | rep_address=(args.ip, args.rep)) | |
52 | if args.ip == LOCALHOST and not args.existing: |
|
52 | if args.ip == LOCALHOST and not args.existing: | |
53 | if args.pure: |
|
53 | if args.pure: | |
54 | kernel_manager.start_kernel(ipython=False) |
|
54 | kernel_manager.start_kernel(ipython=False) | |
55 | elif args.pylab: |
|
55 | elif args.pylab: | |
56 | if args.rich: |
|
56 | if args.rich: | |
57 | kernel_manager.start_kernel(pylab='payload-svg') |
|
57 | kernel_manager.start_kernel(pylab='payload-svg') | |
58 | else: |
|
58 | else: | |
59 | kernel_manager.start_kernel(pylab='qt4') |
|
59 | kernel_manager.start_kernel(pylab='qt4') | |
60 | else: |
|
60 | else: | |
61 | kernel_manager.start_kernel() |
|
61 | kernel_manager.start_kernel() | |
62 | kernel_manager.start_channels() |
|
62 | kernel_manager.start_channels() | |
63 |
|
63 | |||
|
64 | # FIXME: this is a hack, set colors to lightbg by default in qt terminal | |||
|
65 | # unconditionally, regardless of user settings in config files. | |||
|
66 | kernel_manager.xreq_channel.execute("%colors lightbg") | |||
|
67 | ||||
64 | # Launch the application. |
|
68 | # Launch the application. | |
65 | app = QtGui.QApplication([]) |
|
69 | app = QtGui.QApplication([]) | |
66 | if args.pure: |
|
70 | if args.pure: | |
67 | kind = 'rich' if args.rich else 'plain' |
|
71 | kind = 'rich' if args.rich else 'plain' | |
68 | widget = FrontendWidget(kind=kind) |
|
72 | widget = FrontendWidget(kind=kind) | |
69 | elif args.rich: |
|
73 | elif args.rich: | |
70 | widget = RichIPythonWidget() |
|
74 | widget = RichIPythonWidget() | |
71 | else: |
|
75 | else: | |
72 | widget = IPythonWidget() |
|
76 | widget = IPythonWidget() | |
73 | widget.kernel_manager = kernel_manager |
|
77 | widget.kernel_manager = kernel_manager | |
74 | widget.setWindowTitle('Python' if args.pure else 'IPython') |
|
78 | widget.setWindowTitle('Python' if args.pure else 'IPython') | |
75 | widget.show() |
|
79 | widget.show() | |
76 | app.exec_() |
|
80 | app.exec_() | |
77 |
|
81 | |||
78 |
|
82 | |||
79 | if __name__ == '__main__': |
|
83 | if __name__ == '__main__': | |
80 | main() |
|
84 | main() |
@@ -1,281 +1,286 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | IO related utilities. |
|
3 | IO related utilities. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
7 | # Copyright (C) 2008-2009 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 |
|
||||
17 | import sys |
|
16 | import sys | |
18 | import tempfile |
|
17 | import tempfile | |
19 |
|
18 | |||
20 | from IPython.external.Itpl import itpl, printpl |
|
19 | from IPython.external.Itpl import itpl, printpl | |
21 |
|
20 | |||
22 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
23 | # Code |
|
22 | # Code | |
24 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
25 |
|
24 | |||
26 |
|
25 | |||
27 | class IOStream: |
|
26 | class IOStream: | |
28 |
|
27 | |||
29 | def __init__(self,stream,fallback): |
|
28 | def __init__(self,stream,fallback): | |
30 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
29 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): | |
31 | stream = fallback |
|
30 | stream = fallback | |
32 | self.stream = stream |
|
31 | self.stream = stream | |
33 | self._swrite = stream.write |
|
32 | self._swrite = stream.write | |
34 | self.flush = stream.flush |
|
33 | self.flush = stream.flush | |
35 |
|
34 | |||
36 | def write(self,data): |
|
35 | def write(self,data): | |
37 | try: |
|
36 | try: | |
38 | self._swrite(data) |
|
37 | self._swrite(data) | |
39 | except: |
|
38 | except: | |
40 | try: |
|
39 | try: | |
41 | # print handles some unicode issues which may trip a plain |
|
40 | # print handles some unicode issues which may trip a plain | |
42 | # write() call. Attempt to emulate write() by using a |
|
41 | # write() call. Attempt to emulate write() by using a | |
43 | # trailing comma |
|
42 | # trailing comma | |
44 | print >> self.stream, data, |
|
43 | print >> self.stream, data, | |
45 | except: |
|
44 | except: | |
46 | # if we get here, something is seriously broken. |
|
45 | # if we get here, something is seriously broken. | |
47 | print >> sys.stderr, \ |
|
46 | print >> sys.stderr, \ | |
48 | 'ERROR - failed to write data to stream:', self.stream |
|
47 | 'ERROR - failed to write data to stream:', self.stream | |
49 |
|
48 | |||
50 | # This class used to have a writeln method, but regular files and streams |
|
49 | # This class used to have a writeln method, but regular files and streams | |
51 | # in Python don't have this method. We need to keep this completely |
|
50 | # in Python don't have this method. We need to keep this completely | |
52 | # compatible so we removed it. |
|
51 | # compatible so we removed it. | |
53 |
|
52 | |||
54 | def close(self): |
|
53 | def close(self): | |
55 | pass |
|
54 | pass | |
56 |
|
55 | |||
57 |
|
56 | |||
58 | class IOTerm: |
|
57 | class IOTerm: | |
59 | """ Term holds the file or file-like objects for handling I/O operations. |
|
58 | """ Term holds the file or file-like objects for handling I/O operations. | |
60 |
|
59 | |||
61 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
60 | These are normally just sys.stdin, sys.stdout and sys.stderr but for | |
62 | Windows they can can replaced to allow editing the strings before they are |
|
61 | Windows they can can replaced to allow editing the strings before they are | |
63 | displayed.""" |
|
62 | displayed.""" | |
64 |
|
63 | |||
65 | # In the future, having IPython channel all its I/O operations through |
|
64 | # In the future, having IPython channel all its I/O operations through | |
66 | # this class will make it easier to embed it into other environments which |
|
65 | # this class will make it easier to embed it into other environments which | |
67 | # are not a normal terminal (such as a GUI-based shell) |
|
66 | # are not a normal terminal (such as a GUI-based shell) | |
68 | def __init__(self, cin=None, cout=None, cerr=None): |
|
67 | def __init__(self, cin=None, cout=None, cerr=None): | |
69 | self.cin = IOStream(cin, sys.stdin) |
|
68 | self.cin = IOStream(cin, sys.stdin) | |
70 | self.cout = IOStream(cout, sys.stdout) |
|
69 | self.cout = IOStream(cout, sys.stdout) | |
71 | self.cerr = IOStream(cerr, sys.stderr) |
|
70 | self.cerr = IOStream(cerr, sys.stderr) | |
72 |
|
71 | |||
73 |
|
72 | |||
74 | class Tee(object): |
|
73 | class Tee(object): | |
75 | """A class to duplicate an output stream to stdout/err. |
|
74 | """A class to duplicate an output stream to stdout/err. | |
76 |
|
75 | |||
77 | This works in a manner very similar to the Unix 'tee' command. |
|
76 | This works in a manner very similar to the Unix 'tee' command. | |
78 |
|
77 | |||
79 | When the object is closed or deleted, it closes the original file given to |
|
78 | When the object is closed or deleted, it closes the original file given to | |
80 | it for duplication. |
|
79 | it for duplication. | |
81 | """ |
|
80 | """ | |
82 | # Inspired by: |
|
81 | # Inspired by: | |
83 | # http://mail.python.org/pipermail/python-list/2007-May/442737.html |
|
82 | # http://mail.python.org/pipermail/python-list/2007-May/442737.html | |
84 |
|
83 | |||
85 | def __init__(self, file_or_name, mode=None, channel='stdout'): |
|
84 | def __init__(self, file_or_name, mode=None, channel='stdout'): | |
86 | """Construct a new Tee object. |
|
85 | """Construct a new Tee object. | |
87 |
|
86 | |||
88 | Parameters |
|
87 | Parameters | |
89 | ---------- |
|
88 | ---------- | |
90 | file_or_name : filename or open filehandle (writable) |
|
89 | file_or_name : filename or open filehandle (writable) | |
91 | File that will be duplicated |
|
90 | File that will be duplicated | |
92 |
|
91 | |||
93 | mode : optional, valid mode for open(). |
|
92 | mode : optional, valid mode for open(). | |
94 | If a filename was give, open with this mode. |
|
93 | If a filename was give, open with this mode. | |
95 |
|
94 | |||
96 | channel : str, one of ['stdout', 'stderr'] |
|
95 | channel : str, one of ['stdout', 'stderr'] | |
97 | """ |
|
96 | """ | |
98 | if channel not in ['stdout', 'stderr']: |
|
97 | if channel not in ['stdout', 'stderr']: | |
99 | raise ValueError('Invalid channel spec %s' % channel) |
|
98 | raise ValueError('Invalid channel spec %s' % channel) | |
100 |
|
99 | |||
101 | if hasattr(file, 'write') and hasattr(file, 'seek'): |
|
100 | if hasattr(file, 'write') and hasattr(file, 'seek'): | |
102 | self.file = file_or_name |
|
101 | self.file = file_or_name | |
103 | else: |
|
102 | else: | |
104 | self.file = open(file_or_name, mode) |
|
103 | self.file = open(file_or_name, mode) | |
105 | self.channel = channel |
|
104 | self.channel = channel | |
106 | self.ostream = getattr(sys, channel) |
|
105 | self.ostream = getattr(sys, channel) | |
107 | setattr(sys, channel, self) |
|
106 | setattr(sys, channel, self) | |
108 | self._closed = False |
|
107 | self._closed = False | |
109 |
|
108 | |||
110 | def close(self): |
|
109 | def close(self): | |
111 | """Close the file and restore the channel.""" |
|
110 | """Close the file and restore the channel.""" | |
112 | self.flush() |
|
111 | self.flush() | |
113 | setattr(sys, self.channel, self.ostream) |
|
112 | setattr(sys, self.channel, self.ostream) | |
114 | self.file.close() |
|
113 | self.file.close() | |
115 | self._closed = True |
|
114 | self._closed = True | |
116 |
|
115 | |||
117 | def write(self, data): |
|
116 | def write(self, data): | |
118 | """Write data to both channels.""" |
|
117 | """Write data to both channels.""" | |
119 | self.file.write(data) |
|
118 | self.file.write(data) | |
120 | self.ostream.write(data) |
|
119 | self.ostream.write(data) | |
121 | self.ostream.flush() |
|
120 | self.ostream.flush() | |
122 |
|
121 | |||
123 | def flush(self): |
|
122 | def flush(self): | |
124 | """Flush both channels.""" |
|
123 | """Flush both channels.""" | |
125 | self.file.flush() |
|
124 | self.file.flush() | |
126 | self.ostream.flush() |
|
125 | self.ostream.flush() | |
127 |
|
126 | |||
128 | def __del__(self): |
|
127 | def __del__(self): | |
129 | if not self._closed: |
|
128 | if not self._closed: | |
130 | self.close() |
|
129 | self.close() | |
131 |
|
130 | |||
132 |
|
131 | |||
133 | def file_read(filename): |
|
132 | def file_read(filename): | |
134 | """Read a file and close it. Returns the file source.""" |
|
133 | """Read a file and close it. Returns the file source.""" | |
135 | fobj = open(filename,'r'); |
|
134 | fobj = open(filename,'r'); | |
136 | source = fobj.read(); |
|
135 | source = fobj.read(); | |
137 | fobj.close() |
|
136 | fobj.close() | |
138 | return source |
|
137 | return source | |
139 |
|
138 | |||
140 |
|
139 | |||
141 | def file_readlines(filename): |
|
140 | def file_readlines(filename): | |
142 | """Read a file and close it. Returns the file source using readlines().""" |
|
141 | """Read a file and close it. Returns the file source using readlines().""" | |
143 | fobj = open(filename,'r'); |
|
142 | fobj = open(filename,'r'); | |
144 | lines = fobj.readlines(); |
|
143 | lines = fobj.readlines(); | |
145 | fobj.close() |
|
144 | fobj.close() | |
146 | return lines |
|
145 | return lines | |
147 |
|
146 | |||
148 |
|
147 | |||
149 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
148 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): | |
150 | """Take multiple lines of input. |
|
149 | """Take multiple lines of input. | |
151 |
|
150 | |||
152 | A list with each line of input as a separate element is returned when a |
|
151 | A list with each line of input as a separate element is returned when a | |
153 | termination string is entered (defaults to a single '.'). Input can also |
|
152 | termination string is entered (defaults to a single '.'). Input can also | |
154 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
153 | terminate via EOF (^D in Unix, ^Z-RET in Windows). | |
155 |
|
154 | |||
156 | Lines of input which end in \\ are joined into single entries (and a |
|
155 | Lines of input which end in \\ are joined into single entries (and a | |
157 | secondary continuation prompt is issued as long as the user terminates |
|
156 | secondary continuation prompt is issued as long as the user terminates | |
158 | lines with \\). This allows entering very long strings which are still |
|
157 | lines with \\). This allows entering very long strings which are still | |
159 | meant to be treated as single entities. |
|
158 | meant to be treated as single entities. | |
160 | """ |
|
159 | """ | |
161 |
|
160 | |||
162 | try: |
|
161 | try: | |
163 | if header: |
|
162 | if header: | |
164 | header += '\n' |
|
163 | header += '\n' | |
165 | lines = [raw_input(header + ps1)] |
|
164 | lines = [raw_input(header + ps1)] | |
166 | except EOFError: |
|
165 | except EOFError: | |
167 | return [] |
|
166 | return [] | |
168 | terminate = [terminate_str] |
|
167 | terminate = [terminate_str] | |
169 | try: |
|
168 | try: | |
170 | while lines[-1:] != terminate: |
|
169 | while lines[-1:] != terminate: | |
171 | new_line = raw_input(ps1) |
|
170 | new_line = raw_input(ps1) | |
172 | while new_line.endswith('\\'): |
|
171 | while new_line.endswith('\\'): | |
173 | new_line = new_line[:-1] + raw_input(ps2) |
|
172 | new_line = new_line[:-1] + raw_input(ps2) | |
174 | lines.append(new_line) |
|
173 | lines.append(new_line) | |
175 |
|
174 | |||
176 | return lines[:-1] # don't return the termination command |
|
175 | return lines[:-1] # don't return the termination command | |
177 | except EOFError: |
|
176 | except EOFError: | |
178 |
|
177 | |||
179 | return lines |
|
178 | return lines | |
180 |
|
179 | |||
181 |
|
180 | |||
182 | def raw_input_ext(prompt='', ps2='... '): |
|
181 | def raw_input_ext(prompt='', ps2='... '): | |
183 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
182 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" | |
184 |
|
183 | |||
185 | line = raw_input(prompt) |
|
184 | line = raw_input(prompt) | |
186 | while line.endswith('\\'): |
|
185 | while line.endswith('\\'): | |
187 | line = line[:-1] + raw_input(ps2) |
|
186 | line = line[:-1] + raw_input(ps2) | |
188 | return line |
|
187 | return line | |
189 |
|
188 | |||
190 |
|
189 | |||
191 | def ask_yes_no(prompt,default=None): |
|
190 | def ask_yes_no(prompt,default=None): | |
192 | """Asks a question and returns a boolean (y/n) answer. |
|
191 | """Asks a question and returns a boolean (y/n) answer. | |
193 |
|
192 | |||
194 | If default is given (one of 'y','n'), it is used if the user input is |
|
193 | If default is given (one of 'y','n'), it is used if the user input is | |
195 | empty. Otherwise the question is repeated until an answer is given. |
|
194 | empty. Otherwise the question is repeated until an answer is given. | |
196 |
|
195 | |||
197 | An EOF is treated as the default answer. If there is no default, an |
|
196 | An EOF is treated as the default answer. If there is no default, an | |
198 | exception is raised to prevent infinite loops. |
|
197 | exception is raised to prevent infinite loops. | |
199 |
|
198 | |||
200 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
199 | Valid answers are: y/yes/n/no (match is not case sensitive).""" | |
201 |
|
200 | |||
202 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
201 | answers = {'y':True,'n':False,'yes':True,'no':False} | |
203 | ans = None |
|
202 | ans = None | |
204 | while ans not in answers.keys(): |
|
203 | while ans not in answers.keys(): | |
205 | try: |
|
204 | try: | |
206 | ans = raw_input(prompt+' ').lower() |
|
205 | ans = raw_input(prompt+' ').lower() | |
207 | if not ans: # response was an empty string |
|
206 | if not ans: # response was an empty string | |
208 | ans = default |
|
207 | ans = default | |
209 | except KeyboardInterrupt: |
|
208 | except KeyboardInterrupt: | |
210 | pass |
|
209 | pass | |
211 | except EOFError: |
|
210 | except EOFError: | |
212 | if default in answers.keys(): |
|
211 | if default in answers.keys(): | |
213 | ans = default |
|
212 | ans = default | |
214 |
|
213 | |||
215 | else: |
|
214 | else: | |
216 | raise |
|
215 | raise | |
217 |
|
216 | |||
218 | return answers[ans] |
|
217 | return answers[ans] | |
219 |
|
218 | |||
220 |
|
219 | |||
221 | class NLprinter: |
|
220 | class NLprinter: | |
222 | """Print an arbitrarily nested list, indicating index numbers. |
|
221 | """Print an arbitrarily nested list, indicating index numbers. | |
223 |
|
222 | |||
224 | An instance of this class called nlprint is available and callable as a |
|
223 | An instance of this class called nlprint is available and callable as a | |
225 | function. |
|
224 | function. | |
226 |
|
225 | |||
227 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
226 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' | |
228 | and using 'sep' to separate the index from the value. """ |
|
227 | and using 'sep' to separate the index from the value. """ | |
229 |
|
228 | |||
230 | def __init__(self): |
|
229 | def __init__(self): | |
231 | self.depth = 0 |
|
230 | self.depth = 0 | |
232 |
|
231 | |||
233 | def __call__(self,lst,pos='',**kw): |
|
232 | def __call__(self,lst,pos='',**kw): | |
234 | """Prints the nested list numbering levels.""" |
|
233 | """Prints the nested list numbering levels.""" | |
235 | kw.setdefault('indent',' ') |
|
234 | kw.setdefault('indent',' ') | |
236 | kw.setdefault('sep',': ') |
|
235 | kw.setdefault('sep',': ') | |
237 | kw.setdefault('start',0) |
|
236 | kw.setdefault('start',0) | |
238 | kw.setdefault('stop',len(lst)) |
|
237 | kw.setdefault('stop',len(lst)) | |
239 | # we need to remove start and stop from kw so they don't propagate |
|
238 | # we need to remove start and stop from kw so they don't propagate | |
240 | # into a recursive call for a nested list. |
|
239 | # into a recursive call for a nested list. | |
241 | start = kw['start']; del kw['start'] |
|
240 | start = kw['start']; del kw['start'] | |
242 | stop = kw['stop']; del kw['stop'] |
|
241 | stop = kw['stop']; del kw['stop'] | |
243 | if self.depth == 0 and 'header' in kw.keys(): |
|
242 | if self.depth == 0 and 'header' in kw.keys(): | |
244 | print kw['header'] |
|
243 | print kw['header'] | |
245 |
|
244 | |||
246 | for idx in range(start,stop): |
|
245 | for idx in range(start,stop): | |
247 | elem = lst[idx] |
|
246 | elem = lst[idx] | |
248 | if type(elem)==type([]): |
|
247 | if type(elem)==type([]): | |
249 | self.depth += 1 |
|
248 | self.depth += 1 | |
250 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
249 | self.__call__(elem,itpl('$pos$idx,'),**kw) | |
251 | self.depth -= 1 |
|
250 | self.depth -= 1 | |
252 | else: |
|
251 | else: | |
253 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
252 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') | |
254 |
|
253 | |||
255 | nlprint = NLprinter() |
|
254 | nlprint = NLprinter() | |
256 |
|
255 | |||
257 |
|
256 | |||
258 | def temp_pyfile(src, ext='.py'): |
|
257 | def temp_pyfile(src, ext='.py'): | |
259 | """Make a temporary python file, return filename and filehandle. |
|
258 | """Make a temporary python file, return filename and filehandle. | |
260 |
|
259 | |||
261 | Parameters |
|
260 | Parameters | |
262 | ---------- |
|
261 | ---------- | |
263 | src : string or list of strings (no need for ending newlines if list) |
|
262 | src : string or list of strings (no need for ending newlines if list) | |
264 | Source code to be written to the file. |
|
263 | Source code to be written to the file. | |
265 |
|
264 | |||
266 | ext : optional, string |
|
265 | ext : optional, string | |
267 | Extension for the generated file. |
|
266 | Extension for the generated file. | |
268 |
|
267 | |||
269 | Returns |
|
268 | Returns | |
270 | ------- |
|
269 | ------- | |
271 | (filename, open filehandle) |
|
270 | (filename, open filehandle) | |
272 | It is the caller's responsibility to close the open file and unlink it. |
|
271 | It is the caller's responsibility to close the open file and unlink it. | |
273 | """ |
|
272 | """ | |
274 | fname = tempfile.mkstemp(ext)[1] |
|
273 | fname = tempfile.mkstemp(ext)[1] | |
275 | f = open(fname,'w') |
|
274 | f = open(fname,'w') | |
276 | f.write(src) |
|
275 | f.write(src) | |
277 | f.flush() |
|
276 | f.flush() | |
278 | return fname, f |
|
277 | return fname, f | |
279 |
|
278 | |||
280 |
|
279 | |||
281 |
|
280 | def rprint(*info): | ||
|
281 | """Raw print to sys.__stderr__""" | |||
|
282 | ||||
|
283 | for item in info: | |||
|
284 | print >> sys.__stderr__, item, | |||
|
285 | print >> sys.__stderr__ | |||
|
286 | sys.__stderr__.flush() |
@@ -1,378 +1,387 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 | import sys |
|
19 | import sys | |
20 | import time |
|
20 | import time | |
21 | import traceback |
|
21 | import traceback | |
22 |
|
22 | |||
23 | # System library imports. |
|
23 | # System library imports. | |
24 | import zmq |
|
24 | import zmq | |
25 |
|
25 | |||
26 | # Local imports. |
|
26 | # Local imports. | |
27 | from IPython.config.configurable import Configurable |
|
27 | from IPython.config.configurable import Configurable | |
28 | from IPython.utils.traitlets import Instance |
|
28 | from IPython.utils.traitlets import Instance | |
29 | from completer import KernelCompleter |
|
29 | from completer import KernelCompleter | |
30 | from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \ |
|
30 | from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \ | |
31 | start_kernel |
|
31 | start_kernel | |
32 | from iostream import OutStream |
|
32 | from iostream import OutStream | |
33 | from session import Session, Message |
|
33 | from session import Session, Message | |
34 | from zmqshell import ZMQInteractiveShell |
|
34 | from zmqshell import ZMQInteractiveShell | |
35 |
|
35 | |||
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 | # Main kernel class |
|
37 | # Main kernel class | |
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 | class Kernel(Configurable): |
|
40 | class Kernel(Configurable): | |
41 |
|
41 | |||
42 | #--------------------------------------------------------------------------- |
|
42 | #--------------------------------------------------------------------------- | |
43 | # Kernel interface |
|
43 | # Kernel interface | |
44 | #--------------------------------------------------------------------------- |
|
44 | #--------------------------------------------------------------------------- | |
45 |
|
45 | |||
46 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
46 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
47 | session = Instance(Session) |
|
47 | session = Instance(Session) | |
48 | reply_socket = Instance('zmq.Socket') |
|
48 | reply_socket = Instance('zmq.Socket') | |
49 | pub_socket = Instance('zmq.Socket') |
|
49 | pub_socket = Instance('zmq.Socket') | |
50 | req_socket = Instance('zmq.Socket') |
|
50 | req_socket = Instance('zmq.Socket') | |
51 |
|
51 | |||
52 | # Maps user-friendly backend names to matplotlib backend identifiers. |
|
52 | # Maps user-friendly backend names to matplotlib backend identifiers. | |
53 | _pylab_map = { 'tk': 'TkAgg', |
|
53 | _pylab_map = { 'tk': 'TkAgg', | |
54 | 'gtk': 'GTKAgg', |
|
54 | 'gtk': 'GTKAgg', | |
55 | 'wx': 'WXAgg', |
|
55 | 'wx': 'WXAgg', | |
56 | 'qt': 'Qt4Agg', # qt3 not supported |
|
56 | 'qt': 'Qt4Agg', # qt3 not supported | |
57 | 'qt4': 'Qt4Agg', |
|
57 | 'qt4': 'Qt4Agg', | |
58 | 'payload-svg' : \ |
|
58 | 'payload-svg' : \ | |
59 | 'module://IPython.zmq.pylab.backend_payload_svg' } |
|
59 | 'module://IPython.zmq.pylab.backend_payload_svg' } | |
60 |
|
60 | |||
61 | def __init__(self, **kwargs): |
|
61 | def __init__(self, **kwargs): | |
62 | super(Kernel, self).__init__(**kwargs) |
|
62 | super(Kernel, self).__init__(**kwargs) | |
63 |
|
63 | |||
64 | # Initialize the InteractiveShell subclass |
|
64 | # Initialize the InteractiveShell subclass | |
65 | self.shell = ZMQInteractiveShell.instance() |
|
65 | self.shell = ZMQInteractiveShell.instance() | |
66 | self.shell.displayhook.session = self.session |
|
66 | self.shell.displayhook.session = self.session | |
67 | self.shell.displayhook.pub_socket = self.pub_socket |
|
67 | self.shell.displayhook.pub_socket = self.pub_socket | |
68 |
|
68 | |||
|
69 | # TMP - hack while developing | |||
|
70 | self.shell._reply_content = None | |||
|
71 | ||||
69 | # Build dict of handlers for message types |
|
72 | # Build dict of handlers for message types | |
70 | msg_types = [ 'execute_request', 'complete_request', |
|
73 | msg_types = [ 'execute_request', 'complete_request', | |
71 | 'object_info_request', 'prompt_request', |
|
74 | 'object_info_request', 'prompt_request', | |
72 | 'history_request' ] |
|
75 | 'history_request' ] | |
73 | self.handlers = {} |
|
76 | self.handlers = {} | |
74 | for msg_type in msg_types: |
|
77 | for msg_type in msg_types: | |
75 | self.handlers[msg_type] = getattr(self, msg_type) |
|
78 | self.handlers[msg_type] = getattr(self, msg_type) | |
76 |
|
79 | |||
77 | def activate_pylab(self, backend=None, import_all=True): |
|
80 | def activate_pylab(self, backend=None, import_all=True): | |
78 | """ Activates pylab in this kernel's namespace. |
|
81 | """ Activates pylab in this kernel's namespace. | |
79 |
|
82 | |||
80 | Parameters: |
|
83 | Parameters: | |
81 | ----------- |
|
84 | ----------- | |
82 | backend : str, optional |
|
85 | backend : str, optional | |
83 | A valid backend name. |
|
86 | A valid backend name. | |
84 |
|
87 | |||
85 | import_all : bool, optional |
|
88 | import_all : bool, optional | |
86 | If true, an 'import *' is done from numpy and pylab. |
|
89 | If true, an 'import *' is done from numpy and pylab. | |
87 | """ |
|
90 | """ | |
88 | # FIXME: This is adapted from IPython.lib.pylabtools.pylab_activate. |
|
91 | # FIXME: This is adapted from IPython.lib.pylabtools.pylab_activate. | |
89 | # Common functionality should be refactored. |
|
92 | # Common functionality should be refactored. | |
90 |
|
93 | |||
91 | # We must set the desired backend before importing pylab. |
|
94 | # We must set the desired backend before importing pylab. | |
92 | import matplotlib |
|
95 | import matplotlib | |
93 | if backend: |
|
96 | if backend: | |
94 | backend_id = self._pylab_map[backend] |
|
97 | backend_id = self._pylab_map[backend] | |
95 | if backend_id.startswith('module://'): |
|
98 | if backend_id.startswith('module://'): | |
96 | # Work around bug in matplotlib: matplotlib.use converts the |
|
99 | # Work around bug in matplotlib: matplotlib.use converts the | |
97 | # backend_id to lowercase even if a module name is specified! |
|
100 | # backend_id to lowercase even if a module name is specified! | |
98 | matplotlib.rcParams['backend'] = backend_id |
|
101 | matplotlib.rcParams['backend'] = backend_id | |
99 | else: |
|
102 | else: | |
100 | matplotlib.use(backend_id) |
|
103 | matplotlib.use(backend_id) | |
101 |
|
104 | |||
102 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
105 | # Import numpy as np/pyplot as plt are conventions we're trying to | |
103 | # somewhat standardize on. Making them available to users by default |
|
106 | # somewhat standardize on. Making them available to users by default | |
104 | # will greatly help this. |
|
107 | # will greatly help this. | |
105 | exec ("import numpy\n" |
|
108 | exec ("import numpy\n" | |
106 | "import matplotlib\n" |
|
109 | "import matplotlib\n" | |
107 | "from matplotlib import pylab, mlab, pyplot\n" |
|
110 | "from matplotlib import pylab, mlab, pyplot\n" | |
108 | "np = numpy\n" |
|
111 | "np = numpy\n" | |
109 | "plt = pyplot\n" |
|
112 | "plt = pyplot\n" | |
110 | ) in self.shell.user_ns |
|
113 | ) in self.shell.user_ns | |
111 |
|
114 | |||
112 | if import_all: |
|
115 | if import_all: | |
113 | exec("from matplotlib.pylab import *\n" |
|
116 | exec("from matplotlib.pylab import *\n" | |
114 | "from numpy import *\n") in self.shell.user_ns |
|
117 | "from numpy import *\n") in self.shell.user_ns | |
115 |
|
118 | |||
116 | matplotlib.interactive(True) |
|
119 | matplotlib.interactive(True) | |
117 |
|
120 | |||
118 | def start(self): |
|
121 | def start(self): | |
119 | """ Start the kernel main loop. |
|
122 | """ Start the kernel main loop. | |
120 | """ |
|
123 | """ | |
121 | while True: |
|
124 | while True: | |
122 | ident = self.reply_socket.recv() |
|
125 | ident = self.reply_socket.recv() | |
123 | assert self.reply_socket.rcvmore(), "Missing message part." |
|
126 | assert self.reply_socket.rcvmore(), "Missing message part." | |
124 | msg = self.reply_socket.recv_json() |
|
127 | msg = self.reply_socket.recv_json() | |
125 | omsg = Message(msg) |
|
128 | omsg = Message(msg) | |
126 | print>>sys.__stdout__ |
|
129 | print>>sys.__stdout__ | |
127 | print>>sys.__stdout__, omsg |
|
130 | print>>sys.__stdout__, omsg | |
128 | handler = self.handlers.get(omsg.msg_type, None) |
|
131 | handler = self.handlers.get(omsg.msg_type, None) | |
129 | if handler is None: |
|
132 | if handler is None: | |
130 | print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg |
|
133 | print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg | |
131 | else: |
|
134 | else: | |
132 | handler(ident, omsg) |
|
135 | handler(ident, omsg) | |
133 |
|
136 | |||
134 | #--------------------------------------------------------------------------- |
|
137 | #--------------------------------------------------------------------------- | |
135 | # Kernel request handlers |
|
138 | # Kernel request handlers | |
136 | #--------------------------------------------------------------------------- |
|
139 | #--------------------------------------------------------------------------- | |
137 |
|
140 | |||
138 | def execute_request(self, ident, parent): |
|
141 | def execute_request(self, ident, parent): | |
139 | try: |
|
142 | try: | |
140 | code = parent[u'content'][u'code'] |
|
143 | code = parent[u'content'][u'code'] | |
141 | except: |
|
144 | except: | |
142 | print>>sys.__stderr__, "Got bad msg: " |
|
145 | print>>sys.__stderr__, "Got bad msg: " | |
143 | print>>sys.__stderr__, Message(parent) |
|
146 | print>>sys.__stderr__, Message(parent) | |
144 | return |
|
147 | return | |
145 | pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) |
|
148 | pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) | |
146 | self.pub_socket.send_json(pyin_msg) |
|
149 | self.pub_socket.send_json(pyin_msg) | |
147 |
|
150 | |||
148 | try: |
|
151 | try: | |
149 | # Replace raw_input. Note that is not sufficient to replace |
|
152 | # Replace raw_input. Note that is not sufficient to replace | |
150 | # raw_input in the user namespace. |
|
153 | # raw_input in the user namespace. | |
151 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) |
|
154 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) | |
152 | __builtin__.raw_input = raw_input |
|
155 | __builtin__.raw_input = raw_input | |
153 |
|
156 | |||
154 | # Set the parent message of the display hook and out streams. |
|
157 | # Set the parent message of the display hook and out streams. | |
155 | self.shell.displayhook.set_parent(parent) |
|
158 | self.shell.displayhook.set_parent(parent) | |
156 | sys.stdout.set_parent(parent) |
|
159 | sys.stdout.set_parent(parent) | |
157 | sys.stderr.set_parent(parent) |
|
160 | sys.stderr.set_parent(parent) | |
158 |
|
161 | |||
|
162 | # FIXME: runlines calls the exception handler itself. We should | |||
|
163 | # clean this up. | |||
|
164 | self.shell._reply_content = None | |||
159 | self.shell.runlines(code) |
|
165 | self.shell.runlines(code) | |
160 | except: |
|
166 | except: | |
|
167 | # FIXME: this code right now isn't being used yet by default, | |||
|
168 | # because the runlines() call above directly fires off exception | |||
|
169 | # reporting. This code, therefore, is only active in the scenario | |||
|
170 | # where runlines itself has an unhandled exception. We need to | |||
|
171 | # uniformize this, for all exception construction to come from a | |||
|
172 | # single location in the codbase. | |||
161 | etype, evalue, tb = sys.exc_info() |
|
173 | etype, evalue, tb = sys.exc_info() | |
162 | tb = traceback.format_exception(etype, evalue, tb) |
|
174 | tb_list = traceback.format_exception(etype, evalue, tb) | |
163 | exc_content = { |
|
175 | reply_content = self.shell._showtraceback(etype, evalue, tb_list) | |
164 | u'status' : u'error', |
|
|||
165 | u'traceback' : tb, |
|
|||
166 | u'ename' : unicode(etype.__name__), |
|
|||
167 | u'evalue' : unicode(evalue) |
|
|||
168 | } |
|
|||
169 | exc_msg = self.session.msg(u'pyerr', exc_content, parent) |
|
|||
170 | self.pub_socket.send_json(exc_msg) |
|
|||
171 | reply_content = exc_content |
|
|||
172 | else: |
|
176 | else: | |
173 | payload = self.shell.payload_manager.read_payload() |
|
177 | payload = self.shell.payload_manager.read_payload() | |
174 | # Be agressive about clearing the payload because we don't want |
|
178 | # Be agressive about clearing the payload because we don't want | |
175 | # it to sit in memory until the next execute_request comes in. |
|
179 | # it to sit in memory until the next execute_request comes in. | |
176 | self.shell.payload_manager.clear_payload() |
|
180 | self.shell.payload_manager.clear_payload() | |
177 | reply_content = { 'status' : 'ok', 'payload' : payload } |
|
181 | reply_content = { 'status' : 'ok', 'payload' : payload } | |
178 |
|
182 | |||
179 | # Compute the prompt information |
|
183 | # Compute the prompt information | |
180 | prompt_number = self.shell.displayhook.prompt_count |
|
184 | prompt_number = self.shell.displayhook.prompt_count | |
181 | reply_content['prompt_number'] = prompt_number |
|
185 | reply_content['prompt_number'] = prompt_number | |
182 | prompt_string = self.shell.displayhook.prompt1.peek_next_prompt() |
|
186 | prompt_string = self.shell.displayhook.prompt1.peek_next_prompt() | |
183 | next_prompt = {'prompt_string' : prompt_string, |
|
187 | next_prompt = {'prompt_string' : prompt_string, | |
184 | 'prompt_number' : prompt_number+1, |
|
188 | 'prompt_number' : prompt_number+1, | |
185 | 'input_sep' : self.shell.displayhook.input_sep} |
|
189 | 'input_sep' : self.shell.displayhook.input_sep} | |
186 | reply_content['next_prompt'] = next_prompt |
|
190 | reply_content['next_prompt'] = next_prompt | |
187 |
|
191 | |||
|
192 | # TMP - fish exception info out of shell, possibly left there by | |||
|
193 | # runlines | |||
|
194 | if self.shell._reply_content is not None: | |||
|
195 | reply_content.update(self.shell._reply_content) | |||
|
196 | ||||
188 | # Flush output before sending the reply. |
|
197 | # Flush output before sending the reply. | |
189 | sys.stderr.flush() |
|
198 | sys.stderr.flush() | |
190 | sys.stdout.flush() |
|
199 | sys.stdout.flush() | |
191 |
|
200 | |||
192 | # Send the reply. |
|
201 | # Send the reply. | |
193 | reply_msg = self.session.msg(u'execute_reply', reply_content, parent) |
|
202 | reply_msg = self.session.msg(u'execute_reply', reply_content, parent) | |
194 | print>>sys.__stdout__, Message(reply_msg) |
|
203 | print>>sys.__stdout__, Message(reply_msg) | |
195 | self.reply_socket.send(ident, zmq.SNDMORE) |
|
204 | self.reply_socket.send(ident, zmq.SNDMORE) | |
196 | self.reply_socket.send_json(reply_msg) |
|
205 | self.reply_socket.send_json(reply_msg) | |
197 | if reply_msg['content']['status'] == u'error': |
|
206 | if reply_msg['content']['status'] == u'error': | |
198 | self._abort_queue() |
|
207 | self._abort_queue() | |
199 |
|
208 | |||
200 | def complete_request(self, ident, parent): |
|
209 | def complete_request(self, ident, parent): | |
201 | matches = {'matches' : self._complete(parent), |
|
210 | matches = {'matches' : self._complete(parent), | |
202 | 'status' : 'ok'} |
|
211 | 'status' : 'ok'} | |
203 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', |
|
212 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', | |
204 | matches, parent, ident) |
|
213 | matches, parent, ident) | |
205 | print >> sys.__stdout__, completion_msg |
|
214 | print >> sys.__stdout__, completion_msg | |
206 |
|
215 | |||
207 | def object_info_request(self, ident, parent): |
|
216 | def object_info_request(self, ident, parent): | |
208 | context = parent['content']['oname'].split('.') |
|
217 | context = parent['content']['oname'].split('.') | |
209 | object_info = self._object_info(context) |
|
218 | object_info = self._object_info(context) | |
210 | msg = self.session.send(self.reply_socket, 'object_info_reply', |
|
219 | msg = self.session.send(self.reply_socket, 'object_info_reply', | |
211 | object_info, parent, ident) |
|
220 | object_info, parent, ident) | |
212 | print >> sys.__stdout__, msg |
|
221 | print >> sys.__stdout__, msg | |
213 |
|
222 | |||
214 | def prompt_request(self, ident, parent): |
|
223 | def prompt_request(self, ident, parent): | |
215 | prompt_number = self.shell.displayhook.prompt_count |
|
224 | prompt_number = self.shell.displayhook.prompt_count | |
216 | prompt_string = self.shell.displayhook.prompt1.peek_next_prompt() |
|
225 | prompt_string = self.shell.displayhook.prompt1.peek_next_prompt() | |
217 | content = {'prompt_string' : prompt_string, |
|
226 | content = {'prompt_string' : prompt_string, | |
218 | 'prompt_number' : prompt_number+1} |
|
227 | 'prompt_number' : prompt_number+1} | |
219 | msg = self.session.send(self.reply_socket, 'prompt_reply', |
|
228 | msg = self.session.send(self.reply_socket, 'prompt_reply', | |
220 | content, parent, ident) |
|
229 | content, parent, ident) | |
221 | print >> sys.__stdout__, msg |
|
230 | print >> sys.__stdout__, msg | |
222 |
|
231 | |||
223 | def history_request(self, ident, parent): |
|
232 | def history_request(self, ident, parent): | |
224 | output = parent['content'].get('output', True) |
|
233 | output = parent['content'].get('output', True) | |
225 | index = parent['content'].get('index') |
|
234 | index = parent['content'].get('index') | |
226 | raw = parent['content'].get('raw', False) |
|
235 | raw = parent['content'].get('raw', False) | |
227 | hist = self.shell.get_history(index=index, raw=raw, output=output) |
|
236 | hist = self.shell.get_history(index=index, raw=raw, output=output) | |
228 | content = {'history' : hist} |
|
237 | content = {'history' : hist} | |
229 | msg = self.session.send(self.reply_socket, 'history_reply', |
|
238 | msg = self.session.send(self.reply_socket, 'history_reply', | |
230 | content, parent, ident) |
|
239 | content, parent, ident) | |
231 | print >> sys.__stdout__, msg |
|
240 | print >> sys.__stdout__, msg | |
232 |
|
241 | |||
233 | #--------------------------------------------------------------------------- |
|
242 | #--------------------------------------------------------------------------- | |
234 | # Protected interface |
|
243 | # Protected interface | |
235 | #--------------------------------------------------------------------------- |
|
244 | #--------------------------------------------------------------------------- | |
236 |
|
245 | |||
237 | def _abort_queue(self): |
|
246 | def _abort_queue(self): | |
238 | while True: |
|
247 | while True: | |
239 | try: |
|
248 | try: | |
240 | ident = self.reply_socket.recv(zmq.NOBLOCK) |
|
249 | ident = self.reply_socket.recv(zmq.NOBLOCK) | |
241 | except zmq.ZMQError, e: |
|
250 | except zmq.ZMQError, e: | |
242 | if e.errno == zmq.EAGAIN: |
|
251 | if e.errno == zmq.EAGAIN: | |
243 | break |
|
252 | break | |
244 | else: |
|
253 | else: | |
245 | assert self.reply_socket.rcvmore(), "Unexpected missing message part." |
|
254 | assert self.reply_socket.rcvmore(), "Unexpected missing message part." | |
246 | msg = self.reply_socket.recv_json() |
|
255 | msg = self.reply_socket.recv_json() | |
247 | print>>sys.__stdout__, "Aborting:" |
|
256 | print>>sys.__stdout__, "Aborting:" | |
248 | print>>sys.__stdout__, Message(msg) |
|
257 | print>>sys.__stdout__, Message(msg) | |
249 | msg_type = msg['msg_type'] |
|
258 | msg_type = msg['msg_type'] | |
250 | reply_type = msg_type.split('_')[0] + '_reply' |
|
259 | reply_type = msg_type.split('_')[0] + '_reply' | |
251 | reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg) |
|
260 | reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg) | |
252 | print>>sys.__stdout__, Message(reply_msg) |
|
261 | print>>sys.__stdout__, Message(reply_msg) | |
253 | self.reply_socket.send(ident,zmq.SNDMORE) |
|
262 | self.reply_socket.send(ident,zmq.SNDMORE) | |
254 | self.reply_socket.send_json(reply_msg) |
|
263 | self.reply_socket.send_json(reply_msg) | |
255 | # We need to wait a bit for requests to come in. This can probably |
|
264 | # We need to wait a bit for requests to come in. This can probably | |
256 | # be set shorter for true asynchronous clients. |
|
265 | # be set shorter for true asynchronous clients. | |
257 | time.sleep(0.1) |
|
266 | time.sleep(0.1) | |
258 |
|
267 | |||
259 | def _raw_input(self, prompt, ident, parent): |
|
268 | def _raw_input(self, prompt, ident, parent): | |
260 | # Flush output before making the request. |
|
269 | # Flush output before making the request. | |
261 | sys.stderr.flush() |
|
270 | sys.stderr.flush() | |
262 | sys.stdout.flush() |
|
271 | sys.stdout.flush() | |
263 |
|
272 | |||
264 | # Send the input request. |
|
273 | # Send the input request. | |
265 | content = dict(prompt=prompt) |
|
274 | content = dict(prompt=prompt) | |
266 | msg = self.session.msg(u'input_request', content, parent) |
|
275 | msg = self.session.msg(u'input_request', content, parent) | |
267 | self.req_socket.send_json(msg) |
|
276 | self.req_socket.send_json(msg) | |
268 |
|
277 | |||
269 | # Await a response. |
|
278 | # Await a response. | |
270 | reply = self.req_socket.recv_json() |
|
279 | reply = self.req_socket.recv_json() | |
271 | try: |
|
280 | try: | |
272 | value = reply['content']['value'] |
|
281 | value = reply['content']['value'] | |
273 | except: |
|
282 | except: | |
274 | print>>sys.__stderr__, "Got bad raw_input reply: " |
|
283 | print>>sys.__stderr__, "Got bad raw_input reply: " | |
275 | print>>sys.__stderr__, Message(parent) |
|
284 | print>>sys.__stderr__, Message(parent) | |
276 | value = '' |
|
285 | value = '' | |
277 | return value |
|
286 | return value | |
278 |
|
287 | |||
279 | def _complete(self, msg): |
|
288 | def _complete(self, msg): | |
280 | return self.shell.complete(msg.content.line) |
|
289 | return self.shell.complete(msg.content.line) | |
281 |
|
290 | |||
282 | def _object_info(self, context): |
|
291 | def _object_info(self, context): | |
283 | symbol, leftover = self._symbol_from_context(context) |
|
292 | symbol, leftover = self._symbol_from_context(context) | |
284 | if symbol is not None and not leftover: |
|
293 | if symbol is not None and not leftover: | |
285 | doc = getattr(symbol, '__doc__', '') |
|
294 | doc = getattr(symbol, '__doc__', '') | |
286 | else: |
|
295 | else: | |
287 | doc = '' |
|
296 | doc = '' | |
288 | object_info = dict(docstring = doc) |
|
297 | object_info = dict(docstring = doc) | |
289 | return object_info |
|
298 | return object_info | |
290 |
|
299 | |||
291 | def _symbol_from_context(self, context): |
|
300 | def _symbol_from_context(self, context): | |
292 | if not context: |
|
301 | if not context: | |
293 | return None, context |
|
302 | return None, context | |
294 |
|
303 | |||
295 | base_symbol_string = context[0] |
|
304 | base_symbol_string = context[0] | |
296 | symbol = self.shell.user_ns.get(base_symbol_string, None) |
|
305 | symbol = self.shell.user_ns.get(base_symbol_string, None) | |
297 | if symbol is None: |
|
306 | if symbol is None: | |
298 | symbol = __builtin__.__dict__.get(base_symbol_string, None) |
|
307 | symbol = __builtin__.__dict__.get(base_symbol_string, None) | |
299 | if symbol is None: |
|
308 | if symbol is None: | |
300 | return None, context |
|
309 | return None, context | |
301 |
|
310 | |||
302 | context = context[1:] |
|
311 | context = context[1:] | |
303 | for i, name in enumerate(context): |
|
312 | for i, name in enumerate(context): | |
304 | new_symbol = getattr(symbol, name, None) |
|
313 | new_symbol = getattr(symbol, name, None) | |
305 | if new_symbol is None: |
|
314 | if new_symbol is None: | |
306 | return symbol, context[i:] |
|
315 | return symbol, context[i:] | |
307 | else: |
|
316 | else: | |
308 | symbol = new_symbol |
|
317 | symbol = new_symbol | |
309 |
|
318 | |||
310 | return symbol, [] |
|
319 | return symbol, [] | |
311 |
|
320 | |||
312 | #----------------------------------------------------------------------------- |
|
321 | #----------------------------------------------------------------------------- | |
313 | # Kernel main and launch functions |
|
322 | # Kernel main and launch functions | |
314 | #----------------------------------------------------------------------------- |
|
323 | #----------------------------------------------------------------------------- | |
315 |
|
324 | |||
316 | def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False, |
|
325 | def launch_kernel(xrep_port=0, pub_port=0, req_port=0, independent=False, | |
317 | pylab=False): |
|
326 | pylab=False): | |
318 | """ Launches a localhost kernel, binding to the specified ports. |
|
327 | """ Launches a localhost kernel, binding to the specified ports. | |
319 |
|
328 | |||
320 | Parameters |
|
329 | Parameters | |
321 | ---------- |
|
330 | ---------- | |
322 | xrep_port : int, optional |
|
331 | xrep_port : int, optional | |
323 | The port to use for XREP channel. |
|
332 | The port to use for XREP channel. | |
324 |
|
333 | |||
325 | pub_port : int, optional |
|
334 | pub_port : int, optional | |
326 | The port to use for the SUB channel. |
|
335 | The port to use for the SUB channel. | |
327 |
|
336 | |||
328 | req_port : int, optional |
|
337 | req_port : int, optional | |
329 | The port to use for the REQ (raw input) channel. |
|
338 | The port to use for the REQ (raw input) channel. | |
330 |
|
339 | |||
331 | independent : bool, optional (default False) |
|
340 | independent : bool, optional (default False) | |
332 | If set, the kernel process is guaranteed to survive if this process |
|
341 | If set, the kernel process is guaranteed to survive if this process | |
333 | dies. If not set, an effort is made to ensure that the kernel is killed |
|
342 | dies. If not set, an effort is made to ensure that the kernel is killed | |
334 | when this process dies. Note that in this case it is still good practice |
|
343 | when this process dies. Note that in this case it is still good practice | |
335 | to kill kernels manually before exiting. |
|
344 | to kill kernels manually before exiting. | |
336 |
|
345 | |||
337 | pylab : bool or string, optional (default False) |
|
346 | pylab : bool or string, optional (default False) | |
338 | If not False, the kernel will be launched with pylab enabled. If a |
|
347 | If not False, the kernel will be launched with pylab enabled. If a | |
339 | string is passed, matplotlib will use the specified backend. Otherwise, |
|
348 | string is passed, matplotlib will use the specified backend. Otherwise, | |
340 | matplotlib's default backend will be used. |
|
349 | matplotlib's default backend will be used. | |
341 |
|
350 | |||
342 | Returns |
|
351 | Returns | |
343 | ------- |
|
352 | ------- | |
344 | A tuple of form: |
|
353 | A tuple of form: | |
345 | (kernel_process, xrep_port, pub_port, req_port) |
|
354 | (kernel_process, xrep_port, pub_port, req_port) | |
346 | where kernel_process is a Popen object and the ports are integers. |
|
355 | where kernel_process is a Popen object and the ports are integers. | |
347 | """ |
|
356 | """ | |
348 | extra_arguments = [] |
|
357 | extra_arguments = [] | |
349 | if pylab: |
|
358 | if pylab: | |
350 | extra_arguments.append('--pylab') |
|
359 | extra_arguments.append('--pylab') | |
351 | if isinstance(pylab, basestring): |
|
360 | if isinstance(pylab, basestring): | |
352 | extra_arguments.append(pylab) |
|
361 | extra_arguments.append(pylab) | |
353 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', |
|
362 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', | |
354 | xrep_port, pub_port, req_port, independent, |
|
363 | xrep_port, pub_port, req_port, independent, | |
355 | extra_arguments) |
|
364 | extra_arguments) | |
356 |
|
365 | |||
357 | def main(): |
|
366 | def main(): | |
358 | """ The IPython kernel main entry point. |
|
367 | """ The IPython kernel main entry point. | |
359 | """ |
|
368 | """ | |
360 | parser = make_argument_parser() |
|
369 | parser = make_argument_parser() | |
361 | parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?', |
|
370 | parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?', | |
362 | const='auto', help = \ |
|
371 | const='auto', help = \ | |
363 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ |
|
372 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ | |
364 | given, the GUI backend is matplotlib's, otherwise use one of: \ |
|
373 | given, the GUI backend is matplotlib's, otherwise use one of: \ | |
365 | ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].") |
|
374 | ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].") | |
366 | namespace = parser.parse_args() |
|
375 | namespace = parser.parse_args() | |
367 |
|
376 | |||
368 | kernel = make_kernel(namespace, Kernel, OutStream) |
|
377 | kernel = make_kernel(namespace, Kernel, OutStream) | |
369 | if namespace.pylab: |
|
378 | if namespace.pylab: | |
370 | if namespace.pylab == 'auto': |
|
379 | if namespace.pylab == 'auto': | |
371 | kernel.activate_pylab() |
|
380 | kernel.activate_pylab() | |
372 | else: |
|
381 | else: | |
373 | kernel.activate_pylab(namespace.pylab) |
|
382 | kernel.activate_pylab(namespace.pylab) | |
374 |
|
383 | |||
375 | start_kernel(namespace, kernel) |
|
384 | start_kernel(namespace, kernel) | |
376 |
|
385 | |||
377 | if __name__ == '__main__': |
|
386 | if __name__ == '__main__': | |
378 | main() |
|
387 | main() |
@@ -1,365 +1,389 b'' | |||||
1 | import inspect |
|
1 | import inspect | |
2 | import re |
|
2 | import re | |
3 | import sys |
|
3 | import sys | |
4 | from subprocess import Popen, PIPE |
|
4 | from subprocess import Popen, PIPE | |
5 |
|
5 | |||
6 | from IPython.core.interactiveshell import ( |
|
6 | from IPython.core.interactiveshell import ( | |
7 | InteractiveShell, InteractiveShellABC |
|
7 | InteractiveShell, InteractiveShellABC | |
8 | ) |
|
8 | ) | |
9 | from IPython.core.displayhook import DisplayHook |
|
9 | from IPython.core.displayhook import DisplayHook | |
10 | from IPython.core.macro import Macro |
|
10 | from IPython.core.macro import Macro | |
|
11 | from IPython.utils.io import rprint | |||
11 | from IPython.utils.path import get_py_filename |
|
12 | from IPython.utils.path import get_py_filename | |
12 | from IPython.utils.text import StringTypes |
|
13 | from IPython.utils.text import StringTypes | |
13 | from IPython.utils.traitlets import Instance, Type, Dict |
|
14 | from IPython.utils.traitlets import Instance, Type, Dict | |
14 | from IPython.utils.warn import warn |
|
15 | from IPython.utils.warn import warn | |
15 | from IPython.zmq.session import extract_header |
|
16 | from IPython.zmq.session import extract_header | |
16 | from IPython.core.payloadpage import install_payload_page |
|
17 | from IPython.core.payloadpage import install_payload_page | |
17 |
|
18 | |||
18 |
|
19 | |||
19 | # Install the payload version of page. |
|
20 | # Install the payload version of page. | |
20 | install_payload_page() |
|
21 | install_payload_page() | |
21 |
|
22 | |||
22 |
|
23 | |||
23 | class ZMQDisplayHook(DisplayHook): |
|
24 | class ZMQDisplayHook(DisplayHook): | |
24 |
|
25 | |||
25 | session = Instance('IPython.zmq.session.Session') |
|
26 | session = Instance('IPython.zmq.session.Session') | |
26 | pub_socket = Instance('zmq.Socket') |
|
27 | pub_socket = Instance('zmq.Socket') | |
27 | parent_header = Dict({}) |
|
28 | parent_header = Dict({}) | |
28 |
|
29 | |||
29 | def set_parent(self, parent): |
|
30 | def set_parent(self, parent): | |
30 | """Set the parent for outbound messages.""" |
|
31 | """Set the parent for outbound messages.""" | |
31 | self.parent_header = extract_header(parent) |
|
32 | self.parent_header = extract_header(parent) | |
32 |
|
33 | |||
33 | def start_displayhook(self): |
|
34 | def start_displayhook(self): | |
34 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
35 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
35 |
|
36 | |||
36 | def write_output_prompt(self): |
|
37 | def write_output_prompt(self): | |
37 | """Write the output prompt.""" |
|
38 | """Write the output prompt.""" | |
38 | if self.do_full_cache: |
|
39 | if self.do_full_cache: | |
39 | self.msg['content']['output_sep'] = self.output_sep |
|
40 | self.msg['content']['output_sep'] = self.output_sep | |
40 | self.msg['content']['prompt_string'] = str(self.prompt_out) |
|
41 | self.msg['content']['prompt_string'] = str(self.prompt_out) | |
41 | self.msg['content']['prompt_number'] = self.prompt_count |
|
42 | self.msg['content']['prompt_number'] = self.prompt_count | |
42 | self.msg['content']['output_sep2'] = self.output_sep2 |
|
43 | self.msg['content']['output_sep2'] = self.output_sep2 | |
43 |
|
44 | |||
44 | def write_result_repr(self, result_repr): |
|
45 | def write_result_repr(self, result_repr): | |
45 | self.msg['content']['data'] = result_repr |
|
46 | self.msg['content']['data'] = result_repr | |
46 |
|
47 | |||
47 | def finish_displayhook(self): |
|
48 | def finish_displayhook(self): | |
48 | """Finish up all displayhook activities.""" |
|
49 | """Finish up all displayhook activities.""" | |
49 | self.pub_socket.send_json(self.msg) |
|
50 | self.pub_socket.send_json(self.msg) | |
50 | self.msg = None |
|
51 | self.msg = None | |
51 |
|
52 | |||
52 |
|
53 | |||
53 | class ZMQInteractiveShell(InteractiveShell): |
|
54 | class ZMQInteractiveShell(InteractiveShell): | |
54 | """A subclass of InteractiveShell for ZMQ.""" |
|
55 | """A subclass of InteractiveShell for ZMQ.""" | |
55 |
|
56 | |||
56 | displayhook_class = Type(ZMQDisplayHook) |
|
57 | displayhook_class = Type(ZMQDisplayHook) | |
57 |
|
58 | |||
58 | def system(self, cmd): |
|
59 | def system(self, cmd): | |
59 | cmd = self.var_expand(cmd, depth=2) |
|
60 | cmd = self.var_expand(cmd, depth=2) | |
60 | sys.stdout.flush() |
|
61 | sys.stdout.flush() | |
61 | sys.stderr.flush() |
|
62 | sys.stderr.flush() | |
62 | p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) |
|
63 | p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) | |
63 | for line in p.stdout.read().split('\n'): |
|
64 | for line in p.stdout.read().split('\n'): | |
64 | if len(line) > 0: |
|
65 | if len(line) > 0: | |
65 | print line |
|
66 | print line | |
66 | for line in p.stderr.read().split('\n'): |
|
67 | for line in p.stderr.read().split('\n'): | |
67 | if len(line) > 0: |
|
68 | if len(line) > 0: | |
68 | print line |
|
69 | print line | |
69 | p.wait() |
|
70 | p.wait() | |
70 |
|
71 | |||
71 | def init_io(self): |
|
72 | def init_io(self): | |
72 | # This will just use sys.stdout and sys.stderr. If you want to |
|
73 | # This will just use sys.stdout and sys.stderr. If you want to | |
73 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
74 | # override sys.stdout and sys.stderr themselves, you need to do that | |
74 | # *before* instantiating this class, because Term holds onto |
|
75 | # *before* instantiating this class, because Term holds onto | |
75 | # references to the underlying streams. |
|
76 | # references to the underlying streams. | |
76 | import IPython.utils.io |
|
77 | import IPython.utils.io | |
77 | Term = IPython.utils.io.IOTerm() |
|
78 | Term = IPython.utils.io.IOTerm() | |
78 | IPython.utils.io.Term = Term |
|
79 | IPython.utils.io.Term = Term | |
79 |
|
80 | |||
80 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
81 | def magic_edit(self,parameter_s='',last_call=['','']): | |
81 | """Bring up an editor and execute the resulting code. |
|
82 | """Bring up an editor and execute the resulting code. | |
82 |
|
83 | |||
83 | Usage: |
|
84 | Usage: | |
84 | %edit [options] [args] |
|
85 | %edit [options] [args] | |
85 |
|
86 | |||
86 | %edit runs IPython's editor hook. The default version of this hook is |
|
87 | %edit runs IPython's editor hook. The default version of this hook is | |
87 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
88 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
88 | environment variable $EDITOR. If this isn't found, it will default to |
|
89 | environment variable $EDITOR. If this isn't found, it will default to | |
89 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
90 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
90 | docstring for how to change the editor hook. |
|
91 | docstring for how to change the editor hook. | |
91 |
|
92 | |||
92 | You can also set the value of this editor via the command line option |
|
93 | You can also set the value of this editor via the command line option | |
93 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
94 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
94 | specifically for IPython an editor different from your typical default |
|
95 | specifically for IPython an editor different from your typical default | |
95 | (and for Windows users who typically don't set environment variables). |
|
96 | (and for Windows users who typically don't set environment variables). | |
96 |
|
97 | |||
97 | This command allows you to conveniently edit multi-line code right in |
|
98 | This command allows you to conveniently edit multi-line code right in | |
98 | your IPython session. |
|
99 | your IPython session. | |
99 |
|
100 | |||
100 | If called without arguments, %edit opens up an empty editor with a |
|
101 | If called without arguments, %edit opens up an empty editor with a | |
101 | temporary file and will execute the contents of this file when you |
|
102 | temporary file and will execute the contents of this file when you | |
102 | close it (don't forget to save it!). |
|
103 | close it (don't forget to save it!). | |
103 |
|
104 | |||
104 |
|
105 | |||
105 | Options: |
|
106 | Options: | |
106 |
|
107 | |||
107 | -n <number>: open the editor at a specified line number. By default, |
|
108 | -n <number>: open the editor at a specified line number. By default, | |
108 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
109 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
109 | you can configure this by providing your own modified hook if your |
|
110 | you can configure this by providing your own modified hook if your | |
110 | favorite editor supports line-number specifications with a different |
|
111 | favorite editor supports line-number specifications with a different | |
111 | syntax. |
|
112 | syntax. | |
112 |
|
113 | |||
113 | -p: this will call the editor with the same data as the previous time |
|
114 | -p: this will call the editor with the same data as the previous time | |
114 | it was used, regardless of how long ago (in your current session) it |
|
115 | it was used, regardless of how long ago (in your current session) it | |
115 | was. |
|
116 | was. | |
116 |
|
117 | |||
117 | -r: use 'raw' input. This option only applies to input taken from the |
|
118 | -r: use 'raw' input. This option only applies to input taken from the | |
118 | user's history. By default, the 'processed' history is used, so that |
|
119 | user's history. By default, the 'processed' history is used, so that | |
119 | magics are loaded in their transformed version to valid Python. If |
|
120 | magics are loaded in their transformed version to valid Python. If | |
120 | this option is given, the raw input as typed as the command line is |
|
121 | this option is given, the raw input as typed as the command line is | |
121 | used instead. When you exit the editor, it will be executed by |
|
122 | used instead. When you exit the editor, it will be executed by | |
122 | IPython's own processor. |
|
123 | IPython's own processor. | |
123 |
|
124 | |||
124 | -x: do not execute the edited code immediately upon exit. This is |
|
125 | -x: do not execute the edited code immediately upon exit. This is | |
125 | mainly useful if you are editing programs which need to be called with |
|
126 | mainly useful if you are editing programs which need to be called with | |
126 | command line arguments, which you can then do using %run. |
|
127 | command line arguments, which you can then do using %run. | |
127 |
|
128 | |||
128 |
|
129 | |||
129 | Arguments: |
|
130 | Arguments: | |
130 |
|
131 | |||
131 | If arguments are given, the following possibilites exist: |
|
132 | If arguments are given, the following possibilites exist: | |
132 |
|
133 | |||
133 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
134 | - The arguments are numbers or pairs of colon-separated numbers (like | |
134 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
135 | 1 4:8 9). These are interpreted as lines of previous input to be | |
135 | loaded into the editor. The syntax is the same of the %macro command. |
|
136 | loaded into the editor. The syntax is the same of the %macro command. | |
136 |
|
137 | |||
137 | - If the argument doesn't start with a number, it is evaluated as a |
|
138 | - If the argument doesn't start with a number, it is evaluated as a | |
138 | variable and its contents loaded into the editor. You can thus edit |
|
139 | variable and its contents loaded into the editor. You can thus edit | |
139 | any string which contains python code (including the result of |
|
140 | any string which contains python code (including the result of | |
140 | previous edits). |
|
141 | previous edits). | |
141 |
|
142 | |||
142 | - If the argument is the name of an object (other than a string), |
|
143 | - If the argument is the name of an object (other than a string), | |
143 | IPython will try to locate the file where it was defined and open the |
|
144 | IPython will try to locate the file where it was defined and open the | |
144 | editor at the point where it is defined. You can use `%edit function` |
|
145 | editor at the point where it is defined. You can use `%edit function` | |
145 | to load an editor exactly at the point where 'function' is defined, |
|
146 | to load an editor exactly at the point where 'function' is defined, | |
146 | edit it and have the file be executed automatically. |
|
147 | edit it and have the file be executed automatically. | |
147 |
|
148 | |||
148 | If the object is a macro (see %macro for details), this opens up your |
|
149 | If the object is a macro (see %macro for details), this opens up your | |
149 | specified editor with a temporary file containing the macro's data. |
|
150 | specified editor with a temporary file containing the macro's data. | |
150 | Upon exit, the macro is reloaded with the contents of the file. |
|
151 | Upon exit, the macro is reloaded with the contents of the file. | |
151 |
|
152 | |||
152 | Note: opening at an exact line is only supported under Unix, and some |
|
153 | Note: opening at an exact line is only supported under Unix, and some | |
153 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
154 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
154 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
155 | '+NUMBER' parameter necessary for this feature. Good editors like | |
155 | (X)Emacs, vi, jed, pico and joe all do. |
|
156 | (X)Emacs, vi, jed, pico and joe all do. | |
156 |
|
157 | |||
157 | - If the argument is not found as a variable, IPython will look for a |
|
158 | - If the argument is not found as a variable, IPython will look for a | |
158 | file with that name (adding .py if necessary) and load it into the |
|
159 | file with that name (adding .py if necessary) and load it into the | |
159 | editor. It will execute its contents with execfile() when you exit, |
|
160 | editor. It will execute its contents with execfile() when you exit, | |
160 | loading any code in the file into your interactive namespace. |
|
161 | loading any code in the file into your interactive namespace. | |
161 |
|
162 | |||
162 | After executing your code, %edit will return as output the code you |
|
163 | After executing your code, %edit will return as output the code you | |
163 | typed in the editor (except when it was an existing file). This way |
|
164 | typed in the editor (except when it was an existing file). This way | |
164 | you can reload the code in further invocations of %edit as a variable, |
|
165 | you can reload the code in further invocations of %edit as a variable, | |
165 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
166 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
166 | the output. |
|
167 | the output. | |
167 |
|
168 | |||
168 | Note that %edit is also available through the alias %ed. |
|
169 | Note that %edit is also available through the alias %ed. | |
169 |
|
170 | |||
170 | This is an example of creating a simple function inside the editor and |
|
171 | This is an example of creating a simple function inside the editor and | |
171 | then modifying it. First, start up the editor: |
|
172 | then modifying it. First, start up the editor: | |
172 |
|
173 | |||
173 | In [1]: ed |
|
174 | In [1]: ed | |
174 | Editing... done. Executing edited code... |
|
175 | Editing... done. Executing edited code... | |
175 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
176 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
176 |
|
177 | |||
177 | We can then call the function foo(): |
|
178 | We can then call the function foo(): | |
178 |
|
179 | |||
179 | In [2]: foo() |
|
180 | In [2]: foo() | |
180 | foo() was defined in an editing session |
|
181 | foo() was defined in an editing session | |
181 |
|
182 | |||
182 | Now we edit foo. IPython automatically loads the editor with the |
|
183 | Now we edit foo. IPython automatically loads the editor with the | |
183 | (temporary) file where foo() was previously defined: |
|
184 | (temporary) file where foo() was previously defined: | |
184 |
|
185 | |||
185 | In [3]: ed foo |
|
186 | In [3]: ed foo | |
186 | Editing... done. Executing edited code... |
|
187 | Editing... done. Executing edited code... | |
187 |
|
188 | |||
188 | And if we call foo() again we get the modified version: |
|
189 | And if we call foo() again we get the modified version: | |
189 |
|
190 | |||
190 | In [4]: foo() |
|
191 | In [4]: foo() | |
191 | foo() has now been changed! |
|
192 | foo() has now been changed! | |
192 |
|
193 | |||
193 | Here is an example of how to edit a code snippet successive |
|
194 | Here is an example of how to edit a code snippet successive | |
194 | times. First we call the editor: |
|
195 | times. First we call the editor: | |
195 |
|
196 | |||
196 | In [5]: ed |
|
197 | In [5]: ed | |
197 | Editing... done. Executing edited code... |
|
198 | Editing... done. Executing edited code... | |
198 | hello |
|
199 | hello | |
199 | Out[5]: "print 'hello'n" |
|
200 | Out[5]: "print 'hello'n" | |
200 |
|
201 | |||
201 | Now we call it again with the previous output (stored in _): |
|
202 | Now we call it again with the previous output (stored in _): | |
202 |
|
203 | |||
203 | In [6]: ed _ |
|
204 | In [6]: ed _ | |
204 | Editing... done. Executing edited code... |
|
205 | Editing... done. Executing edited code... | |
205 | hello world |
|
206 | hello world | |
206 | Out[6]: "print 'hello world'n" |
|
207 | Out[6]: "print 'hello world'n" | |
207 |
|
208 | |||
208 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
209 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
209 |
|
210 | |||
210 | In [7]: ed _8 |
|
211 | In [7]: ed _8 | |
211 | Editing... done. Executing edited code... |
|
212 | Editing... done. Executing edited code... | |
212 | hello again |
|
213 | hello again | |
213 | Out[7]: "print 'hello again'n" |
|
214 | Out[7]: "print 'hello again'n" | |
214 |
|
215 | |||
215 |
|
216 | |||
216 | Changing the default editor hook: |
|
217 | Changing the default editor hook: | |
217 |
|
218 | |||
218 | If you wish to write your own editor hook, you can put it in a |
|
219 | If you wish to write your own editor hook, you can put it in a | |
219 | configuration file which you load at startup time. The default hook |
|
220 | configuration file which you load at startup time. The default hook | |
220 | is defined in the IPython.core.hooks module, and you can use that as a |
|
221 | is defined in the IPython.core.hooks module, and you can use that as a | |
221 | starting example for further modifications. That file also has |
|
222 | starting example for further modifications. That file also has | |
222 | general instructions on how to set a new hook for use once you've |
|
223 | general instructions on how to set a new hook for use once you've | |
223 | defined it.""" |
|
224 | defined it.""" | |
224 |
|
225 | |||
225 | # FIXME: This function has become a convoluted mess. It needs a |
|
226 | # FIXME: This function has become a convoluted mess. It needs a | |
226 | # ground-up rewrite with clean, simple logic. |
|
227 | # ground-up rewrite with clean, simple logic. | |
227 |
|
228 | |||
228 | def make_filename(arg): |
|
229 | def make_filename(arg): | |
229 | "Make a filename from the given args" |
|
230 | "Make a filename from the given args" | |
230 | try: |
|
231 | try: | |
231 | filename = get_py_filename(arg) |
|
232 | filename = get_py_filename(arg) | |
232 | except IOError: |
|
233 | except IOError: | |
233 | if args.endswith('.py'): |
|
234 | if args.endswith('.py'): | |
234 | filename = arg |
|
235 | filename = arg | |
235 | else: |
|
236 | else: | |
236 | filename = None |
|
237 | filename = None | |
237 | return filename |
|
238 | return filename | |
238 |
|
239 | |||
239 | # custom exceptions |
|
240 | # custom exceptions | |
240 | class DataIsObject(Exception): pass |
|
241 | class DataIsObject(Exception): pass | |
241 |
|
242 | |||
242 | opts,args = self.parse_options(parameter_s,'prn:') |
|
243 | opts,args = self.parse_options(parameter_s,'prn:') | |
243 | # Set a few locals from the options for convenience: |
|
244 | # Set a few locals from the options for convenience: | |
244 | opts_p = opts.has_key('p') |
|
245 | opts_p = opts.has_key('p') | |
245 | opts_r = opts.has_key('r') |
|
246 | opts_r = opts.has_key('r') | |
246 |
|
247 | |||
247 | # Default line number value |
|
248 | # Default line number value | |
248 | lineno = opts.get('n',None) |
|
249 | lineno = opts.get('n',None) | |
249 | if lineno is not None: |
|
250 | if lineno is not None: | |
250 | try: |
|
251 | try: | |
251 | lineno = int(lineno) |
|
252 | lineno = int(lineno) | |
252 | except: |
|
253 | except: | |
253 | warn("The -n argument must be an integer.") |
|
254 | warn("The -n argument must be an integer.") | |
254 | return |
|
255 | return | |
255 |
|
256 | |||
256 | if opts_p: |
|
257 | if opts_p: | |
257 | args = '_%s' % last_call[0] |
|
258 | args = '_%s' % last_call[0] | |
258 | if not self.shell.user_ns.has_key(args): |
|
259 | if not self.shell.user_ns.has_key(args): | |
259 | args = last_call[1] |
|
260 | args = last_call[1] | |
260 |
|
261 | |||
261 | # use last_call to remember the state of the previous call, but don't |
|
262 | # use last_call to remember the state of the previous call, but don't | |
262 | # let it be clobbered by successive '-p' calls. |
|
263 | # let it be clobbered by successive '-p' calls. | |
263 | try: |
|
264 | try: | |
264 | last_call[0] = self.shell.displayhook.prompt_count |
|
265 | last_call[0] = self.shell.displayhook.prompt_count | |
265 | if not opts_p: |
|
266 | if not opts_p: | |
266 | last_call[1] = parameter_s |
|
267 | last_call[1] = parameter_s | |
267 | except: |
|
268 | except: | |
268 | pass |
|
269 | pass | |
269 |
|
270 | |||
270 | # by default this is done with temp files, except when the given |
|
271 | # by default this is done with temp files, except when the given | |
271 | # arg is a filename |
|
272 | # arg is a filename | |
272 | use_temp = 1 |
|
273 | use_temp = 1 | |
273 |
|
274 | |||
274 | if re.match(r'\d',args): |
|
275 | if re.match(r'\d',args): | |
275 | # Mode where user specifies ranges of lines, like in %macro. |
|
276 | # Mode where user specifies ranges of lines, like in %macro. | |
276 | # This means that you can't edit files whose names begin with |
|
277 | # This means that you can't edit files whose names begin with | |
277 | # numbers this way. Tough. |
|
278 | # numbers this way. Tough. | |
278 | ranges = args.split() |
|
279 | ranges = args.split() | |
279 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
280 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
280 | elif args.endswith('.py'): |
|
281 | elif args.endswith('.py'): | |
281 | filename = make_filename(args) |
|
282 | filename = make_filename(args) | |
282 | data = '' |
|
283 | data = '' | |
283 | use_temp = 0 |
|
284 | use_temp = 0 | |
284 | elif args: |
|
285 | elif args: | |
285 | try: |
|
286 | try: | |
286 | # Load the parameter given as a variable. If not a string, |
|
287 | # Load the parameter given as a variable. If not a string, | |
287 | # process it as an object instead (below) |
|
288 | # process it as an object instead (below) | |
288 |
|
289 | |||
289 | #print '*** args',args,'type',type(args) # dbg |
|
290 | #print '*** args',args,'type',type(args) # dbg | |
290 | data = eval(args,self.shell.user_ns) |
|
291 | data = eval(args,self.shell.user_ns) | |
291 | if not type(data) in StringTypes: |
|
292 | if not type(data) in StringTypes: | |
292 | raise DataIsObject |
|
293 | raise DataIsObject | |
293 |
|
294 | |||
294 | except (NameError,SyntaxError): |
|
295 | except (NameError,SyntaxError): | |
295 | # given argument is not a variable, try as a filename |
|
296 | # given argument is not a variable, try as a filename | |
296 | filename = make_filename(args) |
|
297 | filename = make_filename(args) | |
297 | if filename is None: |
|
298 | if filename is None: | |
298 | warn("Argument given (%s) can't be found as a variable " |
|
299 | warn("Argument given (%s) can't be found as a variable " | |
299 | "or as a filename." % args) |
|
300 | "or as a filename." % args) | |
300 | return |
|
301 | return | |
301 |
|
302 | |||
302 | data = '' |
|
303 | data = '' | |
303 | use_temp = 0 |
|
304 | use_temp = 0 | |
304 | except DataIsObject: |
|
305 | except DataIsObject: | |
305 |
|
306 | |||
306 | # macros have a special edit function |
|
307 | # macros have a special edit function | |
307 | if isinstance(data,Macro): |
|
308 | if isinstance(data,Macro): | |
308 | self._edit_macro(args,data) |
|
309 | self._edit_macro(args,data) | |
309 | return |
|
310 | return | |
310 |
|
311 | |||
311 | # For objects, try to edit the file where they are defined |
|
312 | # For objects, try to edit the file where they are defined | |
312 | try: |
|
313 | try: | |
313 | filename = inspect.getabsfile(data) |
|
314 | filename = inspect.getabsfile(data) | |
314 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
315 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
315 | # class created by %edit? Try to find source |
|
316 | # class created by %edit? Try to find source | |
316 | # by looking for method definitions instead, the |
|
317 | # by looking for method definitions instead, the | |
317 | # __module__ in those classes is FakeModule. |
|
318 | # __module__ in those classes is FakeModule. | |
318 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
319 | attrs = [getattr(data, aname) for aname in dir(data)] | |
319 | for attr in attrs: |
|
320 | for attr in attrs: | |
320 | if not inspect.ismethod(attr): |
|
321 | if not inspect.ismethod(attr): | |
321 | continue |
|
322 | continue | |
322 | filename = inspect.getabsfile(attr) |
|
323 | filename = inspect.getabsfile(attr) | |
323 | if filename and 'fakemodule' not in filename.lower(): |
|
324 | if filename and 'fakemodule' not in filename.lower(): | |
324 | # change the attribute to be the edit target instead |
|
325 | # change the attribute to be the edit target instead | |
325 | data = attr |
|
326 | data = attr | |
326 | break |
|
327 | break | |
327 |
|
328 | |||
328 | datafile = 1 |
|
329 | datafile = 1 | |
329 | except TypeError: |
|
330 | except TypeError: | |
330 | filename = make_filename(args) |
|
331 | filename = make_filename(args) | |
331 | datafile = 1 |
|
332 | datafile = 1 | |
332 | warn('Could not find file where `%s` is defined.\n' |
|
333 | warn('Could not find file where `%s` is defined.\n' | |
333 | 'Opening a file named `%s`' % (args,filename)) |
|
334 | 'Opening a file named `%s`' % (args,filename)) | |
334 | # Now, make sure we can actually read the source (if it was in |
|
335 | # Now, make sure we can actually read the source (if it was in | |
335 | # a temp file it's gone by now). |
|
336 | # a temp file it's gone by now). | |
336 | if datafile: |
|
337 | if datafile: | |
337 | try: |
|
338 | try: | |
338 | if lineno is None: |
|
339 | if lineno is None: | |
339 | lineno = inspect.getsourcelines(data)[1] |
|
340 | lineno = inspect.getsourcelines(data)[1] | |
340 | except IOError: |
|
341 | except IOError: | |
341 | filename = make_filename(args) |
|
342 | filename = make_filename(args) | |
342 | if filename is None: |
|
343 | if filename is None: | |
343 | warn('The file `%s` where `%s` was defined cannot ' |
|
344 | warn('The file `%s` where `%s` was defined cannot ' | |
344 | 'be read.' % (filename,data)) |
|
345 | 'be read.' % (filename,data)) | |
345 | return |
|
346 | return | |
346 | use_temp = 0 |
|
347 | use_temp = 0 | |
347 | else: |
|
348 | else: | |
348 | data = '' |
|
349 | data = '' | |
349 |
|
350 | |||
350 | if use_temp: |
|
351 | if use_temp: | |
351 | filename = self.shell.mktempfile(data) |
|
352 | filename = self.shell.mktempfile(data) | |
352 | print 'IPython will make a temporary file named:',filename |
|
353 | print 'IPython will make a temporary file named:',filename | |
353 |
|
354 | |||
354 | payload = { |
|
355 | payload = { | |
355 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
356 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
356 | 'filename' : filename, |
|
357 | 'filename' : filename, | |
357 | 'line_number' : lineno |
|
358 | 'line_number' : lineno | |
358 | } |
|
359 | } | |
359 | self.payload_manager.write_payload(payload) |
|
360 | self.payload_manager.write_payload(payload) | |
360 |
|
361 | |||
361 |
|
362 | |||
362 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
363 | def _showtraceback(self, etype, evalue, stb): | |
363 |
|
364 | |||
|
365 | exc_content = { | |||
|
366 | u'status' : u'error', | |||
|
367 | u'traceback' : stb, | |||
|
368 | u'ename' : unicode(etype.__name__), | |||
|
369 | u'evalue' : unicode(evalue) | |||
|
370 | } | |||
364 |
|
371 | |||
|
372 | dh = self.displayhook | |||
|
373 | exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header) | |||
|
374 | # Send exception info over pub socket for other clients than the caller | |||
|
375 | # to pick up | |||
|
376 | dh.pub_socket.send_json(exc_msg) | |||
|
377 | ||||
|
378 | # FIXME - Hack: store exception info in shell object. Right now, the | |||
|
379 | # caller is reading this info after the fact, we need to fix this logic | |||
|
380 | # to remove this hack. | |||
|
381 | self._reply_content = exc_content | |||
|
382 | # /FIXME | |||
|
383 | ||||
|
384 | return exc_content | |||
365 |
|
385 | |||
|
386 | def runlines(self, lines, clean=False): | |||
|
387 | return InteractiveShell.runlines(self, lines, clean) | |||
|
388 | ||||
|
389 | InteractiveShellABC.register(ZMQInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now