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