Show More
@@ -1,761 +1,761 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 |
|
2 | |||
3 | """Central interpreter object for an IPython engine. |
|
3 | """Central interpreter object for an IPython engine. | |
4 |
|
4 | |||
5 | The interpreter is the object whose job is to process lines of user input and |
|
5 | The interpreter is the object whose job is to process lines of user input and | |
6 | actually execute them in the user's namespace. |
|
6 | actually execute them in the user's namespace. | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | __docformat__ = "restructuredtext en" |
|
9 | __docformat__ = "restructuredtext en" | |
10 |
|
10 | |||
11 | #------------------------------------------------------------------------------- |
|
11 | #------------------------------------------------------------------------------- | |
12 | # Copyright (C) 2008 The IPython Development Team |
|
12 | # Copyright (C) 2008 The IPython Development Team | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #------------------------------------------------------------------------------- |
|
16 | #------------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #------------------------------------------------------------------------------- |
|
18 | #------------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #------------------------------------------------------------------------------- |
|
20 | #------------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | # Standard library imports. |
|
22 | # Standard library imports. | |
23 | from types import FunctionType |
|
23 | from types import FunctionType | |
24 |
|
24 | |||
25 | import __builtin__ |
|
25 | import __builtin__ | |
26 | import codeop |
|
26 | import codeop | |
27 | import compiler |
|
27 | import compiler | |
28 | import sys |
|
28 | import sys | |
29 | import traceback |
|
29 | import traceback | |
30 |
|
30 | |||
31 | # Local imports. |
|
31 | # Local imports. | |
32 |
from IPython |
|
32 | from IPython import ultraTB | |
33 | from IPython.kernel.core.display_trap import DisplayTrap |
|
33 | from IPython.kernel.core.display_trap import DisplayTrap | |
34 | from IPython.kernel.core.macro import Macro |
|
34 | from IPython.kernel.core.macro import Macro | |
35 | from IPython.kernel.core.prompts import CachedOutput |
|
35 | from IPython.kernel.core.prompts import CachedOutput | |
36 | from IPython.kernel.core.traceback_trap import TracebackTrap |
|
36 | from IPython.kernel.core.traceback_trap import TracebackTrap | |
37 | from IPython.kernel.core.util import Bunch, system_shell |
|
37 | from IPython.kernel.core.util import Bunch, system_shell | |
38 | from IPython.external.Itpl import ItplNS |
|
38 | from IPython.external.Itpl import ItplNS | |
39 |
|
39 | |||
40 | # Global constants |
|
40 | # Global constants | |
41 | COMPILER_ERROR = 'error' |
|
41 | COMPILER_ERROR = 'error' | |
42 | INCOMPLETE_INPUT = 'incomplete' |
|
42 | INCOMPLETE_INPUT = 'incomplete' | |
43 | COMPLETE_INPUT = 'complete' |
|
43 | COMPLETE_INPUT = 'complete' | |
44 |
|
44 | |||
45 | ############################################################################## |
|
45 | ############################################################################## | |
46 | # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or |
|
46 | # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or | |
47 | # not |
|
47 | # not | |
48 |
|
48 | |||
49 | rc = Bunch() |
|
49 | rc = Bunch() | |
50 | rc.cache_size = 100 |
|
50 | rc.cache_size = 100 | |
51 | rc.pprint = True |
|
51 | rc.pprint = True | |
52 | rc.separate_in = '\n' |
|
52 | rc.separate_in = '\n' | |
53 | rc.separate_out = '\n' |
|
53 | rc.separate_out = '\n' | |
54 | rc.separate_out2 = '' |
|
54 | rc.separate_out2 = '' | |
55 | rc.prompt_in1 = r'In [\#]: ' |
|
55 | rc.prompt_in1 = r'In [\#]: ' | |
56 | rc.prompt_in2 = r' .\\D.: ' |
|
56 | rc.prompt_in2 = r' .\\D.: ' | |
57 | rc.prompt_out = '' |
|
57 | rc.prompt_out = '' | |
58 | rc.prompts_pad_left = False |
|
58 | rc.prompts_pad_left = False | |
59 |
|
59 | |||
60 | ############################################################################## |
|
60 | ############################################################################## | |
61 |
|
61 | |||
62 | # Top-level utilities |
|
62 | # Top-level utilities | |
63 | def default_display_formatters(): |
|
63 | def default_display_formatters(): | |
64 | """ Return a list of default display formatters. |
|
64 | """ Return a list of default display formatters. | |
65 | """ |
|
65 | """ | |
66 |
|
66 | |||
67 | from display_formatter import PPrintDisplayFormatter, ReprDisplayFormatter |
|
67 | from display_formatter import PPrintDisplayFormatter, ReprDisplayFormatter | |
68 | return [PPrintDisplayFormatter(), ReprDisplayFormatter()] |
|
68 | return [PPrintDisplayFormatter(), ReprDisplayFormatter()] | |
69 |
|
69 | |||
70 | def default_traceback_formatters(): |
|
70 | def default_traceback_formatters(): | |
71 | """ Return a list of default traceback formatters. |
|
71 | """ Return a list of default traceback formatters. | |
72 | """ |
|
72 | """ | |
73 |
|
73 | |||
74 | from traceback_formatter import PlainTracebackFormatter |
|
74 | from traceback_formatter import PlainTracebackFormatter | |
75 | return [PlainTracebackFormatter()] |
|
75 | return [PlainTracebackFormatter()] | |
76 |
|
76 | |||
77 | # Top-level classes |
|
77 | # Top-level classes | |
78 | class NotDefined(object): pass |
|
78 | class NotDefined(object): pass | |
79 |
|
79 | |||
80 | class Interpreter(object): |
|
80 | class Interpreter(object): | |
81 | """ An interpreter object. |
|
81 | """ An interpreter object. | |
82 |
|
82 | |||
83 | fixme: needs to negotiate available formatters with frontends. |
|
83 | fixme: needs to negotiate available formatters with frontends. | |
84 |
|
84 | |||
85 | Important: the interpeter should be built so that it exposes a method |
|
85 | Important: the interpeter should be built so that it exposes a method | |
86 | for each attribute/method of its sub-object. This way it can be |
|
86 | for each attribute/method of its sub-object. This way it can be | |
87 | replaced by a network adapter. |
|
87 | replaced by a network adapter. | |
88 | """ |
|
88 | """ | |
89 |
|
89 | |||
90 | def __init__(self, user_ns=None, global_ns=None,translator=None, |
|
90 | def __init__(self, user_ns=None, global_ns=None,translator=None, | |
91 | magic=None, display_formatters=None, |
|
91 | magic=None, display_formatters=None, | |
92 | traceback_formatters=None, output_trap=None, history=None, |
|
92 | traceback_formatters=None, output_trap=None, history=None, | |
93 | message_cache=None, filename='<string>', config=None): |
|
93 | message_cache=None, filename='<string>', config=None): | |
94 |
|
94 | |||
95 | # The local/global namespaces for code execution |
|
95 | # The local/global namespaces for code execution | |
96 | local_ns = user_ns # compatibility name |
|
96 | local_ns = user_ns # compatibility name | |
97 | if local_ns is None: |
|
97 | if local_ns is None: | |
98 | local_ns = {} |
|
98 | local_ns = {} | |
99 | self.user_ns = local_ns |
|
99 | self.user_ns = local_ns | |
100 | # The local namespace |
|
100 | # The local namespace | |
101 | if global_ns is None: |
|
101 | if global_ns is None: | |
102 | global_ns = {} |
|
102 | global_ns = {} | |
103 | self.user_global_ns = global_ns |
|
103 | self.user_global_ns = global_ns | |
104 |
|
104 | |||
105 | # An object that will translate commands into executable Python. |
|
105 | # An object that will translate commands into executable Python. | |
106 | # The current translator does not work properly so for now we are going |
|
106 | # The current translator does not work properly so for now we are going | |
107 | # without! |
|
107 | # without! | |
108 | # if translator is None: |
|
108 | # if translator is None: | |
109 | # from IPython.kernel.core.translator import IPythonTranslator |
|
109 | # from IPython.kernel.core.translator import IPythonTranslator | |
110 | # translator = IPythonTranslator() |
|
110 | # translator = IPythonTranslator() | |
111 | self.translator = translator |
|
111 | self.translator = translator | |
112 |
|
112 | |||
113 | # An object that maintains magic commands. |
|
113 | # An object that maintains magic commands. | |
114 | if magic is None: |
|
114 | if magic is None: | |
115 | from IPython.kernel.core.magic import Magic |
|
115 | from IPython.kernel.core.magic import Magic | |
116 | magic = Magic(self) |
|
116 | magic = Magic(self) | |
117 | self.magic = magic |
|
117 | self.magic = magic | |
118 |
|
118 | |||
119 | # A list of formatters for the displayhook. |
|
119 | # A list of formatters for the displayhook. | |
120 | if display_formatters is None: |
|
120 | if display_formatters is None: | |
121 | display_formatters = default_display_formatters() |
|
121 | display_formatters = default_display_formatters() | |
122 | self.display_formatters = display_formatters |
|
122 | self.display_formatters = display_formatters | |
123 |
|
123 | |||
124 | # A list of formatters for tracebacks. |
|
124 | # A list of formatters for tracebacks. | |
125 | if traceback_formatters is None: |
|
125 | if traceback_formatters is None: | |
126 | traceback_formatters = default_traceback_formatters() |
|
126 | traceback_formatters = default_traceback_formatters() | |
127 | self.traceback_formatters = traceback_formatters |
|
127 | self.traceback_formatters = traceback_formatters | |
128 |
|
128 | |||
129 | # The object trapping stdout/stderr. |
|
129 | # The object trapping stdout/stderr. | |
130 | if output_trap is None: |
|
130 | if output_trap is None: | |
131 | from IPython.kernel.core.output_trap import OutputTrap |
|
131 | from IPython.kernel.core.output_trap import OutputTrap | |
132 | output_trap = OutputTrap() |
|
132 | output_trap = OutputTrap() | |
133 | self.output_trap = output_trap |
|
133 | self.output_trap = output_trap | |
134 |
|
134 | |||
135 | # An object that manages the history. |
|
135 | # An object that manages the history. | |
136 | if history is None: |
|
136 | if history is None: | |
137 | from IPython.kernel.core.history import InterpreterHistory |
|
137 | from IPython.kernel.core.history import InterpreterHistory | |
138 | history = InterpreterHistory() |
|
138 | history = InterpreterHistory() | |
139 | self.history = history |
|
139 | self.history = history | |
140 | self.get_history_item = history.get_history_item |
|
140 | self.get_history_item = history.get_history_item | |
141 | self.get_history_input_cache = history.get_input_cache |
|
141 | self.get_history_input_cache = history.get_input_cache | |
142 | self.get_history_input_after = history.get_input_after |
|
142 | self.get_history_input_after = history.get_input_after | |
143 |
|
143 | |||
144 | # An object that caches all of the return messages. |
|
144 | # An object that caches all of the return messages. | |
145 | if message_cache is None: |
|
145 | if message_cache is None: | |
146 | from IPython.kernel.core.message_cache import SimpleMessageCache |
|
146 | from IPython.kernel.core.message_cache import SimpleMessageCache | |
147 | message_cache = SimpleMessageCache() |
|
147 | message_cache = SimpleMessageCache() | |
148 | self.message_cache = message_cache |
|
148 | self.message_cache = message_cache | |
149 |
|
149 | |||
150 | # The "filename" of the code that is executed in this interpreter. |
|
150 | # The "filename" of the code that is executed in this interpreter. | |
151 | self.filename = filename |
|
151 | self.filename = filename | |
152 |
|
152 | |||
153 | # An object that contains much configuration information. |
|
153 | # An object that contains much configuration information. | |
154 | if config is None: |
|
154 | if config is None: | |
155 | # fixme: Move this constant elsewhere! |
|
155 | # fixme: Move this constant elsewhere! | |
156 | config = Bunch(ESC_MAGIC='%') |
|
156 | config = Bunch(ESC_MAGIC='%') | |
157 | self.config = config |
|
157 | self.config = config | |
158 |
|
158 | |||
159 | # Hook managers. |
|
159 | # Hook managers. | |
160 | # fixme: make the display callbacks configurable. In the meantime, |
|
160 | # fixme: make the display callbacks configurable. In the meantime, | |
161 | # enable macros. |
|
161 | # enable macros. | |
162 | self.display_trap = DisplayTrap( |
|
162 | self.display_trap = DisplayTrap( | |
163 | formatters=self.display_formatters, |
|
163 | formatters=self.display_formatters, | |
164 | callbacks=[self._possible_macro], |
|
164 | callbacks=[self._possible_macro], | |
165 | ) |
|
165 | ) | |
166 | self.traceback_trap = TracebackTrap( |
|
166 | self.traceback_trap = TracebackTrap( | |
167 | formatters=self.traceback_formatters) |
|
167 | formatters=self.traceback_formatters) | |
168 |
|
168 | |||
169 | # This is used temporarily for reformating exceptions in certain |
|
169 | # This is used temporarily for reformating exceptions in certain | |
170 | # cases. It will go away once the ultraTB stuff is ported |
|
170 | # cases. It will go away once the ultraTB stuff is ported | |
171 | # to ipython1 |
|
171 | # to ipython1 | |
172 | self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor', |
|
172 | self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor', | |
173 | mode='Context', |
|
173 | mode='Context', | |
174 | tb_offset=2) |
|
174 | tb_offset=2) | |
175 |
|
175 | |||
176 | # An object that can compile commands and remember __future__ |
|
176 | # An object that can compile commands and remember __future__ | |
177 | # statements. |
|
177 | # statements. | |
178 | self.command_compiler = codeop.CommandCompiler() |
|
178 | self.command_compiler = codeop.CommandCompiler() | |
179 |
|
179 | |||
180 | # A replacement for the raw_input() and input() builtins. Change these |
|
180 | # A replacement for the raw_input() and input() builtins. Change these | |
181 | # attributes later to configure them. |
|
181 | # attributes later to configure them. | |
182 | self.raw_input_builtin = raw_input |
|
182 | self.raw_input_builtin = raw_input | |
183 | self.input_builtin = input |
|
183 | self.input_builtin = input | |
184 |
|
184 | |||
185 | # The number of the current cell. |
|
185 | # The number of the current cell. | |
186 | self.current_cell_number = 1 |
|
186 | self.current_cell_number = 1 | |
187 |
|
187 | |||
188 | # Initialize cache, set in/out prompts and printing system |
|
188 | # Initialize cache, set in/out prompts and printing system | |
189 | self.outputcache = CachedOutput(self, |
|
189 | self.outputcache = CachedOutput(self, | |
190 | rc.cache_size, |
|
190 | rc.cache_size, | |
191 | rc.pprint, |
|
191 | rc.pprint, | |
192 | input_sep = rc.separate_in, |
|
192 | input_sep = rc.separate_in, | |
193 | output_sep = rc.separate_out, |
|
193 | output_sep = rc.separate_out, | |
194 | output_sep2 = rc.separate_out2, |
|
194 | output_sep2 = rc.separate_out2, | |
195 | ps1 = rc.prompt_in1, |
|
195 | ps1 = rc.prompt_in1, | |
196 | ps2 = rc.prompt_in2, |
|
196 | ps2 = rc.prompt_in2, | |
197 | ps_out = rc.prompt_out, |
|
197 | ps_out = rc.prompt_out, | |
198 | pad_left = rc.prompts_pad_left) |
|
198 | pad_left = rc.prompts_pad_left) | |
199 |
|
199 | |||
200 | # Need to decide later if this is the right approach, but clients |
|
200 | # Need to decide later if this is the right approach, but clients | |
201 | # commonly use sys.ps1/2, so it may be best to just set them here |
|
201 | # commonly use sys.ps1/2, so it may be best to just set them here | |
202 | sys.ps1 = self.outputcache.prompt1.p_str |
|
202 | sys.ps1 = self.outputcache.prompt1.p_str | |
203 | sys.ps2 = self.outputcache.prompt2.p_str |
|
203 | sys.ps2 = self.outputcache.prompt2.p_str | |
204 |
|
204 | |||
205 | # This is the message dictionary assigned temporarily when running the |
|
205 | # This is the message dictionary assigned temporarily when running the | |
206 | # code. |
|
206 | # code. | |
207 | self.message = None |
|
207 | self.message = None | |
208 |
|
208 | |||
209 | self.setup_namespace() |
|
209 | self.setup_namespace() | |
210 |
|
210 | |||
211 |
|
211 | |||
212 | #### Public 'Interpreter' interface ######################################## |
|
212 | #### Public 'Interpreter' interface ######################################## | |
213 |
|
213 | |||
214 | def formatTraceback(self, et, ev, tb, message=''): |
|
214 | def formatTraceback(self, et, ev, tb, message=''): | |
215 | """Put a formatted version of the traceback into value and reraise. |
|
215 | """Put a formatted version of the traceback into value and reraise. | |
216 |
|
216 | |||
217 | When exceptions have to be sent over the network, the traceback |
|
217 | When exceptions have to be sent over the network, the traceback | |
218 | needs to be put into the value of the exception in a nicely |
|
218 | needs to be put into the value of the exception in a nicely | |
219 | formatted way. The method takes the type, value and tb of an |
|
219 | formatted way. The method takes the type, value and tb of an | |
220 | exception and puts a string representation of the tb into the |
|
220 | exception and puts a string representation of the tb into the | |
221 | value of the exception and reraises it. |
|
221 | value of the exception and reraises it. | |
222 |
|
222 | |||
223 | Currently this method uses the ultraTb formatter from IPython trunk. |
|
223 | Currently this method uses the ultraTb formatter from IPython trunk. | |
224 | Eventually it should simply use the traceback formatters in core |
|
224 | Eventually it should simply use the traceback formatters in core | |
225 | that are loaded into self.tracback_trap.formatters. |
|
225 | that are loaded into self.tracback_trap.formatters. | |
226 | """ |
|
226 | """ | |
227 | tbinfo = self.tbHandler.text(et,ev,tb) |
|
227 | tbinfo = self.tbHandler.text(et,ev,tb) | |
228 | ev._ipython_traceback_text = tbinfo |
|
228 | ev._ipython_traceback_text = tbinfo | |
229 | return et, ev, tb |
|
229 | return et, ev, tb | |
230 |
|
230 | |||
231 | def execute(self, commands, raiseException=True): |
|
231 | def execute(self, commands, raiseException=True): | |
232 | """ Execute some IPython commands. |
|
232 | """ Execute some IPython commands. | |
233 |
|
233 | |||
234 | 1. Translate them into Python. |
|
234 | 1. Translate them into Python. | |
235 | 2. Run them. |
|
235 | 2. Run them. | |
236 | 3. Trap stdout/stderr. |
|
236 | 3. Trap stdout/stderr. | |
237 | 4. Trap sys.displayhook(). |
|
237 | 4. Trap sys.displayhook(). | |
238 | 5. Trap exceptions. |
|
238 | 5. Trap exceptions. | |
239 | 6. Return a message object. |
|
239 | 6. Return a message object. | |
240 |
|
240 | |||
241 | Parameters |
|
241 | Parameters | |
242 | ---------- |
|
242 | ---------- | |
243 | commands : str |
|
243 | commands : str | |
244 | The raw commands that the user typed into the prompt. |
|
244 | The raw commands that the user typed into the prompt. | |
245 |
|
245 | |||
246 | Returns |
|
246 | Returns | |
247 | ------- |
|
247 | ------- | |
248 | message : dict |
|
248 | message : dict | |
249 | The dictionary of responses. See the README.txt in this directory |
|
249 | The dictionary of responses. See the README.txt in this directory | |
250 | for an explanation of the format. |
|
250 | for an explanation of the format. | |
251 | """ |
|
251 | """ | |
252 |
|
252 | |||
253 | # Create a message dictionary with all of the information we will be |
|
253 | # Create a message dictionary with all of the information we will be | |
254 | # returning to the frontend and other listeners. |
|
254 | # returning to the frontend and other listeners. | |
255 | message = self.setup_message() |
|
255 | message = self.setup_message() | |
256 |
|
256 | |||
257 | # Massage the input and store the raw and translated commands into |
|
257 | # Massage the input and store the raw and translated commands into | |
258 | # a dict. |
|
258 | # a dict. | |
259 | user_input = dict(raw=commands) |
|
259 | user_input = dict(raw=commands) | |
260 | if self.translator is not None: |
|
260 | if self.translator is not None: | |
261 | python = self.translator(commands, message) |
|
261 | python = self.translator(commands, message) | |
262 | if python is None: |
|
262 | if python is None: | |
263 | # Something went wrong with the translation. The translator |
|
263 | # Something went wrong with the translation. The translator | |
264 | # should have added an appropriate entry to the message object. |
|
264 | # should have added an appropriate entry to the message object. | |
265 | return message |
|
265 | return message | |
266 | else: |
|
266 | else: | |
267 | python = commands |
|
267 | python = commands | |
268 | user_input['translated'] = python |
|
268 | user_input['translated'] = python | |
269 | message['input'] = user_input |
|
269 | message['input'] = user_input | |
270 |
|
270 | |||
271 | # Set the message object so that any magics executed in the code have |
|
271 | # Set the message object so that any magics executed in the code have | |
272 | # access. |
|
272 | # access. | |
273 | self.message = message |
|
273 | self.message = message | |
274 |
|
274 | |||
275 | # Set all of the output/exception traps. |
|
275 | # Set all of the output/exception traps. | |
276 | self.set_traps() |
|
276 | self.set_traps() | |
277 |
|
277 | |||
278 | # Actually execute the Python code. |
|
278 | # Actually execute the Python code. | |
279 | status = self.execute_python(python) |
|
279 | status = self.execute_python(python) | |
280 |
|
280 | |||
281 | # Unset all of the traps. |
|
281 | # Unset all of the traps. | |
282 | self.unset_traps() |
|
282 | self.unset_traps() | |
283 |
|
283 | |||
284 | # Unset the message object. |
|
284 | # Unset the message object. | |
285 | self.message = None |
|
285 | self.message = None | |
286 |
|
286 | |||
287 | # Update the history variables in the namespace. |
|
287 | # Update the history variables in the namespace. | |
288 | # E.g. In, Out, _, __, ___ |
|
288 | # E.g. In, Out, _, __, ___ | |
289 | if self.history is not None: |
|
289 | if self.history is not None: | |
290 | self.history.update_history(self, python) |
|
290 | self.history.update_history(self, python) | |
291 |
|
291 | |||
292 | # Let all of the traps contribute to the message and then clear their |
|
292 | # Let all of the traps contribute to the message and then clear their | |
293 | # stored information. |
|
293 | # stored information. | |
294 | self.output_trap.add_to_message(message) |
|
294 | self.output_trap.add_to_message(message) | |
295 | self.output_trap.clear() |
|
295 | self.output_trap.clear() | |
296 | self.display_trap.add_to_message(message) |
|
296 | self.display_trap.add_to_message(message) | |
297 | self.display_trap.clear() |
|
297 | self.display_trap.clear() | |
298 | self.traceback_trap.add_to_message(message) |
|
298 | self.traceback_trap.add_to_message(message) | |
299 | # Pull out the type, value and tb of the current exception |
|
299 | # Pull out the type, value and tb of the current exception | |
300 | # before clearing it. |
|
300 | # before clearing it. | |
301 | einfo = self.traceback_trap.args |
|
301 | einfo = self.traceback_trap.args | |
302 | self.traceback_trap.clear() |
|
302 | self.traceback_trap.clear() | |
303 |
|
303 | |||
304 | # Cache the message. |
|
304 | # Cache the message. | |
305 | self.message_cache.add_message(self.current_cell_number, message) |
|
305 | self.message_cache.add_message(self.current_cell_number, message) | |
306 |
|
306 | |||
307 | # Bump the number. |
|
307 | # Bump the number. | |
308 | self.current_cell_number += 1 |
|
308 | self.current_cell_number += 1 | |
309 |
|
309 | |||
310 | # This conditional lets the execute method either raise any |
|
310 | # This conditional lets the execute method either raise any | |
311 | # exception that has occured in user code OR return the message |
|
311 | # exception that has occured in user code OR return the message | |
312 | # dict containing the traceback and other useful info. |
|
312 | # dict containing the traceback and other useful info. | |
313 | if raiseException and einfo: |
|
313 | if raiseException and einfo: | |
314 | raise einfo[0],einfo[1],einfo[2] |
|
314 | raise einfo[0],einfo[1],einfo[2] | |
315 | else: |
|
315 | else: | |
316 | return message |
|
316 | return message | |
317 |
|
317 | |||
318 | def generate_prompt(self, is_continuation): |
|
318 | def generate_prompt(self, is_continuation): | |
319 | """Calculate and return a string with the prompt to display. |
|
319 | """Calculate and return a string with the prompt to display. | |
320 |
|
320 | |||
321 | :Parameters: |
|
321 | :Parameters: | |
322 | is_continuation : bool |
|
322 | is_continuation : bool | |
323 | Whether the input line is continuing multiline input or not, so |
|
323 | Whether the input line is continuing multiline input or not, so | |
324 | that a proper continuation prompt can be computed.""" |
|
324 | that a proper continuation prompt can be computed.""" | |
325 |
|
325 | |||
326 | if is_continuation: |
|
326 | if is_continuation: | |
327 | return str(self.outputcache.prompt2) |
|
327 | return str(self.outputcache.prompt2) | |
328 | else: |
|
328 | else: | |
329 | return str(self.outputcache.prompt1) |
|
329 | return str(self.outputcache.prompt1) | |
330 |
|
330 | |||
331 | def execute_python(self, python): |
|
331 | def execute_python(self, python): | |
332 | """ Actually run the Python code in the namespace. |
|
332 | """ Actually run the Python code in the namespace. | |
333 |
|
333 | |||
334 | :Parameters: |
|
334 | :Parameters: | |
335 |
|
335 | |||
336 | python : str |
|
336 | python : str | |
337 | Pure, exec'able Python code. Special IPython commands should have |
|
337 | Pure, exec'able Python code. Special IPython commands should have | |
338 | already been translated into pure Python. |
|
338 | already been translated into pure Python. | |
339 | """ |
|
339 | """ | |
340 |
|
340 | |||
341 | # We use a CommandCompiler instance to compile the code so as to keep |
|
341 | # We use a CommandCompiler instance to compile the code so as to keep | |
342 | # track of __future__ imports. |
|
342 | # track of __future__ imports. | |
343 | try: |
|
343 | try: | |
344 | commands = self.split_commands(python) |
|
344 | commands = self.split_commands(python) | |
345 | except (SyntaxError, IndentationError), e: |
|
345 | except (SyntaxError, IndentationError), e: | |
346 | # Save the exc_info so compilation related exceptions can be |
|
346 | # Save the exc_info so compilation related exceptions can be | |
347 | # reraised |
|
347 | # reraised | |
348 | self.traceback_trap.args = sys.exc_info() |
|
348 | self.traceback_trap.args = sys.exc_info() | |
349 | self.pack_exception(self.message,e) |
|
349 | self.pack_exception(self.message,e) | |
350 | return None |
|
350 | return None | |
351 |
|
351 | |||
352 | for cmd in commands: |
|
352 | for cmd in commands: | |
353 | try: |
|
353 | try: | |
354 | code = self.command_compiler(cmd, self.filename, 'single') |
|
354 | code = self.command_compiler(cmd, self.filename, 'single') | |
355 | except (SyntaxError, OverflowError, ValueError), e: |
|
355 | except (SyntaxError, OverflowError, ValueError), e: | |
356 | self.traceback_trap.args = sys.exc_info() |
|
356 | self.traceback_trap.args = sys.exc_info() | |
357 | self.pack_exception(self.message,e) |
|
357 | self.pack_exception(self.message,e) | |
358 | # No point in continuing if one block raised |
|
358 | # No point in continuing if one block raised | |
359 | return None |
|
359 | return None | |
360 | else: |
|
360 | else: | |
361 | self.execute_block(code) |
|
361 | self.execute_block(code) | |
362 |
|
362 | |||
363 | def execute_block(self,code): |
|
363 | def execute_block(self,code): | |
364 | """Execute a single block of code in the user namespace. |
|
364 | """Execute a single block of code in the user namespace. | |
365 |
|
365 | |||
366 | Return value: a flag indicating whether the code to be run completed |
|
366 | Return value: a flag indicating whether the code to be run completed | |
367 | successfully: |
|
367 | successfully: | |
368 |
|
368 | |||
369 | - 0: successful execution. |
|
369 | - 0: successful execution. | |
370 | - 1: an error occurred. |
|
370 | - 1: an error occurred. | |
371 | """ |
|
371 | """ | |
372 |
|
372 | |||
373 | outflag = 1 # start by assuming error, success will reset it |
|
373 | outflag = 1 # start by assuming error, success will reset it | |
374 | try: |
|
374 | try: | |
375 | exec code in self.user_ns |
|
375 | exec code in self.user_ns | |
376 | outflag = 0 |
|
376 | outflag = 0 | |
377 | except SystemExit: |
|
377 | except SystemExit: | |
378 | self.resetbuffer() |
|
378 | self.resetbuffer() | |
379 | self.traceback_trap.args = sys.exc_info() |
|
379 | self.traceback_trap.args = sys.exc_info() | |
380 | except: |
|
380 | except: | |
381 | self.traceback_trap.args = sys.exc_info() |
|
381 | self.traceback_trap.args = sys.exc_info() | |
382 |
|
382 | |||
383 | return outflag |
|
383 | return outflag | |
384 |
|
384 | |||
385 | def execute_macro(self, macro): |
|
385 | def execute_macro(self, macro): | |
386 | """ Execute the value of a macro. |
|
386 | """ Execute the value of a macro. | |
387 |
|
387 | |||
388 | Parameters |
|
388 | Parameters | |
389 | ---------- |
|
389 | ---------- | |
390 | macro : Macro |
|
390 | macro : Macro | |
391 | """ |
|
391 | """ | |
392 |
|
392 | |||
393 | python = macro.value |
|
393 | python = macro.value | |
394 | if self.translator is not None: |
|
394 | if self.translator is not None: | |
395 | python = self.translator(python) |
|
395 | python = self.translator(python) | |
396 | self.execute_python(python) |
|
396 | self.execute_python(python) | |
397 |
|
397 | |||
398 | def getCommand(self, i=None): |
|
398 | def getCommand(self, i=None): | |
399 | """Gets the ith message in the message_cache. |
|
399 | """Gets the ith message in the message_cache. | |
400 |
|
400 | |||
401 | This is implemented here for compatibility with the old ipython1 shell |
|
401 | This is implemented here for compatibility with the old ipython1 shell | |
402 | I am not sure we need this though. I even seem to remember that we |
|
402 | I am not sure we need this though. I even seem to remember that we | |
403 | were going to get rid of it. |
|
403 | were going to get rid of it. | |
404 | """ |
|
404 | """ | |
405 | return self.message_cache.get_message(i) |
|
405 | return self.message_cache.get_message(i) | |
406 |
|
406 | |||
407 | def reset(self): |
|
407 | def reset(self): | |
408 | """Reset the interpreter. |
|
408 | """Reset the interpreter. | |
409 |
|
409 | |||
410 | Currently this only resets the users variables in the namespace. |
|
410 | Currently this only resets the users variables in the namespace. | |
411 | In the future we might want to also reset the other stateful |
|
411 | In the future we might want to also reset the other stateful | |
412 | things like that the Interpreter has, like In, Out, etc. |
|
412 | things like that the Interpreter has, like In, Out, etc. | |
413 | """ |
|
413 | """ | |
414 | self.user_ns.clear() |
|
414 | self.user_ns.clear() | |
415 | self.setup_namespace() |
|
415 | self.setup_namespace() | |
416 |
|
416 | |||
417 | def complete(self,line,text=None, pos=None): |
|
417 | def complete(self,line,text=None, pos=None): | |
418 | """Complete the given text. |
|
418 | """Complete the given text. | |
419 |
|
419 | |||
420 | :Parameters: |
|
420 | :Parameters: | |
421 |
|
421 | |||
422 | text : str |
|
422 | text : str | |
423 | Text fragment to be completed on. Typically this is |
|
423 | Text fragment to be completed on. Typically this is | |
424 | """ |
|
424 | """ | |
425 | # fixme: implement |
|
425 | # fixme: implement | |
426 | raise NotImplementedError |
|
426 | raise NotImplementedError | |
427 |
|
427 | |||
428 | def push(self, ns): |
|
428 | def push(self, ns): | |
429 | """ Put value into the namespace with name key. |
|
429 | """ Put value into the namespace with name key. | |
430 |
|
430 | |||
431 | Parameters |
|
431 | Parameters | |
432 | ---------- |
|
432 | ---------- | |
433 | **kwds |
|
433 | **kwds | |
434 | """ |
|
434 | """ | |
435 |
|
435 | |||
436 | self.user_ns.update(ns) |
|
436 | self.user_ns.update(ns) | |
437 |
|
437 | |||
438 | def push_function(self, ns): |
|
438 | def push_function(self, ns): | |
439 | # First set the func_globals for all functions to self.user_ns |
|
439 | # First set the func_globals for all functions to self.user_ns | |
440 | new_kwds = {} |
|
440 | new_kwds = {} | |
441 | for k, v in ns.iteritems(): |
|
441 | for k, v in ns.iteritems(): | |
442 | if not isinstance(v, FunctionType): |
|
442 | if not isinstance(v, FunctionType): | |
443 | raise TypeError("function object expected") |
|
443 | raise TypeError("function object expected") | |
444 | new_kwds[k] = FunctionType(v.func_code, self.user_ns) |
|
444 | new_kwds[k] = FunctionType(v.func_code, self.user_ns) | |
445 | self.user_ns.update(new_kwds) |
|
445 | self.user_ns.update(new_kwds) | |
446 |
|
446 | |||
447 | def pack_exception(self,message,exc): |
|
447 | def pack_exception(self,message,exc): | |
448 | message['exception'] = exc.__class__ |
|
448 | message['exception'] = exc.__class__ | |
449 | message['exception_value'] = \ |
|
449 | message['exception_value'] = \ | |
450 | traceback.format_exception_only(exc.__class__, exc) |
|
450 | traceback.format_exception_only(exc.__class__, exc) | |
451 |
|
451 | |||
452 | def feed_block(self, source, filename='<input>', symbol='single'): |
|
452 | def feed_block(self, source, filename='<input>', symbol='single'): | |
453 | """Compile some source in the interpreter. |
|
453 | """Compile some source in the interpreter. | |
454 |
|
454 | |||
455 | One several things can happen: |
|
455 | One several things can happen: | |
456 |
|
456 | |||
457 | 1) The input is incorrect; compile_command() raised an |
|
457 | 1) The input is incorrect; compile_command() raised an | |
458 | exception (SyntaxError or OverflowError). |
|
458 | exception (SyntaxError or OverflowError). | |
459 |
|
459 | |||
460 | 2) The input is incomplete, and more input is required; |
|
460 | 2) The input is incomplete, and more input is required; | |
461 | compile_command() returned None. Nothing happens. |
|
461 | compile_command() returned None. Nothing happens. | |
462 |
|
462 | |||
463 | 3) The input is complete; compile_command() returned a code |
|
463 | 3) The input is complete; compile_command() returned a code | |
464 | object. The code is executed by calling self.runcode() (which |
|
464 | object. The code is executed by calling self.runcode() (which | |
465 | also handles run-time exceptions, except for SystemExit). |
|
465 | also handles run-time exceptions, except for SystemExit). | |
466 |
|
466 | |||
467 | The return value is: |
|
467 | The return value is: | |
468 |
|
468 | |||
469 | - True in case 2 |
|
469 | - True in case 2 | |
470 |
|
470 | |||
471 | - False in the other cases, unless an exception is raised, where |
|
471 | - False in the other cases, unless an exception is raised, where | |
472 | None is returned instead. This can be used by external callers to |
|
472 | None is returned instead. This can be used by external callers to | |
473 | know whether to continue feeding input or not. |
|
473 | know whether to continue feeding input or not. | |
474 |
|
474 | |||
475 | The return value can be used to decide whether to use sys.ps1 or |
|
475 | The return value can be used to decide whether to use sys.ps1 or | |
476 | sys.ps2 to prompt the next line.""" |
|
476 | sys.ps2 to prompt the next line.""" | |
477 |
|
477 | |||
478 | self.message = self.setup_message() |
|
478 | self.message = self.setup_message() | |
479 |
|
479 | |||
480 | try: |
|
480 | try: | |
481 | code = self.command_compiler(source,filename,symbol) |
|
481 | code = self.command_compiler(source,filename,symbol) | |
482 | except (OverflowError, SyntaxError, IndentationError, ValueError ), e: |
|
482 | except (OverflowError, SyntaxError, IndentationError, ValueError ), e: | |
483 | # Case 1 |
|
483 | # Case 1 | |
484 | self.traceback_trap.args = sys.exc_info() |
|
484 | self.traceback_trap.args = sys.exc_info() | |
485 | self.pack_exception(self.message,e) |
|
485 | self.pack_exception(self.message,e) | |
486 | return COMPILER_ERROR,False |
|
486 | return COMPILER_ERROR,False | |
487 |
|
487 | |||
488 | if code is None: |
|
488 | if code is None: | |
489 | # Case 2: incomplete input. This means that the input can span |
|
489 | # Case 2: incomplete input. This means that the input can span | |
490 | # multiple lines. But we still need to decide when to actually |
|
490 | # multiple lines. But we still need to decide when to actually | |
491 | # stop taking user input. Later we'll add auto-indentation support |
|
491 | # stop taking user input. Later we'll add auto-indentation support | |
492 | # somehow. In the meantime, we'll just stop if there are two lines |
|
492 | # somehow. In the meantime, we'll just stop if there are two lines | |
493 | # of pure whitespace at the end. |
|
493 | # of pure whitespace at the end. | |
494 | last_two = source.rsplit('\n',2)[-2:] |
|
494 | last_two = source.rsplit('\n',2)[-2:] | |
495 | print 'last two:',last_two # dbg |
|
495 | print 'last two:',last_two # dbg | |
496 | if len(last_two)==2 and all(s.isspace() for s in last_two): |
|
496 | if len(last_two)==2 and all(s.isspace() for s in last_two): | |
497 | return COMPLETE_INPUT,False |
|
497 | return COMPLETE_INPUT,False | |
498 | else: |
|
498 | else: | |
499 | return INCOMPLETE_INPUT, True |
|
499 | return INCOMPLETE_INPUT, True | |
500 | else: |
|
500 | else: | |
501 | # Case 3 |
|
501 | # Case 3 | |
502 | return COMPLETE_INPUT, False |
|
502 | return COMPLETE_INPUT, False | |
503 |
|
503 | |||
504 | def pull(self, keys): |
|
504 | def pull(self, keys): | |
505 | """ Get an item out of the namespace by key. |
|
505 | """ Get an item out of the namespace by key. | |
506 |
|
506 | |||
507 | Parameters |
|
507 | Parameters | |
508 | ---------- |
|
508 | ---------- | |
509 | key : str |
|
509 | key : str | |
510 |
|
510 | |||
511 | Returns |
|
511 | Returns | |
512 | ------- |
|
512 | ------- | |
513 | value : object |
|
513 | value : object | |
514 |
|
514 | |||
515 | Raises |
|
515 | Raises | |
516 | ------ |
|
516 | ------ | |
517 | TypeError if the key is not a string. |
|
517 | TypeError if the key is not a string. | |
518 | NameError if the object doesn't exist. |
|
518 | NameError if the object doesn't exist. | |
519 | """ |
|
519 | """ | |
520 |
|
520 | |||
521 | if isinstance(keys, str): |
|
521 | if isinstance(keys, str): | |
522 | result = self.user_ns.get(keys, NotDefined()) |
|
522 | result = self.user_ns.get(keys, NotDefined()) | |
523 | if isinstance(result, NotDefined): |
|
523 | if isinstance(result, NotDefined): | |
524 | raise NameError('name %s is not defined' % keys) |
|
524 | raise NameError('name %s is not defined' % keys) | |
525 | elif isinstance(keys, (list, tuple)): |
|
525 | elif isinstance(keys, (list, tuple)): | |
526 | result = [] |
|
526 | result = [] | |
527 | for key in keys: |
|
527 | for key in keys: | |
528 | if not isinstance(key, str): |
|
528 | if not isinstance(key, str): | |
529 | raise TypeError("objects must be keyed by strings.") |
|
529 | raise TypeError("objects must be keyed by strings.") | |
530 | else: |
|
530 | else: | |
531 | r = self.user_ns.get(key, NotDefined()) |
|
531 | r = self.user_ns.get(key, NotDefined()) | |
532 | if isinstance(r, NotDefined): |
|
532 | if isinstance(r, NotDefined): | |
533 | raise NameError('name %s is not defined' % key) |
|
533 | raise NameError('name %s is not defined' % key) | |
534 | else: |
|
534 | else: | |
535 | result.append(r) |
|
535 | result.append(r) | |
536 | if len(keys)==1: |
|
536 | if len(keys)==1: | |
537 | result = result[0] |
|
537 | result = result[0] | |
538 | else: |
|
538 | else: | |
539 | raise TypeError("keys must be a strong or a list/tuple of strings") |
|
539 | raise TypeError("keys must be a strong or a list/tuple of strings") | |
540 | return result |
|
540 | return result | |
541 |
|
541 | |||
542 | def pull_function(self, keys): |
|
542 | def pull_function(self, keys): | |
543 | return self.pull(keys) |
|
543 | return self.pull(keys) | |
544 |
|
544 | |||
545 | #### Interactive user API ################################################## |
|
545 | #### Interactive user API ################################################## | |
546 |
|
546 | |||
547 | def ipsystem(self, command): |
|
547 | def ipsystem(self, command): | |
548 | """ Execute a command in a system shell while expanding variables in the |
|
548 | """ Execute a command in a system shell while expanding variables in the | |
549 | current namespace. |
|
549 | current namespace. | |
550 |
|
550 | |||
551 | Parameters |
|
551 | Parameters | |
552 | ---------- |
|
552 | ---------- | |
553 | command : str |
|
553 | command : str | |
554 | """ |
|
554 | """ | |
555 |
|
555 | |||
556 | # Expand $variables. |
|
556 | # Expand $variables. | |
557 | command = self.var_expand(command) |
|
557 | command = self.var_expand(command) | |
558 |
|
558 | |||
559 | system_shell(command, |
|
559 | system_shell(command, | |
560 | header='IPython system call: ', |
|
560 | header='IPython system call: ', | |
561 | verbose=self.rc.system_verbose, |
|
561 | verbose=self.rc.system_verbose, | |
562 | ) |
|
562 | ) | |
563 |
|
563 | |||
564 | def ipmagic(self, arg_string): |
|
564 | def ipmagic(self, arg_string): | |
565 | """ Call a magic function by name. |
|
565 | """ Call a magic function by name. | |
566 |
|
566 | |||
567 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython |
|
567 | ipmagic('name -opt foo bar') is equivalent to typing at the ipython | |
568 | prompt: |
|
568 | prompt: | |
569 |
|
569 | |||
570 | In[1]: %name -opt foo bar |
|
570 | In[1]: %name -opt foo bar | |
571 |
|
571 | |||
572 | To call a magic without arguments, simply use ipmagic('name'). |
|
572 | To call a magic without arguments, simply use ipmagic('name'). | |
573 |
|
573 | |||
574 | This provides a proper Python function to call IPython's magics in any |
|
574 | This provides a proper Python function to call IPython's magics in any | |
575 | valid Python code you can type at the interpreter, including loops and |
|
575 | valid Python code you can type at the interpreter, including loops and | |
576 | compound statements. It is added by IPython to the Python builtin |
|
576 | compound statements. It is added by IPython to the Python builtin | |
577 | namespace upon initialization. |
|
577 | namespace upon initialization. | |
578 |
|
578 | |||
579 | Parameters |
|
579 | Parameters | |
580 | ---------- |
|
580 | ---------- | |
581 | arg_string : str |
|
581 | arg_string : str | |
582 | A string containing the name of the magic function to call and any |
|
582 | A string containing the name of the magic function to call and any | |
583 | additional arguments to be passed to the magic. |
|
583 | additional arguments to be passed to the magic. | |
584 |
|
584 | |||
585 | Returns |
|
585 | Returns | |
586 | ------- |
|
586 | ------- | |
587 | something : object |
|
587 | something : object | |
588 | The return value of the actual object. |
|
588 | The return value of the actual object. | |
589 | """ |
|
589 | """ | |
590 |
|
590 | |||
591 | # Taken from IPython. |
|
591 | # Taken from IPython. | |
592 | raise NotImplementedError('Not ported yet') |
|
592 | raise NotImplementedError('Not ported yet') | |
593 |
|
593 | |||
594 | args = arg_string.split(' ', 1) |
|
594 | args = arg_string.split(' ', 1) | |
595 | magic_name = args[0] |
|
595 | magic_name = args[0] | |
596 | magic_name = magic_name.lstrip(self.config.ESC_MAGIC) |
|
596 | magic_name = magic_name.lstrip(self.config.ESC_MAGIC) | |
597 |
|
597 | |||
598 | try: |
|
598 | try: | |
599 | magic_args = args[1] |
|
599 | magic_args = args[1] | |
600 | except IndexError: |
|
600 | except IndexError: | |
601 | magic_args = '' |
|
601 | magic_args = '' | |
602 | fn = getattr(self.magic, 'magic_'+magic_name, None) |
|
602 | fn = getattr(self.magic, 'magic_'+magic_name, None) | |
603 | if fn is None: |
|
603 | if fn is None: | |
604 | self.error("Magic function `%s` not found." % magic_name) |
|
604 | self.error("Magic function `%s` not found." % magic_name) | |
605 | else: |
|
605 | else: | |
606 | magic_args = self.var_expand(magic_args) |
|
606 | magic_args = self.var_expand(magic_args) | |
607 | return fn(magic_args) |
|
607 | return fn(magic_args) | |
608 |
|
608 | |||
609 |
|
609 | |||
610 | #### Private 'Interpreter' interface ####################################### |
|
610 | #### Private 'Interpreter' interface ####################################### | |
611 |
|
611 | |||
612 | def setup_message(self): |
|
612 | def setup_message(self): | |
613 | """Return a message object. |
|
613 | """Return a message object. | |
614 |
|
614 | |||
615 | This method prepares and returns a message dictionary. This dict |
|
615 | This method prepares and returns a message dictionary. This dict | |
616 | contains the various fields that are used to transfer information about |
|
616 | contains the various fields that are used to transfer information about | |
617 | execution, results, tracebacks, etc, to clients (either in or out of |
|
617 | execution, results, tracebacks, etc, to clients (either in or out of | |
618 | process ones). Because of the need to work with possibly out of |
|
618 | process ones). Because of the need to work with possibly out of | |
619 | process clients, this dict MUST contain strictly pickle-safe values. |
|
619 | process clients, this dict MUST contain strictly pickle-safe values. | |
620 | """ |
|
620 | """ | |
621 |
|
621 | |||
622 | return dict(number=self.current_cell_number) |
|
622 | return dict(number=self.current_cell_number) | |
623 |
|
623 | |||
624 | def setup_namespace(self): |
|
624 | def setup_namespace(self): | |
625 | """ Add things to the namespace. |
|
625 | """ Add things to the namespace. | |
626 | """ |
|
626 | """ | |
627 |
|
627 | |||
628 | self.user_ns.setdefault('__name__', '__main__') |
|
628 | self.user_ns.setdefault('__name__', '__main__') | |
629 | self.user_ns.setdefault('__builtins__', __builtin__) |
|
629 | self.user_ns.setdefault('__builtins__', __builtin__) | |
630 | self.user_ns['__IP'] = self |
|
630 | self.user_ns['__IP'] = self | |
631 | if self.raw_input_builtin is not None: |
|
631 | if self.raw_input_builtin is not None: | |
632 | self.user_ns['raw_input'] = self.raw_input_builtin |
|
632 | self.user_ns['raw_input'] = self.raw_input_builtin | |
633 | if self.input_builtin is not None: |
|
633 | if self.input_builtin is not None: | |
634 | self.user_ns['input'] = self.input_builtin |
|
634 | self.user_ns['input'] = self.input_builtin | |
635 |
|
635 | |||
636 | builtin_additions = dict( |
|
636 | builtin_additions = dict( | |
637 | ipmagic=self.ipmagic, |
|
637 | ipmagic=self.ipmagic, | |
638 | ) |
|
638 | ) | |
639 | __builtin__.__dict__.update(builtin_additions) |
|
639 | __builtin__.__dict__.update(builtin_additions) | |
640 |
|
640 | |||
641 | if self.history is not None: |
|
641 | if self.history is not None: | |
642 | self.history.setup_namespace(self.user_ns) |
|
642 | self.history.setup_namespace(self.user_ns) | |
643 |
|
643 | |||
644 | def set_traps(self): |
|
644 | def set_traps(self): | |
645 | """ Set all of the output, display, and traceback traps. |
|
645 | """ Set all of the output, display, and traceback traps. | |
646 | """ |
|
646 | """ | |
647 |
|
647 | |||
648 | self.output_trap.set() |
|
648 | self.output_trap.set() | |
649 | self.display_trap.set() |
|
649 | self.display_trap.set() | |
650 | self.traceback_trap.set() |
|
650 | self.traceback_trap.set() | |
651 |
|
651 | |||
652 | def unset_traps(self): |
|
652 | def unset_traps(self): | |
653 | """ Unset all of the output, display, and traceback traps. |
|
653 | """ Unset all of the output, display, and traceback traps. | |
654 | """ |
|
654 | """ | |
655 |
|
655 | |||
656 | self.output_trap.unset() |
|
656 | self.output_trap.unset() | |
657 | self.display_trap.unset() |
|
657 | self.display_trap.unset() | |
658 | self.traceback_trap.unset() |
|
658 | self.traceback_trap.unset() | |
659 |
|
659 | |||
660 | def split_commands(self, python): |
|
660 | def split_commands(self, python): | |
661 | """ Split multiple lines of code into discrete commands that can be |
|
661 | """ Split multiple lines of code into discrete commands that can be | |
662 | executed singly. |
|
662 | executed singly. | |
663 |
|
663 | |||
664 | Parameters |
|
664 | Parameters | |
665 | ---------- |
|
665 | ---------- | |
666 | python : str |
|
666 | python : str | |
667 | Pure, exec'able Python code. |
|
667 | Pure, exec'able Python code. | |
668 |
|
668 | |||
669 | Returns |
|
669 | Returns | |
670 | ------- |
|
670 | ------- | |
671 | commands : list of str |
|
671 | commands : list of str | |
672 | Separate commands that can be exec'ed independently. |
|
672 | Separate commands that can be exec'ed independently. | |
673 | """ |
|
673 | """ | |
674 |
|
674 | |||
675 | # compiler.parse treats trailing spaces after a newline as a |
|
675 | # compiler.parse treats trailing spaces after a newline as a | |
676 | # SyntaxError. This is different than codeop.CommandCompiler, which |
|
676 | # SyntaxError. This is different than codeop.CommandCompiler, which | |
677 | # will compile the trailng spaces just fine. We simply strip any |
|
677 | # will compile the trailng spaces just fine. We simply strip any | |
678 | # trailing whitespace off. Passing a string with trailing whitespace |
|
678 | # trailing whitespace off. Passing a string with trailing whitespace | |
679 | # to exec will fail however. There seems to be some inconsistency in |
|
679 | # to exec will fail however. There seems to be some inconsistency in | |
680 | # how trailing whitespace is handled, but this seems to work. |
|
680 | # how trailing whitespace is handled, but this seems to work. | |
681 | python = python.strip() |
|
681 | python = python.strip() | |
682 |
|
682 | |||
683 | # The compiler module does not like unicode. We need to convert |
|
683 | # The compiler module does not like unicode. We need to convert | |
684 | # it encode it: |
|
684 | # it encode it: | |
685 | if isinstance(python, unicode): |
|
685 | if isinstance(python, unicode): | |
686 | # Use the utf-8-sig BOM so the compiler detects this a UTF-8 |
|
686 | # Use the utf-8-sig BOM so the compiler detects this a UTF-8 | |
687 | # encode string. |
|
687 | # encode string. | |
688 | python = '\xef\xbb\xbf' + python.encode('utf-8') |
|
688 | python = '\xef\xbb\xbf' + python.encode('utf-8') | |
689 |
|
689 | |||
690 | # The compiler module will parse the code into an abstract syntax tree. |
|
690 | # The compiler module will parse the code into an abstract syntax tree. | |
691 | # This has a bug with str("a\nb"), but not str("""a\nb""")!!! |
|
691 | # This has a bug with str("a\nb"), but not str("""a\nb""")!!! | |
692 | ast = compiler.parse(python) |
|
692 | ast = compiler.parse(python) | |
693 |
|
693 | |||
694 | # Uncomment to help debug the ast tree |
|
694 | # Uncomment to help debug the ast tree | |
695 | # for n in ast.node: |
|
695 | # for n in ast.node: | |
696 | # print n.lineno,'->',n |
|
696 | # print n.lineno,'->',n | |
697 |
|
697 | |||
698 | # Each separate command is available by iterating over ast.node. The |
|
698 | # Each separate command is available by iterating over ast.node. The | |
699 | # lineno attribute is the line number (1-indexed) beginning the commands |
|
699 | # lineno attribute is the line number (1-indexed) beginning the commands | |
700 | # suite. |
|
700 | # suite. | |
701 | # lines ending with ";" yield a Discard Node that doesn't have a lineno |
|
701 | # lines ending with ";" yield a Discard Node that doesn't have a lineno | |
702 | # attribute. These nodes can and should be discarded. But there are |
|
702 | # attribute. These nodes can and should be discarded. But there are | |
703 | # other situations that cause Discard nodes that shouldn't be discarded. |
|
703 | # other situations that cause Discard nodes that shouldn't be discarded. | |
704 | # We might eventually discover other cases where lineno is None and have |
|
704 | # We might eventually discover other cases where lineno is None and have | |
705 | # to put in a more sophisticated test. |
|
705 | # to put in a more sophisticated test. | |
706 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] |
|
706 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] | |
707 |
|
707 | |||
708 | # When we finally get the slices, we will need to slice all the way to |
|
708 | # When we finally get the slices, we will need to slice all the way to | |
709 | # the end even though we don't have a line number for it. Fortunately, |
|
709 | # the end even though we don't have a line number for it. Fortunately, | |
710 | # None does the job nicely. |
|
710 | # None does the job nicely. | |
711 | linenos.append(None) |
|
711 | linenos.append(None) | |
712 |
|
712 | |||
713 | # Same problem at the other end: sometimes the ast tree has its |
|
713 | # Same problem at the other end: sometimes the ast tree has its | |
714 | # first complete statement not starting on line 0. In this case |
|
714 | # first complete statement not starting on line 0. In this case | |
715 | # we might miss part of it. This fixes ticket 266993. Thanks Gael! |
|
715 | # we might miss part of it. This fixes ticket 266993. Thanks Gael! | |
716 | linenos[0] = 0 |
|
716 | linenos[0] = 0 | |
717 |
|
717 | |||
718 | lines = python.splitlines() |
|
718 | lines = python.splitlines() | |
719 |
|
719 | |||
720 | # Create a list of atomic commands. |
|
720 | # Create a list of atomic commands. | |
721 | cmds = [] |
|
721 | cmds = [] | |
722 | for i, j in zip(linenos[:-1], linenos[1:]): |
|
722 | for i, j in zip(linenos[:-1], linenos[1:]): | |
723 | cmd = lines[i:j] |
|
723 | cmd = lines[i:j] | |
724 | if cmd: |
|
724 | if cmd: | |
725 | cmds.append('\n'.join(cmd)+'\n') |
|
725 | cmds.append('\n'.join(cmd)+'\n') | |
726 |
|
726 | |||
727 | return cmds |
|
727 | return cmds | |
728 |
|
728 | |||
729 | def error(self, text): |
|
729 | def error(self, text): | |
730 | """ Pass an error message back to the shell. |
|
730 | """ Pass an error message back to the shell. | |
731 |
|
731 | |||
732 | Notes |
|
732 | Notes | |
733 | ----- |
|
733 | ----- | |
734 | This should only be called when self.message is set. In other words, |
|
734 | This should only be called when self.message is set. In other words, | |
735 | when code is being executed. |
|
735 | when code is being executed. | |
736 |
|
736 | |||
737 | Parameters |
|
737 | Parameters | |
738 | ---------- |
|
738 | ---------- | |
739 | text : str |
|
739 | text : str | |
740 | """ |
|
740 | """ | |
741 |
|
741 | |||
742 | errors = self.message.get('IPYTHON_ERROR', []) |
|
742 | errors = self.message.get('IPYTHON_ERROR', []) | |
743 | errors.append(text) |
|
743 | errors.append(text) | |
744 |
|
744 | |||
745 | def var_expand(self, template): |
|
745 | def var_expand(self, template): | |
746 | """ Expand $variables in the current namespace using Itpl. |
|
746 | """ Expand $variables in the current namespace using Itpl. | |
747 |
|
747 | |||
748 | Parameters |
|
748 | Parameters | |
749 | ---------- |
|
749 | ---------- | |
750 | template : str |
|
750 | template : str | |
751 | """ |
|
751 | """ | |
752 |
|
752 | |||
753 | return str(ItplNS(template, self.user_ns)) |
|
753 | return str(ItplNS(template, self.user_ns)) | |
754 |
|
754 | |||
755 | def _possible_macro(self, obj): |
|
755 | def _possible_macro(self, obj): | |
756 | """ If the object is a macro, execute it. |
|
756 | """ If the object is a macro, execute it. | |
757 | """ |
|
757 | """ | |
758 |
|
758 | |||
759 | if isinstance(obj, Macro): |
|
759 | if isinstance(obj, Macro): | |
760 | self.execute_macro(obj) |
|
760 | self.execute_macro(obj) | |
761 |
|
761 |
General Comments 0
You need to be logged in to leave comments.
Login now