##// END OF EJS Templates
Add experimental support for cell-based execution....
Fernando Perez -
Show More
@@ -1,868 +1,954
1 1 """Analysis of text input into executable blocks.
2 2
3 3 The main class in this module, :class:`InputSplitter`, is designed to break
4 4 input from either interactive, line-by-line environments or block-based ones,
5 5 into standalone blocks that can be executed by Python as 'single' statements
6 6 (thus triggering sys.displayhook).
7 7
8 8 A companion, :class:`IPythonInputSplitter`, provides the same functionality but
9 9 with full support for the extended IPython syntax (magics, system calls, etc).
10 10
11 11 For more details, see the class docstring below.
12 12
13 13 Syntax Transformations
14 14 ----------------------
15 15
16 16 One of the main jobs of the code in this file is to apply all syntax
17 17 transformations that make up 'the IPython language', i.e. magics, shell
18 18 escapes, etc. All transformations should be implemented as *fully stateless*
19 19 entities, that simply take one line as their input and return a line.
20 20 Internally for implementation purposes they may be a normal function or a
21 21 callable object, but the only input they receive will be a single line and they
22 22 should only return a line, without holding any data-dependent state between
23 23 calls.
24 24
25 25 As an example, the EscapedTransformer is a class so we can more clearly group
26 26 together the functionality of dispatching to individual functions based on the
27 27 starting escape character, but the only method for public use is its call
28 28 method.
29 29
30 30
31 31 ToDo
32 32 ----
33 33
34 34 - Should we make push() actually raise an exception once push_accepts_more()
35 35 returns False?
36 36
37 37 - Naming cleanups. The tr_* names aren't the most elegant, though now they are
38 38 at least just attributes of a class so not really very exposed.
39 39
40 40 - Think about the best way to support dynamic things: automagic, autocall,
41 41 macros, etc.
42 42
43 43 - Think of a better heuristic for the application of the transforms in
44 44 IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea:
45 45 track indentation change events (indent, dedent, nothing) and apply them only
46 46 if the indentation went up, but not otherwise.
47 47
48 48 - Think of the cleanest way for supporting user-specified transformations (the
49 49 user prefilters we had before).
50 50
51 51 Authors
52 52 -------
53 53
54 54 * Fernando Perez
55 55 * Brian Granger
56 56 """
57 57 #-----------------------------------------------------------------------------
58 58 # Copyright (C) 2010 The IPython Development Team
59 59 #
60 60 # Distributed under the terms of the BSD License. The full license is in
61 61 # the file COPYING, distributed as part of this software.
62 62 #-----------------------------------------------------------------------------
63 63
64 64 #-----------------------------------------------------------------------------
65 65 # Imports
66 66 #-----------------------------------------------------------------------------
67 67 # stdlib
68 68 import codeop
69 69 import re
70 70 import sys
71 71
72 72 # IPython modules
73 73 from IPython.utils.text import make_quoted_expr
74 74 #-----------------------------------------------------------------------------
75 75 # Globals
76 76 #-----------------------------------------------------------------------------
77 77
78 78 # The escape sequences that define the syntax transformations IPython will
79 79 # apply to user input. These can NOT be just changed here: many regular
80 80 # expressions and other parts of the code may use their hardcoded values, and
81 81 # for all intents and purposes they constitute the 'IPython syntax', so they
82 82 # should be considered fixed.
83 83
84 84 ESC_SHELL = '!'
85 85 ESC_SH_CAP = '!!'
86 86 ESC_HELP = '?'
87 87 ESC_HELP2 = '??'
88 88 ESC_MAGIC = '%'
89 89 ESC_QUOTE = ','
90 90 ESC_QUOTE2 = ';'
91 91 ESC_PAREN = '/'
92 92
93 93 #-----------------------------------------------------------------------------
94 94 # Utilities
95 95 #-----------------------------------------------------------------------------
96 96
97 97 # FIXME: These are general-purpose utilities that later can be moved to the
98 98 # general ward. Kept here for now because we're being very strict about test
99 99 # coverage with this code, and this lets us ensure that we keep 100% coverage
100 100 # while developing.
101 101
102 102 # compiled regexps for autoindent management
103 103 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
104 104 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
105 105
106 106
107 107 def num_ini_spaces(s):
108 108 """Return the number of initial spaces in a string.
109 109
110 110 Note that tabs are counted as a single space. For now, we do *not* support
111 111 mixing of tabs and spaces in the user's input.
112 112
113 113 Parameters
114 114 ----------
115 115 s : string
116 116
117 117 Returns
118 118 -------
119 119 n : int
120 120 """
121 121
122 122 ini_spaces = ini_spaces_re.match(s)
123 123 if ini_spaces:
124 124 return ini_spaces.end()
125 125 else:
126 126 return 0
127 127
128 128
129 129 def remove_comments(src):
130 130 """Remove all comments from input source.
131 131
132 132 Note: comments are NOT recognized inside of strings!
133 133
134 134 Parameters
135 135 ----------
136 136 src : string
137 137 A single or multiline input string.
138 138
139 139 Returns
140 140 -------
141 141 String with all Python comments removed.
142 142 """
143 143
144 144 return re.sub('#.*', '', src)
145 145
146 146
147 147 def get_input_encoding():
148 148 """Return the default standard input encoding.
149 149
150 150 If sys.stdin has no encoding, 'ascii' is returned."""
151 151 # There are strange environments for which sys.stdin.encoding is None. We
152 152 # ensure that a valid encoding is returned.
153 153 encoding = getattr(sys.stdin, 'encoding', None)
154 154 if encoding is None:
155 155 encoding = 'ascii'
156 156 return encoding
157 157
158 158 #-----------------------------------------------------------------------------
159 159 # Classes and functions for normal Python syntax handling
160 160 #-----------------------------------------------------------------------------
161 161
162 # HACK! This implementation, written by Robert K a while ago using the
163 # compiler module, is more robust than the other one below, but it expects its
164 # input to be pure python (no ipython syntax). For now we're using it as a
165 # second-pass splitter after the first pass transforms the input to pure
166 # python.
167
168 def split_blocks(python):
169 """ Split multiple lines of code into discrete commands that can be
170 executed singly.
171
172 Parameters
173 ----------
174 python : str
175 Pure, exec'able Python code.
176
177 Returns
178 -------
179 commands : list of str
180 Separate commands that can be exec'ed independently.
181 """
182
183 import compiler
184
185 # compiler.parse treats trailing spaces after a newline as a
186 # SyntaxError. This is different than codeop.CommandCompiler, which
187 # will compile the trailng spaces just fine. We simply strip any
188 # trailing whitespace off. Passing a string with trailing whitespace
189 # to exec will fail however. There seems to be some inconsistency in
190 # how trailing whitespace is handled, but this seems to work.
191 python_ori = python # save original in case we bail on error
192 python = python.strip()
193
194 # The compiler module does not like unicode. We need to convert
195 # it encode it:
196 if isinstance(python, unicode):
197 # Use the utf-8-sig BOM so the compiler detects this a UTF-8
198 # encode string.
199 python = '\xef\xbb\xbf' + python.encode('utf-8')
200
201 # The compiler module will parse the code into an abstract syntax tree.
202 # This has a bug with str("a\nb"), but not str("""a\nb""")!!!
203 try:
204 ast = compiler.parse(python)
205 except:
206 return [python_ori]
207
208 # Uncomment to help debug the ast tree
209 # for n in ast.node:
210 # print n.lineno,'->',n
211
212 # Each separate command is available by iterating over ast.node. The
213 # lineno attribute is the line number (1-indexed) beginning the commands
214 # suite.
215 # lines ending with ";" yield a Discard Node that doesn't have a lineno
216 # attribute. These nodes can and should be discarded. But there are
217 # other situations that cause Discard nodes that shouldn't be discarded.
218 # We might eventually discover other cases where lineno is None and have
219 # to put in a more sophisticated test.
220 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
221
222 # When we finally get the slices, we will need to slice all the way to
223 # the end even though we don't have a line number for it. Fortunately,
224 # None does the job nicely.
225 linenos.append(None)
226
227 # Same problem at the other end: sometimes the ast tree has its
228 # first complete statement not starting on line 0. In this case
229 # we might miss part of it. This fixes ticket 266993. Thanks Gael!
230 linenos[0] = 0
231
232 lines = python.splitlines()
233
234 # Create a list of atomic commands.
235 cmds = []
236 for i, j in zip(linenos[:-1], linenos[1:]):
237 cmd = lines[i:j]
238 if cmd:
239 cmds.append('\n'.join(cmd)+'\n')
240
241 return cmds
242
243
162 244 class InputSplitter(object):
163 245 """An object that can split Python source input in executable blocks.
164 246
165 247 This object is designed to be used in one of two basic modes:
166 248
167 249 1. By feeding it python source line-by-line, using :meth:`push`. In this
168 250 mode, it will return on each push whether the currently pushed code
169 251 could be executed already. In addition, it provides a method called
170 252 :meth:`push_accepts_more` that can be used to query whether more input
171 253 can be pushed into a single interactive block.
172 254
173 255 2. By calling :meth:`split_blocks` with a single, multiline Python string,
174 256 that is then split into blocks each of which can be executed
175 257 interactively as a single statement.
176 258
177 259 This is a simple example of how an interactive terminal-based client can use
178 260 this tool::
179 261
180 262 isp = InputSplitter()
181 263 while isp.push_accepts_more():
182 264 indent = ' '*isp.indent_spaces
183 265 prompt = '>>> ' + indent
184 266 line = indent + raw_input(prompt)
185 267 isp.push(line)
186 268 print 'Input source was:\n', isp.source_reset(),
187 269 """
188 270 # Number of spaces of indentation computed from input that has been pushed
189 271 # so far. This is the attributes callers should query to get the current
190 272 # indentation level, in order to provide auto-indent facilities.
191 273 indent_spaces = 0
192 274 # String, indicating the default input encoding. It is computed by default
193 275 # at initialization time via get_input_encoding(), but it can be reset by a
194 276 # client with specific knowledge of the encoding.
195 277 encoding = ''
196 278 # String where the current full source input is stored, properly encoded.
197 279 # Reading this attribute is the normal way of querying the currently pushed
198 280 # source code, that has been properly encoded.
199 281 source = ''
200 282 # Code object corresponding to the current source. It is automatically
201 283 # synced to the source, so it can be queried at any time to obtain the code
202 284 # object; it will be None if the source doesn't compile to valid Python.
203 285 code = None
204 286 # Input mode
205 287 input_mode = 'line'
206 288
207 289 # Private attributes
208 290
209 291 # List with lines of input accumulated so far
210 292 _buffer = None
211 293 # Command compiler
212 294 _compile = None
213 295 # Mark when input has changed indentation all the way back to flush-left
214 296 _full_dedent = False
215 297 # Boolean indicating whether the current block is complete
216 298 _is_complete = None
217 299
218 300 def __init__(self, input_mode=None):
219 301 """Create a new InputSplitter instance.
220 302
221 303 Parameters
222 304 ----------
223 305 input_mode : str
224 306
225 307 One of ['line', 'block']; default is 'line'.
226 308
227 309 The input_mode parameter controls how new inputs are used when fed via
228 310 the :meth:`push` method:
229 311
230 312 - 'line': meant for line-oriented clients, inputs are appended one at a
231 313 time to the internal buffer and the whole buffer is compiled.
232 314
233 315 - 'block': meant for clients that can edit multi-line blocks of text at
234 316 a time. Each new input new input completely replaces all prior
235 317 inputs. Block mode is thus equivalent to prepending a full reset()
236 318 to every push() call.
237 319 """
238 320 self._buffer = []
239 321 self._compile = codeop.CommandCompiler()
240 322 self.encoding = get_input_encoding()
241 323 self.input_mode = InputSplitter.input_mode if input_mode is None \
242 324 else input_mode
243 325
244 326 def reset(self):
245 327 """Reset the input buffer and associated state."""
246 328 self.indent_spaces = 0
247 329 self._buffer[:] = []
248 330 self.source = ''
249 331 self.code = None
250 332 self._is_complete = False
251 333 self._full_dedent = False
252 334
253 335 def source_reset(self):
254 336 """Return the input source and perform a full reset.
255 337 """
256 338 out = self.source
257 339 self.reset()
258 340 return out
259 341
260 342 def push(self, lines):
261 343 """Push one ore more lines of input.
262 344
263 345 This stores the given lines and returns a status code indicating
264 346 whether the code forms a complete Python block or not.
265 347
266 348 Any exceptions generated in compilation are swallowed, but if an
267 349 exception was produced, the method returns True.
268 350
269 351 Parameters
270 352 ----------
271 353 lines : string
272 354 One or more lines of Python input.
273 355
274 356 Returns
275 357 -------
276 358 is_complete : boolean
277 359 True if the current input source (the result of the current input
278 360 plus prior inputs) forms a complete Python execution block. Note that
279 361 this value is also stored as a private attribute (_is_complete), so it
280 362 can be queried at any time.
281 363 """
282 364 if self.input_mode == 'block':
283 365 self.reset()
284 366
285 367 # If the source code has leading blanks, add 'if 1:\n' to it
286 368 # this allows execution of indented pasted code. It is tempting
287 369 # to add '\n' at the end of source to run commands like ' a=1'
288 370 # directly, but this fails for more complicated scenarios
289 371 if not self._buffer and lines[:1] in [' ', '\t']:
290 372 lines = 'if 1:\n%s' % lines
291 373
292 374 self._store(lines)
293 375 source = self.source
294 376
295 377 # Before calling _compile(), reset the code object to None so that if an
296 378 # exception is raised in compilation, we don't mislead by having
297 379 # inconsistent code/source attributes.
298 380 self.code, self._is_complete = None, None
299 381
300 382 self._update_indent(lines)
301 383 try:
302 384 self.code = self._compile(source)
303 385 # Invalid syntax can produce any of a number of different errors from
304 386 # inside the compiler, so we have to catch them all. Syntax errors
305 387 # immediately produce a 'ready' block, so the invalid Python can be
306 388 # sent to the kernel for evaluation with possible ipython
307 389 # special-syntax conversion.
308 390 except (SyntaxError, OverflowError, ValueError, TypeError,
309 391 MemoryError):
310 392 self._is_complete = True
311 393 else:
312 394 # Compilation didn't produce any exceptions (though it may not have
313 395 # given a complete code object)
314 396 self._is_complete = self.code is not None
315 397
316 398 return self._is_complete
317 399
318 400 def push_accepts_more(self):
319 401 """Return whether a block of interactive input can accept more input.
320 402
321 403 This method is meant to be used by line-oriented frontends, who need to
322 404 guess whether a block is complete or not based solely on prior and
323 405 current input lines. The InputSplitter considers it has a complete
324 406 interactive block and will not accept more input only when either a
325 407 SyntaxError is raised, or *all* of the following are true:
326 408
327 409 1. The input compiles to a complete statement.
328 410
329 411 2. The indentation level is flush-left (because if we are indented,
330 412 like inside a function definition or for loop, we need to keep
331 413 reading new input).
332 414
333 415 3. There is one extra line consisting only of whitespace.
334 416
335 417 Because of condition #3, this method should be used only by
336 418 *line-oriented* frontends, since it means that intermediate blank lines
337 419 are not allowed in function definitions (or any other indented block).
338 420
339 421 Block-oriented frontends that have a separate keyboard event to
340 422 indicate execution should use the :meth:`split_blocks` method instead.
341 423
342 424 If the current input produces a syntax error, this method immediately
343 425 returns False but does *not* raise the syntax error exception, as
344 426 typically clients will want to send invalid syntax to an execution
345 427 backend which might convert the invalid syntax into valid Python via
346 428 one of the dynamic IPython mechanisms.
347 429 """
348 430
349 431 if not self._is_complete:
350 432 return True
351 433
352 434 if self.indent_spaces==0:
353 435 return False
354 436
355 437 last_line = self.source.splitlines()[-1]
356 438 return bool(last_line and not last_line.isspace())
357 439
358 440 def split_blocks(self, lines):
359 441 """Split a multiline string into multiple input blocks.
360 442
361 443 Note: this method starts by performing a full reset().
362 444
363 445 Parameters
364 446 ----------
365 447 lines : str
366 448 A possibly multiline string.
367 449
368 450 Returns
369 451 -------
370 452 blocks : list
371 453 A list of strings, each possibly multiline. Each string corresponds
372 454 to a single block that can be compiled in 'single' mode (unless it
373 455 has a syntax error)."""
374 456
375 457 # This code is fairly delicate. If you make any changes here, make
376 458 # absolutely sure that you do run the full test suite and ALL tests
377 459 # pass.
378 460
379 461 self.reset()
380 462 blocks = []
381 463
382 464 # Reversed copy so we can use pop() efficiently and consume the input
383 465 # as a stack
384 466 lines = lines.splitlines()[::-1]
385 467 # Outer loop over all input
386 468 while lines:
387 469 #print 'Current lines:', lines # dbg
388 470 # Inner loop to build each block
389 471 while True:
390 472 # Safety exit from inner loop
391 473 if not lines:
392 474 break
393 475 # Grab next line but don't push it yet
394 476 next_line = lines.pop()
395 477 # Blank/empty lines are pushed as-is
396 478 if not next_line or next_line.isspace():
397 479 self.push(next_line)
398 480 continue
399 481
400 482 # Check indentation changes caused by the *next* line
401 483 indent_spaces, _full_dedent = self._find_indent(next_line)
402 484
403 485 # If the next line causes a dedent, it can be for two differnt
404 486 # reasons: either an explicit de-dent by the user or a
405 487 # return/raise/pass statement. These MUST be handled
406 488 # separately:
407 489 #
408 490 # 1. the first case is only detected when the actual explicit
409 491 # dedent happens, and that would be the *first* line of a *new*
410 492 # block. Thus, we must put the line back into the input buffer
411 493 # so that it starts a new block on the next pass.
412 494 #
413 495 # 2. the second case is detected in the line before the actual
414 496 # dedent happens, so , we consume the line and we can break out
415 497 # to start a new block.
416 498
417 499 # Case 1, explicit dedent causes a break.
418 500 # Note: check that we weren't on the very last line, else we'll
419 501 # enter an infinite loop adding/removing the last line.
420 502 if _full_dedent and lines and not next_line.startswith(' '):
421 503 lines.append(next_line)
422 504 break
423 505
424 506 # Otherwise any line is pushed
425 507 self.push(next_line)
426 508
427 509 # Case 2, full dedent with full block ready:
428 510 if _full_dedent or \
429 511 self.indent_spaces==0 and not self.push_accepts_more():
430 512 break
431 513 # Form the new block with the current source input
432 514 blocks.append(self.source_reset())
433 515
434 return blocks
516 #return blocks
517 # HACK!!! Now that our input is in blocks but guaranteed to be pure
518 # python syntax, feed it back a second time through the AST-based
519 # splitter, which is more accurate than ours.
520 return split_blocks(''.join(blocks))
435 521
436 522 #------------------------------------------------------------------------
437 523 # Private interface
438 524 #------------------------------------------------------------------------
439 525
440 526 def _find_indent(self, line):
441 527 """Compute the new indentation level for a single line.
442 528
443 529 Parameters
444 530 ----------
445 531 line : str
446 532 A single new line of non-whitespace, non-comment Python input.
447 533
448 534 Returns
449 535 -------
450 536 indent_spaces : int
451 537 New value for the indent level (it may be equal to self.indent_spaces
452 538 if indentation doesn't change.
453 539
454 540 full_dedent : boolean
455 541 Whether the new line causes a full flush-left dedent.
456 542 """
457 543 indent_spaces = self.indent_spaces
458 544 full_dedent = self._full_dedent
459 545
460 546 inisp = num_ini_spaces(line)
461 547 if inisp < indent_spaces:
462 548 indent_spaces = inisp
463 549 if indent_spaces <= 0:
464 550 #print 'Full dedent in text',self.source # dbg
465 551 full_dedent = True
466 552
467 553 if line[-1] == ':':
468 554 indent_spaces += 4
469 555 elif dedent_re.match(line):
470 556 indent_spaces -= 4
471 557 if indent_spaces <= 0:
472 558 full_dedent = True
473 559
474 560 # Safety
475 561 if indent_spaces < 0:
476 562 indent_spaces = 0
477 563 #print 'safety' # dbg
478 564
479 565 return indent_spaces, full_dedent
480 566
481 567 def _update_indent(self, lines):
482 568 for line in remove_comments(lines).splitlines():
483 569 if line and not line.isspace():
484 570 self.indent_spaces, self._full_dedent = self._find_indent(line)
485 571
486 572 def _store(self, lines):
487 573 """Store one or more lines of input.
488 574
489 575 If input lines are not newline-terminated, a newline is automatically
490 576 appended."""
491 577
492 578 if lines.endswith('\n'):
493 579 self._buffer.append(lines)
494 580 else:
495 581 self._buffer.append(lines+'\n')
496 582 self._set_source()
497 583
498 584 def _set_source(self):
499 585 self.source = ''.join(self._buffer).encode(self.encoding)
500 586
501 587
502 588 #-----------------------------------------------------------------------------
503 589 # Functions and classes for IPython-specific syntactic support
504 590 #-----------------------------------------------------------------------------
505 591
506 592 # RegExp for splitting line contents into pre-char//first word-method//rest.
507 593 # For clarity, each group in on one line.
508 594
509 595 line_split = re.compile("""
510 596 ^(\s*) # any leading space
511 597 ([,;/%]|!!?|\?\??) # escape character or characters
512 598 \s*(%?[\w\.]*) # function/method, possibly with leading %
513 599 # to correctly treat things like '?%magic'
514 600 (\s+.*$|$) # rest of line
515 601 """, re.VERBOSE)
516 602
517 603
518 604 def split_user_input(line):
519 605 """Split user input into early whitespace, esc-char, function part and rest.
520 606
521 607 This is currently handles lines with '=' in them in a very inconsistent
522 608 manner.
523 609
524 610 Examples
525 611 ========
526 612 >>> split_user_input('x=1')
527 613 ('', '', 'x=1', '')
528 614 >>> split_user_input('?')
529 615 ('', '?', '', '')
530 616 >>> split_user_input('??')
531 617 ('', '??', '', '')
532 618 >>> split_user_input(' ?')
533 619 (' ', '?', '', '')
534 620 >>> split_user_input(' ??')
535 621 (' ', '??', '', '')
536 622 >>> split_user_input('??x')
537 623 ('', '??', 'x', '')
538 624 >>> split_user_input('?x=1')
539 625 ('', '', '?x=1', '')
540 626 >>> split_user_input('!ls')
541 627 ('', '!', 'ls', '')
542 628 >>> split_user_input(' !ls')
543 629 (' ', '!', 'ls', '')
544 630 >>> split_user_input('!!ls')
545 631 ('', '!!', 'ls', '')
546 632 >>> split_user_input(' !!ls')
547 633 (' ', '!!', 'ls', '')
548 634 >>> split_user_input(',ls')
549 635 ('', ',', 'ls', '')
550 636 >>> split_user_input(';ls')
551 637 ('', ';', 'ls', '')
552 638 >>> split_user_input(' ;ls')
553 639 (' ', ';', 'ls', '')
554 640 >>> split_user_input('f.g(x)')
555 641 ('', '', 'f.g(x)', '')
556 642 >>> split_user_input('f.g (x)')
557 643 ('', '', 'f.g', '(x)')
558 644 >>> split_user_input('?%hist')
559 645 ('', '?', '%hist', '')
560 646 """
561 647 match = line_split.match(line)
562 648 if match:
563 649 lspace, esc, fpart, rest = match.groups()
564 650 else:
565 651 # print "match failed for line '%s'" % line
566 652 try:
567 653 fpart, rest = line.split(None, 1)
568 654 except ValueError:
569 655 # print "split failed for line '%s'" % line
570 656 fpart, rest = line,''
571 657 lspace = re.match('^(\s*)(.*)', line).groups()[0]
572 658 esc = ''
573 659
574 660 # fpart has to be a valid python identifier, so it better be only pure
575 661 # ascii, no unicode:
576 662 try:
577 663 fpart = fpart.encode('ascii')
578 664 except UnicodeEncodeError:
579 665 lspace = unicode(lspace)
580 666 rest = fpart + u' ' + rest
581 667 fpart = u''
582 668
583 669 #print 'line:<%s>' % line # dbg
584 670 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
585 671 return lspace, esc, fpart.strip(), rest.lstrip()
586 672
587 673
588 674 # The escaped translators ALL receive a line where their own escape has been
589 675 # stripped. Only '?' is valid at the end of the line, all others can only be
590 676 # placed at the start.
591 677
592 678 class LineInfo(object):
593 679 """A single line of input and associated info.
594 680
595 681 This is a utility class that mostly wraps the output of
596 682 :func:`split_user_input` into a convenient object to be passed around
597 683 during input transformations.
598 684
599 685 Includes the following as properties:
600 686
601 687 line
602 688 The original, raw line
603 689
604 690 lspace
605 691 Any early whitespace before actual text starts.
606 692
607 693 esc
608 694 The initial esc character (or characters, for double-char escapes like
609 695 '??' or '!!').
610 696
611 697 fpart
612 698 The 'function part', which is basically the maximal initial sequence
613 699 of valid python identifiers and the '.' character. This is what is
614 700 checked for alias and magic transformations, used for auto-calling,
615 701 etc.
616 702
617 703 rest
618 704 Everything else on the line.
619 705 """
620 706 def __init__(self, line):
621 707 self.line = line
622 708 self.lspace, self.esc, self.fpart, self.rest = \
623 709 split_user_input(line)
624 710
625 711 def __str__(self):
626 712 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
627 713 self.fpart, self.rest)
628 714
629 715
630 716 # Transformations of the special syntaxes that don't rely on an explicit escape
631 717 # character but instead on patterns on the input line
632 718
633 719 # The core transformations are implemented as standalone functions that can be
634 720 # tested and validated in isolation. Each of these uses a regexp, we
635 721 # pre-compile these and keep them close to each function definition for clarity
636 722
637 723 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
638 724 r'\s*=\s*!\s*(?P<cmd>.*)')
639 725
640 726 def transform_assign_system(line):
641 727 """Handle the `files = !ls` syntax."""
642 728 # FIXME: This transforms the line to use %sc, but we've listed that magic
643 729 # as deprecated. We should then implement this functionality in a
644 730 # standalone api that we can transform to, without going through a
645 731 # deprecated magic.
646 732 m = _assign_system_re.match(line)
647 733 if m is not None:
648 734 cmd = m.group('cmd')
649 735 lhs = m.group('lhs')
650 736 expr = make_quoted_expr("sc -l = %s" % cmd)
651 737 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
652 738 return new_line
653 739 return line
654 740
655 741
656 742 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
657 743 r'\s*=\s*%\s*(?P<cmd>.*)')
658 744
659 745 def transform_assign_magic(line):
660 746 """Handle the `a = %who` syntax."""
661 747 m = _assign_magic_re.match(line)
662 748 if m is not None:
663 749 cmd = m.group('cmd')
664 750 lhs = m.group('lhs')
665 751 expr = make_quoted_expr(cmd)
666 752 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
667 753 return new_line
668 754 return line
669 755
670 756
671 757 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
672 758
673 759 def transform_classic_prompt(line):
674 760 """Handle inputs that start with '>>> ' syntax."""
675 761
676 762 if not line or line.isspace():
677 763 return line
678 764 m = _classic_prompt_re.match(line)
679 765 if m:
680 766 return line[len(m.group(0)):]
681 767 else:
682 768 return line
683 769
684 770
685 771 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
686 772
687 773 def transform_ipy_prompt(line):
688 774 """Handle inputs that start classic IPython prompt syntax."""
689 775
690 776 if not line or line.isspace():
691 777 return line
692 778 #print 'LINE: %r' % line # dbg
693 779 m = _ipy_prompt_re.match(line)
694 780 if m:
695 781 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
696 782 return line[len(m.group(0)):]
697 783 else:
698 784 return line
699 785
700 786
701 787 class EscapedTransformer(object):
702 788 """Class to transform lines that are explicitly escaped out."""
703 789
704 790 def __init__(self):
705 791 tr = { ESC_SHELL : self._tr_system,
706 792 ESC_SH_CAP : self._tr_system2,
707 793 ESC_HELP : self._tr_help,
708 794 ESC_HELP2 : self._tr_help,
709 795 ESC_MAGIC : self._tr_magic,
710 796 ESC_QUOTE : self._tr_quote,
711 797 ESC_QUOTE2 : self._tr_quote2,
712 798 ESC_PAREN : self._tr_paren }
713 799 self.tr = tr
714 800
715 801 # Support for syntax transformations that use explicit escapes typed by the
716 802 # user at the beginning of a line
717 803 @staticmethod
718 804 def _tr_system(line_info):
719 805 "Translate lines escaped with: !"
720 806 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
721 807 return '%sget_ipython().system(%s)' % (line_info.lspace,
722 808 make_quoted_expr(cmd))
723 809
724 810 @staticmethod
725 811 def _tr_system2(line_info):
726 812 "Translate lines escaped with: !!"
727 813 cmd = line_info.line.lstrip()[2:]
728 814 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
729 815 make_quoted_expr(cmd))
730 816
731 817 @staticmethod
732 818 def _tr_help(line_info):
733 819 "Translate lines escaped with: ?/??"
734 820 # A naked help line should just fire the intro help screen
735 821 if not line_info.line[1:]:
736 822 return 'get_ipython().show_usage()'
737 823
738 824 # There may be one or two '?' at the end, move them to the front so that
739 825 # the rest of the logic can assume escapes are at the start
740 826 line = line_info.line
741 827 if line.endswith('?'):
742 828 line = line[-1] + line[:-1]
743 829 if line.endswith('?'):
744 830 line = line[-1] + line[:-1]
745 831 line_info = LineInfo(line)
746 832
747 833 # From here on, simply choose which level of detail to get.
748 834 if line_info.esc == '?':
749 835 pinfo = 'pinfo'
750 836 elif line_info.esc == '??':
751 837 pinfo = 'pinfo2'
752 838
753 839 tpl = '%sget_ipython().magic("%s %s")'
754 840 return tpl % (line_info.lspace, pinfo,
755 841 ' '.join([line_info.fpart, line_info.rest]).strip())
756 842
757 843 @staticmethod
758 844 def _tr_magic(line_info):
759 845 "Translate lines escaped with: %"
760 846 tpl = '%sget_ipython().magic(%s)'
761 847 cmd = make_quoted_expr(' '.join([line_info.fpart,
762 848 line_info.rest]).strip())
763 849 return tpl % (line_info.lspace, cmd)
764 850
765 851 @staticmethod
766 852 def _tr_quote(line_info):
767 853 "Translate lines escaped with: ,"
768 854 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
769 855 '", "'.join(line_info.rest.split()) )
770 856
771 857 @staticmethod
772 858 def _tr_quote2(line_info):
773 859 "Translate lines escaped with: ;"
774 860 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
775 861 line_info.rest)
776 862
777 863 @staticmethod
778 864 def _tr_paren(line_info):
779 865 "Translate lines escaped with: /"
780 866 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
781 867 ", ".join(line_info.rest.split()))
782 868
783 869 def __call__(self, line):
784 870 """Class to transform lines that are explicitly escaped out.
785 871
786 872 This calls the above _tr_* static methods for the actual line
787 873 translations."""
788 874
789 875 # Empty lines just get returned unmodified
790 876 if not line or line.isspace():
791 877 return line
792 878
793 879 # Get line endpoints, where the escapes can be
794 880 line_info = LineInfo(line)
795 881
796 882 # If the escape is not at the start, only '?' needs to be special-cased.
797 883 # All other escapes are only valid at the start
798 884 if not line_info.esc in self.tr:
799 885 if line.endswith(ESC_HELP):
800 886 return self._tr_help(line_info)
801 887 else:
802 888 # If we don't recognize the escape, don't modify the line
803 889 return line
804 890
805 891 return self.tr[line_info.esc](line_info)
806 892
807 893
808 894 # A function-looking object to be used by the rest of the code. The purpose of
809 895 # the class in this case is to organize related functionality, more than to
810 896 # manage state.
811 897 transform_escaped = EscapedTransformer()
812 898
813 899
814 900 class IPythonInputSplitter(InputSplitter):
815 901 """An input splitter that recognizes all of IPython's special syntax."""
816 902
817 903 def push(self, lines):
818 904 """Push one or more lines of IPython input.
819 905 """
820 906 if not lines:
821 907 return super(IPythonInputSplitter, self).push(lines)
822 908
823 909 lines_list = lines.splitlines()
824 910
825 911 transforms = [transform_escaped, transform_assign_system,
826 912 transform_assign_magic, transform_ipy_prompt,
827 913 transform_classic_prompt]
828 914
829 915 # Transform logic
830 916 #
831 917 # We only apply the line transformers to the input if we have either no
832 918 # input yet, or complete input, or if the last line of the buffer ends
833 919 # with ':' (opening an indented block). This prevents the accidental
834 920 # transformation of escapes inside multiline expressions like
835 921 # triple-quoted strings or parenthesized expressions.
836 922 #
837 923 # The last heuristic, while ugly, ensures that the first line of an
838 924 # indented block is correctly transformed.
839 925 #
840 926 # FIXME: try to find a cleaner approach for this last bit.
841 927
842 928 # If we were in 'block' mode, since we're going to pump the parent
843 929 # class by hand line by line, we need to temporarily switch out to
844 930 # 'line' mode, do a single manual reset and then feed the lines one
845 931 # by one. Note that this only matters if the input has more than one
846 932 # line.
847 933 changed_input_mode = False
848 934
849 935 if len(lines_list)>1 and self.input_mode == 'block':
850 936 self.reset()
851 937 changed_input_mode = True
852 938 saved_input_mode = 'block'
853 939 self.input_mode = 'line'
854 940
855 941 try:
856 942 push = super(IPythonInputSplitter, self).push
857 943 for line in lines_list:
858 944 if self._is_complete or not self._buffer or \
859 945 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
860 946 for f in transforms:
861 947 line = f(line)
862 948
863 949 out = push(line)
864 950 finally:
865 951 if changed_input_mode:
866 952 self.input_mode = saved_input_mode
867 953
868 954 return out
@@ -1,2403 +1,2449
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.display_trap import DisplayTrap
44 44 from IPython.core.displayhook import DisplayHook
45 45 from IPython.core.error import TryNext, UsageError
46 46 from IPython.core.extensions import ExtensionManager
47 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 48 from IPython.core.inputlist import InputList
49 from IPython.core.inputsplitter import IPythonInputSplitter
49 50 from IPython.core.logger import Logger
50 51 from IPython.core.magic import Magic
51 52 from IPython.core.payload import PayloadManager
52 53 from IPython.core.plugin import PluginManager
53 54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 55 from IPython.external.Itpl import ItplNS
55 56 from IPython.utils import PyColorize
56 57 from IPython.utils import io
57 58 from IPython.utils import pickleshare
58 59 from IPython.utils.doctestreload import doctest_reload
59 60 from IPython.utils.io import ask_yes_no, rprint
60 61 from IPython.utils.ipstruct import Struct
61 62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 63 from IPython.utils.process import system, getoutput
63 64 from IPython.utils.strdispatch import StrDispatch
64 65 from IPython.utils.syspathcontext import prepended_to_syspath
65 66 from IPython.utils.text import num_ini_spaces, format_screen
66 67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 68 List, Unicode, Instance, Type)
68 69 from IPython.utils.warn import warn, error, fatal
69 70 import IPython.core.hooks
70 71
71 72 #-----------------------------------------------------------------------------
72 73 # Globals
73 74 #-----------------------------------------------------------------------------
74 75
75 76 # compiled regexps for autoindent management
76 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 78
78 79 #-----------------------------------------------------------------------------
79 80 # Utilities
80 81 #-----------------------------------------------------------------------------
81 82
82 83 # store the builtin raw_input globally, and use this always, in case user code
83 84 # overwrites it (like wx.py.PyShell does)
84 85 raw_input_original = raw_input
85 86
86 87 def softspace(file, newvalue):
87 88 """Copied from code.py, to remove the dependency"""
88 89
89 90 oldvalue = 0
90 91 try:
91 92 oldvalue = file.softspace
92 93 except AttributeError:
93 94 pass
94 95 try:
95 96 file.softspace = newvalue
96 97 except (AttributeError, TypeError):
97 98 # "attribute-less object" or "read-only attributes"
98 99 pass
99 100 return oldvalue
100 101
101 102
102 103 def no_op(*a, **kw): pass
103 104
104 105 class SpaceInInput(exceptions.Exception): pass
105 106
106 107 class Bunch: pass
107 108
108 109
109 110 def get_default_colors():
110 111 if sys.platform=='darwin':
111 112 return "LightBG"
112 113 elif os.name=='nt':
113 114 return 'Linux'
114 115 else:
115 116 return 'Linux'
116 117
117 118
118 119 class SeparateStr(Str):
119 120 """A Str subclass to validate separate_in, separate_out, etc.
120 121
121 122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 123 """
123 124
124 125 def validate(self, obj, value):
125 126 if value == '0': value = ''
126 127 value = value.replace('\\n','\n')
127 128 return super(SeparateStr, self).validate(obj, value)
128 129
129 130 class MultipleInstanceError(Exception):
130 131 pass
131 132
132 133
133 134 #-----------------------------------------------------------------------------
134 135 # Main IPython class
135 136 #-----------------------------------------------------------------------------
136 137
137 138
138 139 class InteractiveShell(Configurable, Magic):
139 140 """An enhanced, interactive shell for Python."""
140 141
141 142 _instance = None
142 143 autocall = Enum((0,1,2), default_value=1, config=True)
143 144 # TODO: remove all autoindent logic and put into frontends.
144 145 # We can't do this yet because even runlines uses the autoindent.
145 146 autoindent = CBool(True, config=True)
146 147 automagic = CBool(True, config=True)
147 148 cache_size = Int(1000, config=True)
148 149 color_info = CBool(True, config=True)
149 150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 151 default_value=get_default_colors(), config=True)
151 152 debug = CBool(False, config=True)
152 153 deep_reload = CBool(False, config=True)
153 154 displayhook_class = Type(DisplayHook)
154 155 exit_now = CBool(False)
155 156 filename = Str("<ipython console>")
156 157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter')
157 159 logstart = CBool(False, config=True)
158 160 logfile = Str('', config=True)
159 161 logappend = Str('', config=True)
160 162 object_info_string_level = Enum((0,1,2), default_value=0,
161 163 config=True)
162 164 pdb = CBool(False, config=True)
163 165 pprint = CBool(True, config=True)
164 166 profile = Str('', config=True)
165 167 prompt_in1 = Str('In [\\#]: ', config=True)
166 168 prompt_in2 = Str(' .\\D.: ', config=True)
167 169 prompt_out = Str('Out[\\#]: ', config=True)
168 170 prompts_pad_left = CBool(True, config=True)
169 171 quiet = CBool(False, config=True)
170 172
171 173 # The readline stuff will eventually be moved to the terminal subclass
172 174 # but for now, we can't do that as readline is welded in everywhere.
173 175 readline_use = CBool(True, config=True)
174 176 readline_merge_completions = CBool(True, config=True)
175 177 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 178 readline_remove_delims = Str('-/~', config=True)
177 179 readline_parse_and_bind = List([
178 180 'tab: complete',
179 181 '"\C-l": clear-screen',
180 182 'set show-all-if-ambiguous on',
181 183 '"\C-o": tab-insert',
182 184 '"\M-i": " "',
183 185 '"\M-o": "\d\d\d\d"',
184 186 '"\M-I": "\d\d\d\d"',
185 187 '"\C-r": reverse-search-history',
186 188 '"\C-s": forward-search-history',
187 189 '"\C-p": history-search-backward',
188 190 '"\C-n": history-search-forward',
189 191 '"\e[A": history-search-backward',
190 192 '"\e[B": history-search-forward',
191 193 '"\C-k": kill-line',
192 194 '"\C-u": unix-line-discard',
193 195 ], allow_none=False, config=True)
194 196
195 197 # TODO: this part of prompt management should be moved to the frontends.
196 198 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 199 separate_in = SeparateStr('\n', config=True)
198 200 separate_out = SeparateStr('', config=True)
199 201 separate_out2 = SeparateStr('', config=True)
200 202 wildcards_case_sensitive = CBool(True, config=True)
201 203 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
202 204 default_value='Context', config=True)
203 205
204 206 # Subcomponents of InteractiveShell
205 207 alias_manager = Instance('IPython.core.alias.AliasManager')
206 208 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
207 209 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
208 210 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
209 211 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
210 212 plugin_manager = Instance('IPython.core.plugin.PluginManager')
211 213 payload_manager = Instance('IPython.core.payload.PayloadManager')
212 214
213 215 def __init__(self, config=None, ipython_dir=None,
214 216 user_ns=None, user_global_ns=None,
215 custom_exceptions=((),None)):
217 custom_exceptions=((), None)):
216 218
217 219 # This is where traits with a config_key argument are updated
218 220 # from the values on config.
219 221 super(InteractiveShell, self).__init__(config=config)
220 222
221 223 # These are relatively independent and stateless
222 224 self.init_ipython_dir(ipython_dir)
223 225 self.init_instance_attrs()
224 226
225 227 # Create namespaces (user_ns, user_global_ns, etc.)
226 228 self.init_create_namespaces(user_ns, user_global_ns)
227 229 # This has to be done after init_create_namespaces because it uses
228 230 # something in self.user_ns, but before init_sys_modules, which
229 231 # is the first thing to modify sys.
230 232 # TODO: When we override sys.stdout and sys.stderr before this class
231 233 # is created, we are saving the overridden ones here. Not sure if this
232 234 # is what we want to do.
233 235 self.save_sys_module_state()
234 236 self.init_sys_modules()
235 237
236 238 self.init_history()
237 239 self.init_encoding()
238 240 self.init_prefilter()
239 241
240 242 Magic.__init__(self, self)
241 243
242 244 self.init_syntax_highlighting()
243 245 self.init_hooks()
244 246 self.init_pushd_popd_magic()
245 247 # self.init_traceback_handlers use to be here, but we moved it below
246 248 # because it and init_io have to come after init_readline.
247 249 self.init_user_ns()
248 250 self.init_logger()
249 251 self.init_alias()
250 252 self.init_builtins()
251 253
252 254 # pre_config_initialization
253 255 self.init_shadow_hist()
254 256
255 # The next section should contain averything that was in ipmaker.
257 # The next section should contain everything that was in ipmaker.
256 258 self.init_logstart()
257 259
258 260 # The following was in post_config_initialization
259 261 self.init_inspector()
260 262 # init_readline() must come before init_io(), because init_io uses
261 263 # readline related things.
262 264 self.init_readline()
263 265 # init_completer must come after init_readline, because it needs to
264 266 # know whether readline is present or not system-wide to configure the
265 267 # completers, since the completion machinery can now operate
266 268 # independently of readline (e.g. over the network)
267 269 self.init_completer()
268 270 # TODO: init_io() needs to happen before init_traceback handlers
269 271 # because the traceback handlers hardcode the stdout/stderr streams.
270 272 # This logic in in debugger.Pdb and should eventually be changed.
271 273 self.init_io()
272 274 self.init_traceback_handlers(custom_exceptions)
273 275 self.init_prompts()
274 276 self.init_displayhook()
275 277 self.init_reload_doctest()
276 278 self.init_magics()
277 279 self.init_pdb()
278 280 self.init_extension_manager()
279 281 self.init_plugin_manager()
280 282 self.init_payload()
281 283 self.hooks.late_startup_hook()
282 284 atexit.register(self.atexit_operations)
283 285
284 286 @classmethod
285 287 def instance(cls, *args, **kwargs):
286 288 """Returns a global InteractiveShell instance."""
287 289 if cls._instance is None:
288 290 inst = cls(*args, **kwargs)
289 291 # Now make sure that the instance will also be returned by
290 292 # the subclasses instance attribute.
291 293 for subclass in cls.mro():
292 294 if issubclass(cls, subclass) and \
293 295 issubclass(subclass, InteractiveShell):
294 296 subclass._instance = inst
295 297 else:
296 298 break
297 299 if isinstance(cls._instance, cls):
298 300 return cls._instance
299 301 else:
300 302 raise MultipleInstanceError(
301 303 'Multiple incompatible subclass instances of '
302 304 'InteractiveShell are being created.'
303 305 )
304 306
305 307 @classmethod
306 308 def initialized(cls):
307 309 return hasattr(cls, "_instance")
308 310
309 311 def get_ipython(self):
310 312 """Return the currently running IPython instance."""
311 313 return self
312 314
313 315 #-------------------------------------------------------------------------
314 316 # Trait changed handlers
315 317 #-------------------------------------------------------------------------
316 318
317 319 def _ipython_dir_changed(self, name, new):
318 320 if not os.path.isdir(new):
319 321 os.makedirs(new, mode = 0777)
320 322
321 323 def set_autoindent(self,value=None):
322 324 """Set the autoindent flag, checking for readline support.
323 325
324 326 If called with no arguments, it acts as a toggle."""
325 327
326 328 if not self.has_readline:
327 329 if os.name == 'posix':
328 330 warn("The auto-indent feature requires the readline library")
329 331 self.autoindent = 0
330 332 return
331 333 if value is None:
332 334 self.autoindent = not self.autoindent
333 335 else:
334 336 self.autoindent = value
335 337
336 338 #-------------------------------------------------------------------------
337 339 # init_* methods called by __init__
338 340 #-------------------------------------------------------------------------
339 341
340 342 def init_ipython_dir(self, ipython_dir):
341 343 if ipython_dir is not None:
342 344 self.ipython_dir = ipython_dir
343 345 self.config.Global.ipython_dir = self.ipython_dir
344 346 return
345 347
346 348 if hasattr(self.config.Global, 'ipython_dir'):
347 349 self.ipython_dir = self.config.Global.ipython_dir
348 350 else:
349 351 self.ipython_dir = get_ipython_dir()
350 352
351 353 # All children can just read this
352 354 self.config.Global.ipython_dir = self.ipython_dir
353 355
354 356 def init_instance_attrs(self):
355 357 self.more = False
356 358
357 359 # command compiler
358 360 self.compile = codeop.CommandCompiler()
359 361
360 362 # User input buffer
361 363 self.buffer = []
362 364
363 365 # Make an empty namespace, which extension writers can rely on both
364 366 # existing and NEVER being used by ipython itself. This gives them a
365 367 # convenient location for storing additional information and state
366 368 # their extensions may require, without fear of collisions with other
367 369 # ipython names that may develop later.
368 370 self.meta = Struct()
369 371
370 372 # Object variable to store code object waiting execution. This is
371 373 # used mainly by the multithreaded shells, but it can come in handy in
372 374 # other situations. No need to use a Queue here, since it's a single
373 375 # item which gets cleared once run.
374 376 self.code_to_run = None
375 377
376 378 # Temporary files used for various purposes. Deleted at exit.
377 379 self.tempfiles = []
378 380
379 381 # Keep track of readline usage (later set by init_readline)
380 382 self.has_readline = False
381 383
382 384 # keep track of where we started running (mainly for crash post-mortem)
383 385 # This is not being used anywhere currently.
384 386 self.starting_dir = os.getcwd()
385 387
386 388 # Indentation management
387 389 self.indent_current_nsp = 0
388 390
391 # Input splitter, to split entire cells of input into either individual
392 # interactive statements or whole blocks.
393 self.input_splitter = IPythonInputSplitter()
394
389 395 def init_encoding(self):
390 396 # Get system encoding at startup time. Certain terminals (like Emacs
391 397 # under Win32 have it set to None, and we need to have a known valid
392 398 # encoding to use in the raw_input() method
393 399 try:
394 400 self.stdin_encoding = sys.stdin.encoding or 'ascii'
395 401 except AttributeError:
396 402 self.stdin_encoding = 'ascii'
397 403
398 404 def init_syntax_highlighting(self):
399 405 # Python source parser/formatter for syntax highlighting
400 406 pyformat = PyColorize.Parser().format
401 407 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
402 408
403 409 def init_pushd_popd_magic(self):
404 410 # for pushd/popd management
405 411 try:
406 412 self.home_dir = get_home_dir()
407 413 except HomeDirError, msg:
408 414 fatal(msg)
409 415
410 416 self.dir_stack = []
411 417
412 418 def init_logger(self):
413 419 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
414 420 # local shortcut, this is used a LOT
415 421 self.log = self.logger.log
416 422
417 423 def init_logstart(self):
418 424 if self.logappend:
419 425 self.magic_logstart(self.logappend + ' append')
420 426 elif self.logfile:
421 427 self.magic_logstart(self.logfile)
422 428 elif self.logstart:
423 429 self.magic_logstart()
424 430
425 431 def init_builtins(self):
426 432 self.builtin_trap = BuiltinTrap(shell=self)
427 433
428 434 def init_inspector(self):
429 435 # Object inspector
430 436 self.inspector = oinspect.Inspector(oinspect.InspectColors,
431 437 PyColorize.ANSICodeColors,
432 438 'NoColor',
433 439 self.object_info_string_level)
434 440
435 441 def init_io(self):
436 442 import IPython.utils.io
437 443 if sys.platform == 'win32' and self.has_readline:
438 444 Term = io.IOTerm(
439 445 cout=self.readline._outputfile,cerr=self.readline._outputfile
440 446 )
441 447 else:
442 448 Term = io.IOTerm()
443 449 io.Term = Term
444 450
445 451 def init_prompts(self):
446 452 # TODO: This is a pass for now because the prompts are managed inside
447 453 # the DisplayHook. Once there is a separate prompt manager, this
448 454 # will initialize that object and all prompt related information.
449 455 pass
450 456
451 457 def init_displayhook(self):
452 458 # Initialize displayhook, set in/out prompts and printing system
453 459 self.displayhook = self.displayhook_class(
454 460 shell=self,
455 461 cache_size=self.cache_size,
456 462 input_sep = self.separate_in,
457 463 output_sep = self.separate_out,
458 464 output_sep2 = self.separate_out2,
459 465 ps1 = self.prompt_in1,
460 466 ps2 = self.prompt_in2,
461 467 ps_out = self.prompt_out,
462 468 pad_left = self.prompts_pad_left
463 469 )
464 470 # This is a context manager that installs/revmoes the displayhook at
465 471 # the appropriate time.
466 472 self.display_trap = DisplayTrap(hook=self.displayhook)
467 473
468 474 def init_reload_doctest(self):
469 475 # Do a proper resetting of doctest, including the necessary displayhook
470 476 # monkeypatching
471 477 try:
472 478 doctest_reload()
473 479 except ImportError:
474 480 warn("doctest module does not exist.")
475 481
476 482 #-------------------------------------------------------------------------
477 483 # Things related to injections into the sys module
478 484 #-------------------------------------------------------------------------
479 485
480 486 def save_sys_module_state(self):
481 487 """Save the state of hooks in the sys module.
482 488
483 489 This has to be called after self.user_ns is created.
484 490 """
485 491 self._orig_sys_module_state = {}
486 492 self._orig_sys_module_state['stdin'] = sys.stdin
487 493 self._orig_sys_module_state['stdout'] = sys.stdout
488 494 self._orig_sys_module_state['stderr'] = sys.stderr
489 495 self._orig_sys_module_state['excepthook'] = sys.excepthook
490 496 try:
491 497 self._orig_sys_modules_main_name = self.user_ns['__name__']
492 498 except KeyError:
493 499 pass
494 500
495 501 def restore_sys_module_state(self):
496 502 """Restore the state of the sys module."""
497 503 try:
498 504 for k, v in self._orig_sys_module_state.items():
499 505 setattr(sys, k, v)
500 506 except AttributeError:
501 507 pass
502 508 # Reset what what done in self.init_sys_modules
503 509 try:
504 510 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
505 511 except (AttributeError, KeyError):
506 512 pass
507 513
508 514 #-------------------------------------------------------------------------
509 515 # Things related to hooks
510 516 #-------------------------------------------------------------------------
511 517
512 518 def init_hooks(self):
513 519 # hooks holds pointers used for user-side customizations
514 520 self.hooks = Struct()
515 521
516 522 self.strdispatchers = {}
517 523
518 524 # Set all default hooks, defined in the IPython.hooks module.
519 525 hooks = IPython.core.hooks
520 526 for hook_name in hooks.__all__:
521 527 # default hooks have priority 100, i.e. low; user hooks should have
522 528 # 0-100 priority
523 529 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
524 530
525 531 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
526 532 """set_hook(name,hook) -> sets an internal IPython hook.
527 533
528 534 IPython exposes some of its internal API as user-modifiable hooks. By
529 535 adding your function to one of these hooks, you can modify IPython's
530 536 behavior to call at runtime your own routines."""
531 537
532 538 # At some point in the future, this should validate the hook before it
533 539 # accepts it. Probably at least check that the hook takes the number
534 540 # of args it's supposed to.
535 541
536 542 f = new.instancemethod(hook,self,self.__class__)
537 543
538 544 # check if the hook is for strdispatcher first
539 545 if str_key is not None:
540 546 sdp = self.strdispatchers.get(name, StrDispatch())
541 547 sdp.add_s(str_key, f, priority )
542 548 self.strdispatchers[name] = sdp
543 549 return
544 550 if re_key is not None:
545 551 sdp = self.strdispatchers.get(name, StrDispatch())
546 552 sdp.add_re(re.compile(re_key), f, priority )
547 553 self.strdispatchers[name] = sdp
548 554 return
549 555
550 556 dp = getattr(self.hooks, name, None)
551 557 if name not in IPython.core.hooks.__all__:
552 558 print "Warning! Hook '%s' is not one of %s" % \
553 559 (name, IPython.core.hooks.__all__ )
554 560 if not dp:
555 561 dp = IPython.core.hooks.CommandChainDispatcher()
556 562
557 563 try:
558 564 dp.add(f,priority)
559 565 except AttributeError:
560 566 # it was not commandchain, plain old func - replace
561 567 dp = f
562 568
563 569 setattr(self.hooks,name, dp)
564 570
565 571 #-------------------------------------------------------------------------
566 572 # Things related to the "main" module
567 573 #-------------------------------------------------------------------------
568 574
569 575 def new_main_mod(self,ns=None):
570 576 """Return a new 'main' module object for user code execution.
571 577 """
572 578 main_mod = self._user_main_module
573 579 init_fakemod_dict(main_mod,ns)
574 580 return main_mod
575 581
576 582 def cache_main_mod(self,ns,fname):
577 583 """Cache a main module's namespace.
578 584
579 585 When scripts are executed via %run, we must keep a reference to the
580 586 namespace of their __main__ module (a FakeModule instance) around so
581 587 that Python doesn't clear it, rendering objects defined therein
582 588 useless.
583 589
584 590 This method keeps said reference in a private dict, keyed by the
585 591 absolute path of the module object (which corresponds to the script
586 592 path). This way, for multiple executions of the same script we only
587 593 keep one copy of the namespace (the last one), thus preventing memory
588 594 leaks from old references while allowing the objects from the last
589 595 execution to be accessible.
590 596
591 597 Note: we can not allow the actual FakeModule instances to be deleted,
592 598 because of how Python tears down modules (it hard-sets all their
593 599 references to None without regard for reference counts). This method
594 600 must therefore make a *copy* of the given namespace, to allow the
595 601 original module's __dict__ to be cleared and reused.
596 602
597 603
598 604 Parameters
599 605 ----------
600 606 ns : a namespace (a dict, typically)
601 607
602 608 fname : str
603 609 Filename associated with the namespace.
604 610
605 611 Examples
606 612 --------
607 613
608 614 In [10]: import IPython
609 615
610 616 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
611 617
612 618 In [12]: IPython.__file__ in _ip._main_ns_cache
613 619 Out[12]: True
614 620 """
615 621 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
616 622
617 623 def clear_main_mod_cache(self):
618 624 """Clear the cache of main modules.
619 625
620 626 Mainly for use by utilities like %reset.
621 627
622 628 Examples
623 629 --------
624 630
625 631 In [15]: import IPython
626 632
627 633 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
628 634
629 635 In [17]: len(_ip._main_ns_cache) > 0
630 636 Out[17]: True
631 637
632 638 In [18]: _ip.clear_main_mod_cache()
633 639
634 640 In [19]: len(_ip._main_ns_cache) == 0
635 641 Out[19]: True
636 642 """
637 643 self._main_ns_cache.clear()
638 644
639 645 #-------------------------------------------------------------------------
640 646 # Things related to debugging
641 647 #-------------------------------------------------------------------------
642 648
643 649 def init_pdb(self):
644 650 # Set calling of pdb on exceptions
645 651 # self.call_pdb is a property
646 652 self.call_pdb = self.pdb
647 653
648 654 def _get_call_pdb(self):
649 655 return self._call_pdb
650 656
651 657 def _set_call_pdb(self,val):
652 658
653 659 if val not in (0,1,False,True):
654 660 raise ValueError,'new call_pdb value must be boolean'
655 661
656 662 # store value in instance
657 663 self._call_pdb = val
658 664
659 665 # notify the actual exception handlers
660 666 self.InteractiveTB.call_pdb = val
661 667
662 668 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
663 669 'Control auto-activation of pdb at exceptions')
664 670
665 671 def debugger(self,force=False):
666 672 """Call the pydb/pdb debugger.
667 673
668 674 Keywords:
669 675
670 676 - force(False): by default, this routine checks the instance call_pdb
671 677 flag and does not actually invoke the debugger if the flag is false.
672 678 The 'force' option forces the debugger to activate even if the flag
673 679 is false.
674 680 """
675 681
676 682 if not (force or self.call_pdb):
677 683 return
678 684
679 685 if not hasattr(sys,'last_traceback'):
680 686 error('No traceback has been produced, nothing to debug.')
681 687 return
682 688
683 689 # use pydb if available
684 690 if debugger.has_pydb:
685 691 from pydb import pm
686 692 else:
687 693 # fallback to our internal debugger
688 694 pm = lambda : self.InteractiveTB.debugger(force=True)
689 695 self.history_saving_wrapper(pm)()
690 696
691 697 #-------------------------------------------------------------------------
692 698 # Things related to IPython's various namespaces
693 699 #-------------------------------------------------------------------------
694 700
695 701 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
696 702 # Create the namespace where the user will operate. user_ns is
697 703 # normally the only one used, and it is passed to the exec calls as
698 704 # the locals argument. But we do carry a user_global_ns namespace
699 705 # given as the exec 'globals' argument, This is useful in embedding
700 706 # situations where the ipython shell opens in a context where the
701 707 # distinction between locals and globals is meaningful. For
702 708 # non-embedded contexts, it is just the same object as the user_ns dict.
703 709
704 710 # FIXME. For some strange reason, __builtins__ is showing up at user
705 711 # level as a dict instead of a module. This is a manual fix, but I
706 712 # should really track down where the problem is coming from. Alex
707 713 # Schmolck reported this problem first.
708 714
709 715 # A useful post by Alex Martelli on this topic:
710 716 # Re: inconsistent value from __builtins__
711 717 # Von: Alex Martelli <aleaxit@yahoo.com>
712 718 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
713 719 # Gruppen: comp.lang.python
714 720
715 721 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
716 722 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
717 723 # > <type 'dict'>
718 724 # > >>> print type(__builtins__)
719 725 # > <type 'module'>
720 726 # > Is this difference in return value intentional?
721 727
722 728 # Well, it's documented that '__builtins__' can be either a dictionary
723 729 # or a module, and it's been that way for a long time. Whether it's
724 730 # intentional (or sensible), I don't know. In any case, the idea is
725 731 # that if you need to access the built-in namespace directly, you
726 732 # should start with "import __builtin__" (note, no 's') which will
727 733 # definitely give you a module. Yeah, it's somewhat confusing:-(.
728 734
729 735 # These routines return properly built dicts as needed by the rest of
730 736 # the code, and can also be used by extension writers to generate
731 737 # properly initialized namespaces.
732 738 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
733 739 user_global_ns)
734 740
735 741 # Assign namespaces
736 742 # This is the namespace where all normal user variables live
737 743 self.user_ns = user_ns
738 744 self.user_global_ns = user_global_ns
739 745
740 746 # An auxiliary namespace that checks what parts of the user_ns were
741 747 # loaded at startup, so we can list later only variables defined in
742 748 # actual interactive use. Since it is always a subset of user_ns, it
743 749 # doesn't need to be separately tracked in the ns_table.
744 750 self.user_ns_hidden = {}
745 751
746 752 # A namespace to keep track of internal data structures to prevent
747 753 # them from cluttering user-visible stuff. Will be updated later
748 754 self.internal_ns = {}
749 755
750 756 # Now that FakeModule produces a real module, we've run into a nasty
751 757 # problem: after script execution (via %run), the module where the user
752 758 # code ran is deleted. Now that this object is a true module (needed
753 759 # so docetst and other tools work correctly), the Python module
754 760 # teardown mechanism runs over it, and sets to None every variable
755 761 # present in that module. Top-level references to objects from the
756 762 # script survive, because the user_ns is updated with them. However,
757 763 # calling functions defined in the script that use other things from
758 764 # the script will fail, because the function's closure had references
759 765 # to the original objects, which are now all None. So we must protect
760 766 # these modules from deletion by keeping a cache.
761 767 #
762 768 # To avoid keeping stale modules around (we only need the one from the
763 769 # last run), we use a dict keyed with the full path to the script, so
764 770 # only the last version of the module is held in the cache. Note,
765 771 # however, that we must cache the module *namespace contents* (their
766 772 # __dict__). Because if we try to cache the actual modules, old ones
767 773 # (uncached) could be destroyed while still holding references (such as
768 774 # those held by GUI objects that tend to be long-lived)>
769 775 #
770 776 # The %reset command will flush this cache. See the cache_main_mod()
771 777 # and clear_main_mod_cache() methods for details on use.
772 778
773 779 # This is the cache used for 'main' namespaces
774 780 self._main_ns_cache = {}
775 781 # And this is the single instance of FakeModule whose __dict__ we keep
776 782 # copying and clearing for reuse on each %run
777 783 self._user_main_module = FakeModule()
778 784
779 785 # A table holding all the namespaces IPython deals with, so that
780 786 # introspection facilities can search easily.
781 787 self.ns_table = {'user':user_ns,
782 788 'user_global':user_global_ns,
783 789 'internal':self.internal_ns,
784 790 'builtin':__builtin__.__dict__
785 791 }
786 792
787 793 # Similarly, track all namespaces where references can be held and that
788 794 # we can safely clear (so it can NOT include builtin). This one can be
789 795 # a simple list.
790 796 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
791 797 self.internal_ns, self._main_ns_cache ]
792 798
793 799 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
794 800 """Return a valid local and global user interactive namespaces.
795 801
796 802 This builds a dict with the minimal information needed to operate as a
797 803 valid IPython user namespace, which you can pass to the various
798 804 embedding classes in ipython. The default implementation returns the
799 805 same dict for both the locals and the globals to allow functions to
800 806 refer to variables in the namespace. Customized implementations can
801 807 return different dicts. The locals dictionary can actually be anything
802 808 following the basic mapping protocol of a dict, but the globals dict
803 809 must be a true dict, not even a subclass. It is recommended that any
804 810 custom object for the locals namespace synchronize with the globals
805 811 dict somehow.
806 812
807 813 Raises TypeError if the provided globals namespace is not a true dict.
808 814
809 815 Parameters
810 816 ----------
811 817 user_ns : dict-like, optional
812 818 The current user namespace. The items in this namespace should
813 819 be included in the output. If None, an appropriate blank
814 820 namespace should be created.
815 821 user_global_ns : dict, optional
816 822 The current user global namespace. The items in this namespace
817 823 should be included in the output. If None, an appropriate
818 824 blank namespace should be created.
819 825
820 826 Returns
821 827 -------
822 828 A pair of dictionary-like object to be used as the local namespace
823 829 of the interpreter and a dict to be used as the global namespace.
824 830 """
825 831
826 832
827 833 # We must ensure that __builtin__ (without the final 's') is always
828 834 # available and pointing to the __builtin__ *module*. For more details:
829 835 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
830 836
831 837 if user_ns is None:
832 838 # Set __name__ to __main__ to better match the behavior of the
833 839 # normal interpreter.
834 840 user_ns = {'__name__' :'__main__',
835 841 '__builtin__' : __builtin__,
836 842 '__builtins__' : __builtin__,
837 843 }
838 844 else:
839 845 user_ns.setdefault('__name__','__main__')
840 846 user_ns.setdefault('__builtin__',__builtin__)
841 847 user_ns.setdefault('__builtins__',__builtin__)
842 848
843 849 if user_global_ns is None:
844 850 user_global_ns = user_ns
845 851 if type(user_global_ns) is not dict:
846 852 raise TypeError("user_global_ns must be a true dict; got %r"
847 853 % type(user_global_ns))
848 854
849 855 return user_ns, user_global_ns
850 856
851 857 def init_sys_modules(self):
852 858 # We need to insert into sys.modules something that looks like a
853 859 # module but which accesses the IPython namespace, for shelve and
854 860 # pickle to work interactively. Normally they rely on getting
855 861 # everything out of __main__, but for embedding purposes each IPython
856 862 # instance has its own private namespace, so we can't go shoving
857 863 # everything into __main__.
858 864
859 865 # note, however, that we should only do this for non-embedded
860 866 # ipythons, which really mimic the __main__.__dict__ with their own
861 867 # namespace. Embedded instances, on the other hand, should not do
862 868 # this because they need to manage the user local/global namespaces
863 869 # only, but they live within a 'normal' __main__ (meaning, they
864 870 # shouldn't overtake the execution environment of the script they're
865 871 # embedded in).
866 872
867 873 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
868 874
869 875 try:
870 876 main_name = self.user_ns['__name__']
871 877 except KeyError:
872 878 raise KeyError('user_ns dictionary MUST have a "__name__" key')
873 879 else:
874 880 sys.modules[main_name] = FakeModule(self.user_ns)
875 881
876 882 def init_user_ns(self):
877 883 """Initialize all user-visible namespaces to their minimum defaults.
878 884
879 885 Certain history lists are also initialized here, as they effectively
880 886 act as user namespaces.
881 887
882 888 Notes
883 889 -----
884 890 All data structures here are only filled in, they are NOT reset by this
885 891 method. If they were not empty before, data will simply be added to
886 892 therm.
887 893 """
888 894 # This function works in two parts: first we put a few things in
889 895 # user_ns, and we sync that contents into user_ns_hidden so that these
890 896 # initial variables aren't shown by %who. After the sync, we add the
891 897 # rest of what we *do* want the user to see with %who even on a new
892 898 # session (probably nothing, so theye really only see their own stuff)
893 899
894 900 # The user dict must *always* have a __builtin__ reference to the
895 901 # Python standard __builtin__ namespace, which must be imported.
896 902 # This is so that certain operations in prompt evaluation can be
897 903 # reliably executed with builtins. Note that we can NOT use
898 904 # __builtins__ (note the 's'), because that can either be a dict or a
899 905 # module, and can even mutate at runtime, depending on the context
900 906 # (Python makes no guarantees on it). In contrast, __builtin__ is
901 907 # always a module object, though it must be explicitly imported.
902 908
903 909 # For more details:
904 910 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
905 911 ns = dict(__builtin__ = __builtin__)
906 912
907 913 # Put 'help' in the user namespace
908 914 try:
909 915 from site import _Helper
910 916 ns['help'] = _Helper()
911 917 except ImportError:
912 918 warn('help() not available - check site.py')
913 919
914 920 # make global variables for user access to the histories
915 921 ns['_ih'] = self.input_hist
916 922 ns['_oh'] = self.output_hist
917 923 ns['_dh'] = self.dir_hist
918 924
919 925 ns['_sh'] = shadowns
920 926
921 927 # user aliases to input and output histories. These shouldn't show up
922 928 # in %who, as they can have very large reprs.
923 929 ns['In'] = self.input_hist
924 930 ns['Out'] = self.output_hist
925 931
926 932 # Store myself as the public api!!!
927 933 ns['get_ipython'] = self.get_ipython
928 934
929 935 # Sync what we've added so far to user_ns_hidden so these aren't seen
930 936 # by %who
931 937 self.user_ns_hidden.update(ns)
932 938
933 939 # Anything put into ns now would show up in %who. Think twice before
934 940 # putting anything here, as we really want %who to show the user their
935 941 # stuff, not our variables.
936 942
937 943 # Finally, update the real user's namespace
938 944 self.user_ns.update(ns)
939 945
940 946
941 947 def reset(self):
942 948 """Clear all internal namespaces.
943 949
944 950 Note that this is much more aggressive than %reset, since it clears
945 951 fully all namespaces, as well as all input/output lists.
946 952 """
947 953 for ns in self.ns_refs_table:
948 954 ns.clear()
949 955
950 956 self.alias_manager.clear_aliases()
951 957
952 958 # Clear input and output histories
953 959 self.input_hist[:] = []
954 960 self.input_hist_raw[:] = []
955 961 self.output_hist.clear()
956 962
957 963 # Restore the user namespaces to minimal usability
958 964 self.init_user_ns()
959 965
960 966 # Restore the default and user aliases
961 967 self.alias_manager.init_aliases()
962 968
963 969 def reset_selective(self, regex=None):
964 970 """Clear selective variables from internal namespaces based on a
965 971 specified regular expression.
966 972
967 973 Parameters
968 974 ----------
969 975 regex : string or compiled pattern, optional
970 976 A regular expression pattern that will be used in searching
971 977 variable names in the users namespaces.
972 978 """
973 979 if regex is not None:
974 980 try:
975 981 m = re.compile(regex)
976 982 except TypeError:
977 983 raise TypeError('regex must be a string or compiled pattern')
978 984 # Search for keys in each namespace that match the given regex
979 985 # If a match is found, delete the key/value pair.
980 986 for ns in self.ns_refs_table:
981 987 for var in ns:
982 988 if m.search(var):
983 989 del ns[var]
984 990
985 991 def push(self, variables, interactive=True):
986 992 """Inject a group of variables into the IPython user namespace.
987 993
988 994 Parameters
989 995 ----------
990 996 variables : dict, str or list/tuple of str
991 997 The variables to inject into the user's namespace. If a dict, a
992 998 simple update is done. If a str, the string is assumed to have
993 999 variable names separated by spaces. A list/tuple of str can also
994 1000 be used to give the variable names. If just the variable names are
995 1001 give (list/tuple/str) then the variable values looked up in the
996 1002 callers frame.
997 1003 interactive : bool
998 1004 If True (default), the variables will be listed with the ``who``
999 1005 magic.
1000 1006 """
1001 1007 vdict = None
1002 1008
1003 1009 # We need a dict of name/value pairs to do namespace updates.
1004 1010 if isinstance(variables, dict):
1005 1011 vdict = variables
1006 1012 elif isinstance(variables, (basestring, list, tuple)):
1007 1013 if isinstance(variables, basestring):
1008 1014 vlist = variables.split()
1009 1015 else:
1010 1016 vlist = variables
1011 1017 vdict = {}
1012 1018 cf = sys._getframe(1)
1013 1019 for name in vlist:
1014 1020 try:
1015 1021 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1016 1022 except:
1017 1023 print ('Could not get variable %s from %s' %
1018 1024 (name,cf.f_code.co_name))
1019 1025 else:
1020 1026 raise ValueError('variables must be a dict/str/list/tuple')
1021 1027
1022 1028 # Propagate variables to user namespace
1023 1029 self.user_ns.update(vdict)
1024 1030
1025 1031 # And configure interactive visibility
1026 1032 config_ns = self.user_ns_hidden
1027 1033 if interactive:
1028 1034 for name, val in vdict.iteritems():
1029 1035 config_ns.pop(name, None)
1030 1036 else:
1031 1037 for name,val in vdict.iteritems():
1032 1038 config_ns[name] = val
1033 1039
1034 1040 #-------------------------------------------------------------------------
1035 1041 # Things related to object introspection
1036 1042 #-------------------------------------------------------------------------
1037 1043 def _ofind(self, oname, namespaces=None):
1038 1044 """Find an object in the available namespaces.
1039 1045
1040 1046 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1041 1047
1042 1048 Has special code to detect magic functions.
1043 1049 """
1044 1050 #oname = oname.strip()
1045 1051 #print '1- oname: <%r>' % oname # dbg
1046 1052 try:
1047 1053 oname = oname.strip().encode('ascii')
1048 1054 #print '2- oname: <%r>' % oname # dbg
1049 1055 except UnicodeEncodeError:
1050 1056 print 'Python identifiers can only contain ascii characters.'
1051 1057 return dict(found=False)
1052 1058
1053 1059 alias_ns = None
1054 1060 if namespaces is None:
1055 1061 # Namespaces to search in:
1056 1062 # Put them in a list. The order is important so that we
1057 1063 # find things in the same order that Python finds them.
1058 1064 namespaces = [ ('Interactive', self.user_ns),
1059 1065 ('IPython internal', self.internal_ns),
1060 1066 ('Python builtin', __builtin__.__dict__),
1061 1067 ('Alias', self.alias_manager.alias_table),
1062 1068 ]
1063 1069 alias_ns = self.alias_manager.alias_table
1064 1070
1065 1071 # initialize results to 'null'
1066 1072 found = False; obj = None; ospace = None; ds = None;
1067 1073 ismagic = False; isalias = False; parent = None
1068 1074
1069 1075 # We need to special-case 'print', which as of python2.6 registers as a
1070 1076 # function but should only be treated as one if print_function was
1071 1077 # loaded with a future import. In this case, just bail.
1072 1078 if (oname == 'print' and not (self.compile.compiler.flags &
1073 1079 __future__.CO_FUTURE_PRINT_FUNCTION)):
1074 1080 return {'found':found, 'obj':obj, 'namespace':ospace,
1075 1081 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1076 1082
1077 1083 # Look for the given name by splitting it in parts. If the head is
1078 1084 # found, then we look for all the remaining parts as members, and only
1079 1085 # declare success if we can find them all.
1080 1086 oname_parts = oname.split('.')
1081 1087 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1082 1088 for nsname,ns in namespaces:
1083 1089 try:
1084 1090 obj = ns[oname_head]
1085 1091 except KeyError:
1086 1092 continue
1087 1093 else:
1088 1094 #print 'oname_rest:', oname_rest # dbg
1089 1095 for part in oname_rest:
1090 1096 try:
1091 1097 parent = obj
1092 1098 obj = getattr(obj,part)
1093 1099 except:
1094 1100 # Blanket except b/c some badly implemented objects
1095 1101 # allow __getattr__ to raise exceptions other than
1096 1102 # AttributeError, which then crashes IPython.
1097 1103 break
1098 1104 else:
1099 1105 # If we finish the for loop (no break), we got all members
1100 1106 found = True
1101 1107 ospace = nsname
1102 1108 if ns == alias_ns:
1103 1109 isalias = True
1104 1110 break # namespace loop
1105 1111
1106 1112 # Try to see if it's magic
1107 1113 if not found:
1108 1114 if oname.startswith(ESC_MAGIC):
1109 1115 oname = oname[1:]
1110 1116 obj = getattr(self,'magic_'+oname,None)
1111 1117 if obj is not None:
1112 1118 found = True
1113 1119 ospace = 'IPython internal'
1114 1120 ismagic = True
1115 1121
1116 1122 # Last try: special-case some literals like '', [], {}, etc:
1117 1123 if not found and oname_head in ["''",'""','[]','{}','()']:
1118 1124 obj = eval(oname_head)
1119 1125 found = True
1120 1126 ospace = 'Interactive'
1121 1127
1122 1128 return {'found':found, 'obj':obj, 'namespace':ospace,
1123 1129 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1124 1130
1125 1131 def _ofind_property(self, oname, info):
1126 1132 """Second part of object finding, to look for property details."""
1127 1133 if info.found:
1128 1134 # Get the docstring of the class property if it exists.
1129 1135 path = oname.split('.')
1130 1136 root = '.'.join(path[:-1])
1131 1137 if info.parent is not None:
1132 1138 try:
1133 1139 target = getattr(info.parent, '__class__')
1134 1140 # The object belongs to a class instance.
1135 1141 try:
1136 1142 target = getattr(target, path[-1])
1137 1143 # The class defines the object.
1138 1144 if isinstance(target, property):
1139 1145 oname = root + '.__class__.' + path[-1]
1140 1146 info = Struct(self._ofind(oname))
1141 1147 except AttributeError: pass
1142 1148 except AttributeError: pass
1143 1149
1144 1150 # We return either the new info or the unmodified input if the object
1145 1151 # hadn't been found
1146 1152 return info
1147 1153
1148 1154 def _object_find(self, oname, namespaces=None):
1149 1155 """Find an object and return a struct with info about it."""
1150 1156 inf = Struct(self._ofind(oname, namespaces))
1151 1157 return Struct(self._ofind_property(oname, inf))
1152 1158
1153 1159 def _inspect(self, meth, oname, namespaces=None, **kw):
1154 1160 """Generic interface to the inspector system.
1155 1161
1156 1162 This function is meant to be called by pdef, pdoc & friends."""
1157 1163 info = self._object_find(oname)
1158 1164 if info.found:
1159 1165 pmethod = getattr(self.inspector, meth)
1160 1166 formatter = format_screen if info.ismagic else None
1161 1167 if meth == 'pdoc':
1162 1168 pmethod(info.obj, oname, formatter)
1163 1169 elif meth == 'pinfo':
1164 1170 pmethod(info.obj, oname, formatter, info, **kw)
1165 1171 else:
1166 1172 pmethod(info.obj, oname)
1167 1173 else:
1168 1174 print 'Object `%s` not found.' % oname
1169 1175 return 'not found' # so callers can take other action
1170 1176
1171 1177 def object_inspect(self, oname):
1172 1178 info = self._object_find(oname)
1173 1179 if info.found:
1174 1180 return self.inspector.info(info.obj, info=info)
1175 1181 else:
1176 1182 return oinspect.mk_object_info({'found' : False})
1177 1183
1178 1184 #-------------------------------------------------------------------------
1179 1185 # Things related to history management
1180 1186 #-------------------------------------------------------------------------
1181 1187
1182 1188 def init_history(self):
1183 1189 # List of input with multi-line handling.
1184 1190 self.input_hist = InputList()
1185 1191 # This one will hold the 'raw' input history, without any
1186 1192 # pre-processing. This will allow users to retrieve the input just as
1187 1193 # it was exactly typed in by the user, with %hist -r.
1188 1194 self.input_hist_raw = InputList()
1189 1195
1190 1196 # list of visited directories
1191 1197 try:
1192 1198 self.dir_hist = [os.getcwd()]
1193 1199 except OSError:
1194 1200 self.dir_hist = []
1195 1201
1196 1202 # dict of output history
1197 1203 self.output_hist = {}
1198 1204
1199 1205 # Now the history file
1200 1206 if self.profile:
1201 1207 histfname = 'history-%s' % self.profile
1202 1208 else:
1203 1209 histfname = 'history'
1204 1210 self.histfile = os.path.join(self.ipython_dir, histfname)
1205 1211
1206 1212 # Fill the history zero entry, user counter starts at 1
1207 1213 self.input_hist.append('\n')
1208 1214 self.input_hist_raw.append('\n')
1209 1215
1210 1216 def init_shadow_hist(self):
1211 1217 try:
1212 1218 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1213 1219 except exceptions.UnicodeDecodeError:
1214 1220 print "Your ipython_dir can't be decoded to unicode!"
1215 1221 print "Please set HOME environment variable to something that"
1216 1222 print r"only has ASCII characters, e.g. c:\home"
1217 1223 print "Now it is", self.ipython_dir
1218 1224 sys.exit()
1219 1225 self.shadowhist = ipcorehist.ShadowHist(self.db)
1220 1226
1221 1227 def savehist(self):
1222 1228 """Save input history to a file (via readline library)."""
1223 1229
1224 1230 try:
1225 1231 self.readline.write_history_file(self.histfile)
1226 1232 except:
1227 1233 print 'Unable to save IPython command history to file: ' + \
1228 1234 `self.histfile`
1229 1235
1230 1236 def reloadhist(self):
1231 1237 """Reload the input history from disk file."""
1232 1238
1233 1239 try:
1234 1240 self.readline.clear_history()
1235 1241 self.readline.read_history_file(self.shell.histfile)
1236 1242 except AttributeError:
1237 1243 pass
1238 1244
1239 1245 def history_saving_wrapper(self, func):
1240 1246 """ Wrap func for readline history saving
1241 1247
1242 1248 Convert func into callable that saves & restores
1243 1249 history around the call """
1244 1250
1245 1251 if self.has_readline:
1246 1252 from IPython.utils import rlineimpl as readline
1247 1253 else:
1248 1254 return func
1249 1255
1250 1256 def wrapper():
1251 1257 self.savehist()
1252 1258 try:
1253 1259 func()
1254 1260 finally:
1255 1261 readline.read_history_file(self.histfile)
1256 1262 return wrapper
1257 1263
1258 1264 def get_history(self, index=None, raw=False, output=True):
1259 1265 """Get the history list.
1260 1266
1261 1267 Get the input and output history.
1262 1268
1263 1269 Parameters
1264 1270 ----------
1265 1271 index : n or (n1, n2) or None
1266 1272 If n, then the last entries. If a tuple, then all in
1267 1273 range(n1, n2). If None, then all entries. Raises IndexError if
1268 1274 the format of index is incorrect.
1269 1275 raw : bool
1270 1276 If True, return the raw input.
1271 1277 output : bool
1272 1278 If True, then return the output as well.
1273 1279
1274 1280 Returns
1275 1281 -------
1276 1282 If output is True, then return a dict of tuples, keyed by the prompt
1277 1283 numbers and with values of (input, output). If output is False, then
1278 1284 a dict, keyed by the prompt number with the values of input. Raises
1279 1285 IndexError if no history is found.
1280 1286 """
1281 1287 if raw:
1282 1288 input_hist = self.input_hist_raw
1283 1289 else:
1284 1290 input_hist = self.input_hist
1285 1291 if output:
1286 1292 output_hist = self.user_ns['Out']
1287 1293 n = len(input_hist)
1288 1294 if index is None:
1289 1295 start=0; stop=n
1290 1296 elif isinstance(index, int):
1291 1297 start=n-index; stop=n
1292 1298 elif isinstance(index, tuple) and len(index) == 2:
1293 1299 start=index[0]; stop=index[1]
1294 1300 else:
1295 1301 raise IndexError('Not a valid index for the input history: %r'
1296 1302 % index)
1297 1303 hist = {}
1298 1304 for i in range(start, stop):
1299 1305 if output:
1300 1306 hist[i] = (input_hist[i], output_hist.get(i))
1301 1307 else:
1302 1308 hist[i] = input_hist[i]
1303 1309 if len(hist)==0:
1304 1310 raise IndexError('No history for range of indices: %r' % index)
1305 1311 return hist
1306 1312
1307 1313 #-------------------------------------------------------------------------
1308 1314 # Things related to exception handling and tracebacks (not debugging)
1309 1315 #-------------------------------------------------------------------------
1310 1316
1311 1317 def init_traceback_handlers(self, custom_exceptions):
1312 1318 # Syntax error handler.
1313 1319 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1314 1320
1315 1321 # The interactive one is initialized with an offset, meaning we always
1316 1322 # want to remove the topmost item in the traceback, which is our own
1317 1323 # internal code. Valid modes: ['Plain','Context','Verbose']
1318 1324 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1319 1325 color_scheme='NoColor',
1320 1326 tb_offset = 1)
1321 1327
1322 1328 # The instance will store a pointer to the system-wide exception hook,
1323 1329 # so that runtime code (such as magics) can access it. This is because
1324 1330 # during the read-eval loop, it may get temporarily overwritten.
1325 1331 self.sys_excepthook = sys.excepthook
1326 1332
1327 1333 # and add any custom exception handlers the user may have specified
1328 1334 self.set_custom_exc(*custom_exceptions)
1329 1335
1330 1336 # Set the exception mode
1331 1337 self.InteractiveTB.set_mode(mode=self.xmode)
1332 1338
1333 1339 def set_custom_exc(self, exc_tuple, handler):
1334 1340 """set_custom_exc(exc_tuple,handler)
1335 1341
1336 1342 Set a custom exception handler, which will be called if any of the
1337 1343 exceptions in exc_tuple occur in the mainloop (specifically, in the
1338 1344 runcode() method.
1339 1345
1340 1346 Inputs:
1341 1347
1342 1348 - exc_tuple: a *tuple* of valid exceptions to call the defined
1343 1349 handler for. It is very important that you use a tuple, and NOT A
1344 1350 LIST here, because of the way Python's except statement works. If
1345 1351 you only want to trap a single exception, use a singleton tuple:
1346 1352
1347 1353 exc_tuple == (MyCustomException,)
1348 1354
1349 1355 - handler: this must be defined as a function with the following
1350 1356 basic interface::
1351 1357
1352 1358 def my_handler(self, etype, value, tb, tb_offset=None)
1353 1359 ...
1354 1360 # The return value must be
1355 1361 return structured_traceback
1356 1362
1357 1363 This will be made into an instance method (via new.instancemethod)
1358 1364 of IPython itself, and it will be called if any of the exceptions
1359 1365 listed in the exc_tuple are caught. If the handler is None, an
1360 1366 internal basic one is used, which just prints basic info.
1361 1367
1362 1368 WARNING: by putting in your own exception handler into IPython's main
1363 1369 execution loop, you run a very good chance of nasty crashes. This
1364 1370 facility should only be used if you really know what you are doing."""
1365 1371
1366 1372 assert type(exc_tuple)==type(()) , \
1367 1373 "The custom exceptions must be given AS A TUPLE."
1368 1374
1369 1375 def dummy_handler(self,etype,value,tb):
1370 1376 print '*** Simple custom exception handler ***'
1371 1377 print 'Exception type :',etype
1372 1378 print 'Exception value:',value
1373 1379 print 'Traceback :',tb
1374 1380 print 'Source code :','\n'.join(self.buffer)
1375 1381
1376 1382 if handler is None: handler = dummy_handler
1377 1383
1378 1384 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1379 1385 self.custom_exceptions = exc_tuple
1380 1386
1381 1387 def excepthook(self, etype, value, tb):
1382 1388 """One more defense for GUI apps that call sys.excepthook.
1383 1389
1384 1390 GUI frameworks like wxPython trap exceptions and call
1385 1391 sys.excepthook themselves. I guess this is a feature that
1386 1392 enables them to keep running after exceptions that would
1387 1393 otherwise kill their mainloop. This is a bother for IPython
1388 1394 which excepts to catch all of the program exceptions with a try:
1389 1395 except: statement.
1390 1396
1391 1397 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1392 1398 any app directly invokes sys.excepthook, it will look to the user like
1393 1399 IPython crashed. In order to work around this, we can disable the
1394 1400 CrashHandler and replace it with this excepthook instead, which prints a
1395 1401 regular traceback using our InteractiveTB. In this fashion, apps which
1396 1402 call sys.excepthook will generate a regular-looking exception from
1397 1403 IPython, and the CrashHandler will only be triggered by real IPython
1398 1404 crashes.
1399 1405
1400 1406 This hook should be used sparingly, only in places which are not likely
1401 1407 to be true IPython errors.
1402 1408 """
1403 1409 self.showtraceback((etype,value,tb),tb_offset=0)
1404 1410
1405 1411 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1406 1412 exception_only=False):
1407 1413 """Display the exception that just occurred.
1408 1414
1409 1415 If nothing is known about the exception, this is the method which
1410 1416 should be used throughout the code for presenting user tracebacks,
1411 1417 rather than directly invoking the InteractiveTB object.
1412 1418
1413 1419 A specific showsyntaxerror() also exists, but this method can take
1414 1420 care of calling it if needed, so unless you are explicitly catching a
1415 1421 SyntaxError exception, don't try to analyze the stack manually and
1416 1422 simply call this method."""
1417 1423
1418 1424 try:
1419 1425 if exc_tuple is None:
1420 1426 etype, value, tb = sys.exc_info()
1421 1427 else:
1422 1428 etype, value, tb = exc_tuple
1423 1429
1424 1430 if etype is None:
1425 1431 if hasattr(sys, 'last_type'):
1426 1432 etype, value, tb = sys.last_type, sys.last_value, \
1427 1433 sys.last_traceback
1428 1434 else:
1429 1435 self.write_err('No traceback available to show.\n')
1430 1436 return
1431 1437
1432 1438 if etype is SyntaxError:
1433 1439 # Though this won't be called by syntax errors in the input
1434 1440 # line, there may be SyntaxError cases whith imported code.
1435 1441 self.showsyntaxerror(filename)
1436 1442 elif etype is UsageError:
1437 1443 print "UsageError:", value
1438 1444 else:
1439 1445 # WARNING: these variables are somewhat deprecated and not
1440 1446 # necessarily safe to use in a threaded environment, but tools
1441 1447 # like pdb depend on their existence, so let's set them. If we
1442 1448 # find problems in the field, we'll need to revisit their use.
1443 1449 sys.last_type = etype
1444 1450 sys.last_value = value
1445 1451 sys.last_traceback = tb
1446 1452
1447 1453 if etype in self.custom_exceptions:
1448 1454 # FIXME: Old custom traceback objects may just return a
1449 1455 # string, in that case we just put it into a list
1450 1456 stb = self.CustomTB(etype, value, tb, tb_offset)
1451 1457 if isinstance(ctb, basestring):
1452 1458 stb = [stb]
1453 1459 else:
1454 1460 if exception_only:
1455 1461 stb = ['An exception has occurred, use %tb to see '
1456 1462 'the full traceback.\n']
1457 1463 stb.extend(self.InteractiveTB.get_exception_only(etype,
1458 1464 value))
1459 1465 else:
1460 1466 stb = self.InteractiveTB.structured_traceback(etype,
1461 1467 value, tb, tb_offset=tb_offset)
1462 1468 # FIXME: the pdb calling should be done by us, not by
1463 1469 # the code computing the traceback.
1464 1470 if self.InteractiveTB.call_pdb:
1465 1471 # pdb mucks up readline, fix it back
1466 1472 self.set_readline_completer()
1467 1473
1468 1474 # Actually show the traceback
1469 1475 self._showtraceback(etype, value, stb)
1470 1476
1471 1477 except KeyboardInterrupt:
1472 1478 self.write_err("\nKeyboardInterrupt\n")
1473 1479
1474 1480 def _showtraceback(self, etype, evalue, stb):
1475 1481 """Actually show a traceback.
1476 1482
1477 1483 Subclasses may override this method to put the traceback on a different
1478 1484 place, like a side channel.
1479 1485 """
1480 1486 # FIXME: this should use the proper write channels, but our test suite
1481 1487 # relies on it coming out of stdout...
1482 1488 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1483 1489
1484 1490 def showsyntaxerror(self, filename=None):
1485 1491 """Display the syntax error that just occurred.
1486 1492
1487 1493 This doesn't display a stack trace because there isn't one.
1488 1494
1489 1495 If a filename is given, it is stuffed in the exception instead
1490 1496 of what was there before (because Python's parser always uses
1491 1497 "<string>" when reading from a string).
1492 1498 """
1493 1499 etype, value, last_traceback = sys.exc_info()
1494 1500
1495 1501 # See note about these variables in showtraceback() above
1496 1502 sys.last_type = etype
1497 1503 sys.last_value = value
1498 1504 sys.last_traceback = last_traceback
1499 1505
1500 1506 if filename and etype is SyntaxError:
1501 1507 # Work hard to stuff the correct filename in the exception
1502 1508 try:
1503 1509 msg, (dummy_filename, lineno, offset, line) = value
1504 1510 except:
1505 1511 # Not the format we expect; leave it alone
1506 1512 pass
1507 1513 else:
1508 1514 # Stuff in the right filename
1509 1515 try:
1510 1516 # Assume SyntaxError is a class exception
1511 1517 value = SyntaxError(msg, (filename, lineno, offset, line))
1512 1518 except:
1513 1519 # If that failed, assume SyntaxError is a string
1514 1520 value = msg, (filename, lineno, offset, line)
1515 1521 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1516 1522 self._showtraceback(etype, value, stb)
1517 1523
1518 1524 #-------------------------------------------------------------------------
1519 1525 # Things related to readline
1520 1526 #-------------------------------------------------------------------------
1521 1527
1522 1528 def init_readline(self):
1523 1529 """Command history completion/saving/reloading."""
1524 1530
1525 1531 if self.readline_use:
1526 1532 import IPython.utils.rlineimpl as readline
1527 1533
1528 1534 self.rl_next_input = None
1529 1535 self.rl_do_indent = False
1530 1536
1531 1537 if not self.readline_use or not readline.have_readline:
1532 1538 self.has_readline = False
1533 1539 self.readline = None
1534 1540 # Set a number of methods that depend on readline to be no-op
1535 1541 self.savehist = no_op
1536 1542 self.reloadhist = no_op
1537 1543 self.set_readline_completer = no_op
1538 1544 self.set_custom_completer = no_op
1539 1545 self.set_completer_frame = no_op
1540 1546 warn('Readline services not available or not loaded.')
1541 1547 else:
1542 1548 self.has_readline = True
1543 1549 self.readline = readline
1544 1550 sys.modules['readline'] = readline
1545 1551
1546 1552 # Platform-specific configuration
1547 1553 if os.name == 'nt':
1548 1554 # FIXME - check with Frederick to see if we can harmonize
1549 1555 # naming conventions with pyreadline to avoid this
1550 1556 # platform-dependent check
1551 1557 self.readline_startup_hook = readline.set_pre_input_hook
1552 1558 else:
1553 1559 self.readline_startup_hook = readline.set_startup_hook
1554 1560
1555 1561 # Load user's initrc file (readline config)
1556 1562 # Or if libedit is used, load editrc.
1557 1563 inputrc_name = os.environ.get('INPUTRC')
1558 1564 if inputrc_name is None:
1559 1565 home_dir = get_home_dir()
1560 1566 if home_dir is not None:
1561 1567 inputrc_name = '.inputrc'
1562 1568 if readline.uses_libedit:
1563 1569 inputrc_name = '.editrc'
1564 1570 inputrc_name = os.path.join(home_dir, inputrc_name)
1565 1571 if os.path.isfile(inputrc_name):
1566 1572 try:
1567 1573 readline.read_init_file(inputrc_name)
1568 1574 except:
1569 1575 warn('Problems reading readline initialization file <%s>'
1570 1576 % inputrc_name)
1571 1577
1572 1578 # Configure readline according to user's prefs
1573 1579 # This is only done if GNU readline is being used. If libedit
1574 1580 # is being used (as on Leopard) the readline config is
1575 1581 # not run as the syntax for libedit is different.
1576 1582 if not readline.uses_libedit:
1577 1583 for rlcommand in self.readline_parse_and_bind:
1578 1584 #print "loading rl:",rlcommand # dbg
1579 1585 readline.parse_and_bind(rlcommand)
1580 1586
1581 1587 # Remove some chars from the delimiters list. If we encounter
1582 1588 # unicode chars, discard them.
1583 1589 delims = readline.get_completer_delims().encode("ascii", "ignore")
1584 1590 delims = delims.translate(string._idmap,
1585 1591 self.readline_remove_delims)
1586 1592 delims = delims.replace(ESC_MAGIC, '')
1587 1593 readline.set_completer_delims(delims)
1588 1594 # otherwise we end up with a monster history after a while:
1589 1595 readline.set_history_length(1000)
1590 1596 try:
1591 1597 #print '*** Reading readline history' # dbg
1592 1598 readline.read_history_file(self.histfile)
1593 1599 except IOError:
1594 1600 pass # It doesn't exist yet.
1595 1601
1596 1602 # If we have readline, we want our history saved upon ipython
1597 1603 # exiting.
1598 1604 atexit.register(self.savehist)
1599 1605
1600 1606 # Configure auto-indent for all platforms
1601 1607 self.set_autoindent(self.autoindent)
1602 1608
1603 1609 def set_next_input(self, s):
1604 1610 """ Sets the 'default' input string for the next command line.
1605 1611
1606 1612 Requires readline.
1607 1613
1608 1614 Example:
1609 1615
1610 1616 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1611 1617 [D:\ipython]|2> Hello Word_ # cursor is here
1612 1618 """
1613 1619
1614 1620 self.rl_next_input = s
1615 1621
1616 1622 # Maybe move this to the terminal subclass?
1617 1623 def pre_readline(self):
1618 1624 """readline hook to be used at the start of each line.
1619 1625
1620 1626 Currently it handles auto-indent only."""
1621 1627
1622 1628 if self.rl_do_indent:
1623 1629 self.readline.insert_text(self._indent_current_str())
1624 1630 if self.rl_next_input is not None:
1625 1631 self.readline.insert_text(self.rl_next_input)
1626 1632 self.rl_next_input = None
1627 1633
1628 1634 def _indent_current_str(self):
1629 1635 """return the current level of indentation as a string"""
1630 1636 return self.indent_current_nsp * ' '
1631 1637
1632 1638 #-------------------------------------------------------------------------
1633 1639 # Things related to text completion
1634 1640 #-------------------------------------------------------------------------
1635 1641
1636 1642 def init_completer(self):
1637 1643 """Initialize the completion machinery.
1638 1644
1639 1645 This creates completion machinery that can be used by client code,
1640 1646 either interactively in-process (typically triggered by the readline
1641 1647 library), programatically (such as in test suites) or out-of-prcess
1642 1648 (typically over the network by remote frontends).
1643 1649 """
1644 1650 from IPython.core.completer import IPCompleter
1645 1651 from IPython.core.completerlib import (module_completer,
1646 1652 magic_run_completer, cd_completer)
1647 1653
1648 1654 self.Completer = IPCompleter(self,
1649 1655 self.user_ns,
1650 1656 self.user_global_ns,
1651 1657 self.readline_omit__names,
1652 1658 self.alias_manager.alias_table,
1653 1659 self.has_readline)
1654 1660
1655 1661 # Add custom completers to the basic ones built into IPCompleter
1656 1662 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1657 1663 self.strdispatchers['complete_command'] = sdisp
1658 1664 self.Completer.custom_completers = sdisp
1659 1665
1660 1666 self.set_hook('complete_command', module_completer, str_key = 'import')
1661 1667 self.set_hook('complete_command', module_completer, str_key = 'from')
1662 1668 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1663 1669 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1664 1670
1665 1671 # Only configure readline if we truly are using readline. IPython can
1666 1672 # do tab-completion over the network, in GUIs, etc, where readline
1667 1673 # itself may be absent
1668 1674 if self.has_readline:
1669 1675 self.set_readline_completer()
1670 1676
1671 1677 def complete(self, text, line=None, cursor_pos=None):
1672 1678 """Return the completed text and a list of completions.
1673 1679
1674 1680 Parameters
1675 1681 ----------
1676 1682
1677 1683 text : string
1678 1684 A string of text to be completed on. It can be given as empty and
1679 1685 instead a line/position pair are given. In this case, the
1680 1686 completer itself will split the line like readline does.
1681 1687
1682 1688 line : string, optional
1683 1689 The complete line that text is part of.
1684 1690
1685 1691 cursor_pos : int, optional
1686 1692 The position of the cursor on the input line.
1687 1693
1688 1694 Returns
1689 1695 -------
1690 1696 text : string
1691 1697 The actual text that was completed.
1692 1698
1693 1699 matches : list
1694 1700 A sorted list with all possible completions.
1695 1701
1696 1702 The optional arguments allow the completion to take more context into
1697 1703 account, and are part of the low-level completion API.
1698 1704
1699 1705 This is a wrapper around the completion mechanism, similar to what
1700 1706 readline does at the command line when the TAB key is hit. By
1701 1707 exposing it as a method, it can be used by other non-readline
1702 1708 environments (such as GUIs) for text completion.
1703 1709
1704 1710 Simple usage example:
1705 1711
1706 1712 In [1]: x = 'hello'
1707 1713
1708 1714 In [2]: _ip.complete('x.l')
1709 1715 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1710 1716 """
1711 1717
1712 1718 # Inject names into __builtin__ so we can complete on the added names.
1713 1719 with self.builtin_trap:
1714 1720 return self.Completer.complete(text, line, cursor_pos)
1715 1721
1716 1722 def set_custom_completer(self, completer, pos=0):
1717 1723 """Adds a new custom completer function.
1718 1724
1719 1725 The position argument (defaults to 0) is the index in the completers
1720 1726 list where you want the completer to be inserted."""
1721 1727
1722 1728 newcomp = new.instancemethod(completer,self.Completer,
1723 1729 self.Completer.__class__)
1724 1730 self.Completer.matchers.insert(pos,newcomp)
1725 1731
1726 1732 def set_readline_completer(self):
1727 1733 """Reset readline's completer to be our own."""
1728 1734 self.readline.set_completer(self.Completer.rlcomplete)
1729 1735
1730 1736 def set_completer_frame(self, frame=None):
1731 1737 """Set the frame of the completer."""
1732 1738 if frame:
1733 1739 self.Completer.namespace = frame.f_locals
1734 1740 self.Completer.global_namespace = frame.f_globals
1735 1741 else:
1736 1742 self.Completer.namespace = self.user_ns
1737 1743 self.Completer.global_namespace = self.user_global_ns
1738 1744
1739 1745 #-------------------------------------------------------------------------
1740 1746 # Things related to magics
1741 1747 #-------------------------------------------------------------------------
1742 1748
1743 1749 def init_magics(self):
1744 1750 # FIXME: Move the color initialization to the DisplayHook, which
1745 1751 # should be split into a prompt manager and displayhook. We probably
1746 1752 # even need a centralize colors management object.
1747 1753 self.magic_colors(self.colors)
1748 1754 # History was moved to a separate module
1749 1755 from . import history
1750 1756 history.init_ipython(self)
1751 1757
1752 1758 def magic(self,arg_s):
1753 1759 """Call a magic function by name.
1754 1760
1755 1761 Input: a string containing the name of the magic function to call and
1756 1762 any additional arguments to be passed to the magic.
1757 1763
1758 1764 magic('name -opt foo bar') is equivalent to typing at the ipython
1759 1765 prompt:
1760 1766
1761 1767 In[1]: %name -opt foo bar
1762 1768
1763 1769 To call a magic without arguments, simply use magic('name').
1764 1770
1765 1771 This provides a proper Python function to call IPython's magics in any
1766 1772 valid Python code you can type at the interpreter, including loops and
1767 1773 compound statements.
1768 1774 """
1769 1775 args = arg_s.split(' ',1)
1770 1776 magic_name = args[0]
1771 1777 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1772 1778
1773 1779 try:
1774 1780 magic_args = args[1]
1775 1781 except IndexError:
1776 1782 magic_args = ''
1777 1783 fn = getattr(self,'magic_'+magic_name,None)
1778 1784 if fn is None:
1779 1785 error("Magic function `%s` not found." % magic_name)
1780 1786 else:
1781 1787 magic_args = self.var_expand(magic_args,1)
1782 1788 with nested(self.builtin_trap,):
1783 1789 result = fn(magic_args)
1784 1790 return result
1785 1791
1786 1792 def define_magic(self, magicname, func):
1787 1793 """Expose own function as magic function for ipython
1788 1794
1789 1795 def foo_impl(self,parameter_s=''):
1790 1796 'My very own magic!. (Use docstrings, IPython reads them).'
1791 1797 print 'Magic function. Passed parameter is between < >:'
1792 1798 print '<%s>' % parameter_s
1793 1799 print 'The self object is:',self
1794 1800
1795 1801 self.define_magic('foo',foo_impl)
1796 1802 """
1797 1803
1798 1804 import new
1799 1805 im = new.instancemethod(func,self, self.__class__)
1800 1806 old = getattr(self, "magic_" + magicname, None)
1801 1807 setattr(self, "magic_" + magicname, im)
1802 1808 return old
1803 1809
1804 1810 #-------------------------------------------------------------------------
1805 1811 # Things related to macros
1806 1812 #-------------------------------------------------------------------------
1807 1813
1808 1814 def define_macro(self, name, themacro):
1809 1815 """Define a new macro
1810 1816
1811 1817 Parameters
1812 1818 ----------
1813 1819 name : str
1814 1820 The name of the macro.
1815 1821 themacro : str or Macro
1816 1822 The action to do upon invoking the macro. If a string, a new
1817 1823 Macro object is created by passing the string to it.
1818 1824 """
1819 1825
1820 1826 from IPython.core import macro
1821 1827
1822 1828 if isinstance(themacro, basestring):
1823 1829 themacro = macro.Macro(themacro)
1824 1830 if not isinstance(themacro, macro.Macro):
1825 1831 raise ValueError('A macro must be a string or a Macro instance.')
1826 1832 self.user_ns[name] = themacro
1827 1833
1828 1834 #-------------------------------------------------------------------------
1829 1835 # Things related to the running of system commands
1830 1836 #-------------------------------------------------------------------------
1831 1837
1832 1838 def system(self, cmd):
1833 1839 """Call the given cmd in a subprocess."""
1834 1840 # We do not support backgrounding processes because we either use
1835 1841 # pexpect or pipes to read from. Users can always just call
1836 1842 # os.system() if they really want a background process.
1837 1843 if cmd.endswith('&'):
1838 1844 raise OSError("Background processes not supported.")
1839 1845
1840 1846 return system(self.var_expand(cmd, depth=2))
1841 1847
1842 1848 def getoutput(self, cmd):
1843 1849 """Get output (possibly including stderr) from a subprocess."""
1844 1850 if cmd.endswith('&'):
1845 1851 raise OSError("Background processes not supported.")
1846 1852 return getoutput(self.var_expand(cmd, depth=2))
1847 1853
1848 1854 #-------------------------------------------------------------------------
1849 1855 # Things related to aliases
1850 1856 #-------------------------------------------------------------------------
1851 1857
1852 1858 def init_alias(self):
1853 1859 self.alias_manager = AliasManager(shell=self, config=self.config)
1854 1860 self.ns_table['alias'] = self.alias_manager.alias_table,
1855 1861
1856 1862 #-------------------------------------------------------------------------
1857 1863 # Things related to extensions and plugins
1858 1864 #-------------------------------------------------------------------------
1859 1865
1860 1866 def init_extension_manager(self):
1861 1867 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1862 1868
1863 1869 def init_plugin_manager(self):
1864 1870 self.plugin_manager = PluginManager(config=self.config)
1865 1871
1866 1872 #-------------------------------------------------------------------------
1867 1873 # Things related to payloads
1868 1874 #-------------------------------------------------------------------------
1869 1875
1870 1876 def init_payload(self):
1871 1877 self.payload_manager = PayloadManager(config=self.config)
1872 1878
1873 1879 #-------------------------------------------------------------------------
1874 1880 # Things related to the prefilter
1875 1881 #-------------------------------------------------------------------------
1876 1882
1877 1883 def init_prefilter(self):
1878 1884 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1879 1885 # Ultimately this will be refactored in the new interpreter code, but
1880 1886 # for now, we should expose the main prefilter method (there's legacy
1881 1887 # code out there that may rely on this).
1882 1888 self.prefilter = self.prefilter_manager.prefilter_lines
1883 1889
1884 1890
1885 1891 def auto_rewrite_input(self, cmd):
1886 1892 """Print to the screen the rewritten form of the user's command.
1887 1893
1888 1894 This shows visual feedback by rewriting input lines that cause
1889 1895 automatic calling to kick in, like::
1890 1896
1891 1897 /f x
1892 1898
1893 1899 into::
1894 1900
1895 1901 ------> f(x)
1896 1902
1897 1903 after the user's input prompt. This helps the user understand that the
1898 1904 input line was transformed automatically by IPython.
1899 1905 """
1900 1906 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1901 1907
1902 1908 try:
1903 1909 # plain ascii works better w/ pyreadline, on some machines, so
1904 1910 # we use it and only print uncolored rewrite if we have unicode
1905 1911 rw = str(rw)
1906 1912 print >> IPython.utils.io.Term.cout, rw
1907 1913 except UnicodeEncodeError:
1908 1914 print "------> " + cmd
1909 1915
1910 1916 #-------------------------------------------------------------------------
1911 1917 # Things related to extracting values/expressions from kernel and user_ns
1912 1918 #-------------------------------------------------------------------------
1913 1919
1914 1920 def _simple_error(self):
1915 1921 etype, value = sys.exc_info()[:2]
1916 1922 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1917 1923
1918 1924 def get_user_variables(self, names):
1919 1925 """Get a list of variable names from the user's namespace.
1920 1926
1921 1927 The return value is a dict with the repr() of each value.
1922 1928 """
1923 1929 out = {}
1924 1930 user_ns = self.user_ns
1925 1931 for varname in names:
1926 1932 try:
1927 1933 value = repr(user_ns[varname])
1928 1934 except:
1929 1935 value = self._simple_error()
1930 1936 out[varname] = value
1931 1937 return out
1932 1938
1933 1939 def eval_expressions(self, expressions):
1934 1940 """Evaluate a dict of expressions in the user's namespace.
1935 1941
1936 1942 The return value is a dict with the repr() of each value.
1937 1943 """
1938 1944 out = {}
1939 1945 user_ns = self.user_ns
1940 1946 global_ns = self.user_global_ns
1941 1947 for key, expr in expressions.iteritems():
1942 1948 try:
1943 1949 value = repr(eval(expr, global_ns, user_ns))
1944 1950 except:
1945 1951 value = self._simple_error()
1946 1952 out[key] = value
1947 1953 return out
1948 1954
1949 1955 #-------------------------------------------------------------------------
1950 1956 # Things related to the running of code
1951 1957 #-------------------------------------------------------------------------
1952 1958
1953 1959 def ex(self, cmd):
1954 1960 """Execute a normal python statement in user namespace."""
1955 1961 with nested(self.builtin_trap,):
1956 1962 exec cmd in self.user_global_ns, self.user_ns
1957 1963
1958 1964 def ev(self, expr):
1959 1965 """Evaluate python expression expr in user namespace.
1960 1966
1961 1967 Returns the result of evaluation
1962 1968 """
1963 1969 with nested(self.builtin_trap,):
1964 1970 return eval(expr, self.user_global_ns, self.user_ns)
1965 1971
1966 1972 def safe_execfile(self, fname, *where, **kw):
1967 1973 """A safe version of the builtin execfile().
1968 1974
1969 1975 This version will never throw an exception, but instead print
1970 1976 helpful error messages to the screen. This only works on pure
1971 1977 Python files with the .py extension.
1972 1978
1973 1979 Parameters
1974 1980 ----------
1975 1981 fname : string
1976 1982 The name of the file to be executed.
1977 1983 where : tuple
1978 1984 One or two namespaces, passed to execfile() as (globals,locals).
1979 1985 If only one is given, it is passed as both.
1980 1986 exit_ignore : bool (False)
1981 1987 If True, then silence SystemExit for non-zero status (it is always
1982 1988 silenced for zero status, as it is so common).
1983 1989 """
1984 1990 kw.setdefault('exit_ignore', False)
1985 1991
1986 1992 fname = os.path.abspath(os.path.expanduser(fname))
1987 1993
1988 1994 # Make sure we have a .py file
1989 1995 if not fname.endswith('.py'):
1990 1996 warn('File must end with .py to be run using execfile: <%s>' % fname)
1991 1997
1992 1998 # Make sure we can open the file
1993 1999 try:
1994 2000 with open(fname) as thefile:
1995 2001 pass
1996 2002 except:
1997 2003 warn('Could not open file <%s> for safe execution.' % fname)
1998 2004 return
1999 2005
2000 2006 # Find things also in current directory. This is needed to mimic the
2001 2007 # behavior of running a script from the system command line, where
2002 2008 # Python inserts the script's directory into sys.path
2003 2009 dname = os.path.dirname(fname)
2004 2010
2005 2011 with prepended_to_syspath(dname):
2006 2012 try:
2007 2013 execfile(fname,*where)
2008 2014 except SystemExit, status:
2009 2015 # If the call was made with 0 or None exit status (sys.exit(0)
2010 2016 # or sys.exit() ), don't bother showing a traceback, as both of
2011 2017 # these are considered normal by the OS:
2012 2018 # > python -c'import sys;sys.exit(0)'; echo $?
2013 2019 # 0
2014 2020 # > python -c'import sys;sys.exit()'; echo $?
2015 2021 # 0
2016 2022 # For other exit status, we show the exception unless
2017 2023 # explicitly silenced, but only in short form.
2018 2024 if status.code not in (0, None) and not kw['exit_ignore']:
2019 2025 self.showtraceback(exception_only=True)
2020 2026 except:
2021 2027 self.showtraceback()
2022 2028
2023 2029 def safe_execfile_ipy(self, fname):
2024 2030 """Like safe_execfile, but for .ipy files with IPython syntax.
2025 2031
2026 2032 Parameters
2027 2033 ----------
2028 2034 fname : str
2029 2035 The name of the file to execute. The filename must have a
2030 2036 .ipy extension.
2031 2037 """
2032 2038 fname = os.path.abspath(os.path.expanduser(fname))
2033 2039
2034 2040 # Make sure we have a .py file
2035 2041 if not fname.endswith('.ipy'):
2036 2042 warn('File must end with .py to be run using execfile: <%s>' % fname)
2037 2043
2038 2044 # Make sure we can open the file
2039 2045 try:
2040 2046 with open(fname) as thefile:
2041 2047 pass
2042 2048 except:
2043 2049 warn('Could not open file <%s> for safe execution.' % fname)
2044 2050 return
2045 2051
2046 2052 # Find things also in current directory. This is needed to mimic the
2047 2053 # behavior of running a script from the system command line, where
2048 2054 # Python inserts the script's directory into sys.path
2049 2055 dname = os.path.dirname(fname)
2050 2056
2051 2057 with prepended_to_syspath(dname):
2052 2058 try:
2053 2059 with open(fname) as thefile:
2054 2060 script = thefile.read()
2055 2061 # self.runlines currently captures all exceptions
2056 2062 # raise in user code. It would be nice if there were
2057 2063 # versions of runlines, execfile that did raise, so
2058 2064 # we could catch the errors.
2059 2065 self.runlines(script, clean=True)
2060 2066 except:
2061 2067 self.showtraceback()
2062 2068 warn('Unknown failure executing file: <%s>' % fname)
2063 2069
2070 def run_cell(self, cell):
2071 """Run the contents of an entire multiline 'cell' of code.
2072
2073 The cell is split into separate blocks which can be executed
2074 individually. Then, based on how many blocks there are, they are
2075 executed as follows:
2076
2077 - A single block: 'single' mode.
2078
2079 If there's more than one block, it depends:
2080
2081 - if the last one is a single line long, run all but the last in
2082 'exec' mode and the very last one in 'single' mode. This makes it
2083 easy to type simple expressions at the end to see computed values.
2084 - otherwise (last one is also multiline), run all in 'exec' mode
2085
2086 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2087 results are displayed and output prompts are computed. In 'exec' mode,
2088 no results are displayed unless :func:`print` is called explicitly;
2089 this mode is more akin to running a script.
2090
2091 Parameters
2092 ----------
2093 cell : str
2094 A single or multiline string.
2095 """
2096 blocks = self.input_splitter.split_blocks(cell)
2097 if not blocks:
2098 return
2099
2100 if len(blocks) == 1:
2101 self.runlines(blocks[0])
2102
2103 last = blocks[-1]
2104 if len(last.splitlines()) < 2:
2105 map(self.runcode, blocks[:-1])
2106 self.runlines(last)
2107 else:
2108 map(self.runcode, blocks)
2109
2064 2110 def runlines(self, lines, clean=False):
2065 2111 """Run a string of one or more lines of source.
2066 2112
2067 2113 This method is capable of running a string containing multiple source
2068 2114 lines, as if they had been entered at the IPython prompt. Since it
2069 2115 exposes IPython's processing machinery, the given strings can contain
2070 2116 magic calls (%magic), special shell access (!cmd), etc.
2071 2117 """
2072 2118
2073 2119 if isinstance(lines, (list, tuple)):
2074 2120 lines = '\n'.join(lines)
2075 2121
2076 2122 if clean:
2077 2123 lines = self._cleanup_ipy_script(lines)
2078 2124
2079 2125 # We must start with a clean buffer, in case this is run from an
2080 2126 # interactive IPython session (via a magic, for example).
2081 2127 self.resetbuffer()
2082 2128 lines = lines.splitlines()
2083 2129 more = 0
2084 2130 with nested(self.builtin_trap, self.display_trap):
2085 2131 for line in lines:
2086 2132 # skip blank lines so we don't mess up the prompt counter, but
2087 2133 # do NOT skip even a blank line if we are in a code block (more
2088 2134 # is true)
2089 2135
2090 2136 if line or more:
2091 2137 # push to raw history, so hist line numbers stay in sync
2092 2138 self.input_hist_raw.append(line + '\n')
2093 2139 prefiltered = self.prefilter_manager.prefilter_lines(line,
2094 2140 more)
2095 2141 more = self.push_line(prefiltered)
2096 2142 # IPython's runsource returns None if there was an error
2097 2143 # compiling the code. This allows us to stop processing
2098 2144 # right away, so the user gets the error message at the
2099 2145 # right place.
2100 2146 if more is None:
2101 2147 break
2102 2148 else:
2103 2149 self.input_hist_raw.append("\n")
2104 2150 # final newline in case the input didn't have it, so that the code
2105 2151 # actually does get executed
2106 2152 if more:
2107 2153 self.push_line('\n')
2108 2154
2109 2155 def runsource(self, source, filename='<input>', symbol='single'):
2110 2156 """Compile and run some source in the interpreter.
2111 2157
2112 2158 Arguments are as for compile_command().
2113 2159
2114 2160 One several things can happen:
2115 2161
2116 2162 1) The input is incorrect; compile_command() raised an
2117 2163 exception (SyntaxError or OverflowError). A syntax traceback
2118 2164 will be printed by calling the showsyntaxerror() method.
2119 2165
2120 2166 2) The input is incomplete, and more input is required;
2121 2167 compile_command() returned None. Nothing happens.
2122 2168
2123 2169 3) The input is complete; compile_command() returned a code
2124 2170 object. The code is executed by calling self.runcode() (which
2125 2171 also handles run-time exceptions, except for SystemExit).
2126 2172
2127 2173 The return value is:
2128 2174
2129 2175 - True in case 2
2130 2176
2131 2177 - False in the other cases, unless an exception is raised, where
2132 2178 None is returned instead. This can be used by external callers to
2133 2179 know whether to continue feeding input or not.
2134 2180
2135 2181 The return value can be used to decide whether to use sys.ps1 or
2136 2182 sys.ps2 to prompt the next line."""
2137 2183
2138 2184 # if the source code has leading blanks, add 'if 1:\n' to it
2139 2185 # this allows execution of indented pasted code. It is tempting
2140 2186 # to add '\n' at the end of source to run commands like ' a=1'
2141 2187 # directly, but this fails for more complicated scenarios
2142 2188 source=source.encode(self.stdin_encoding)
2143 2189 if source[:1] in [' ', '\t']:
2144 2190 source = 'if 1:\n%s' % source
2145 2191
2146 2192 try:
2147 2193 code = self.compile(source,filename,symbol)
2148 2194 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2149 2195 # Case 1
2150 2196 self.showsyntaxerror(filename)
2151 2197 return None
2152 2198
2153 2199 if code is None:
2154 2200 # Case 2
2155 2201 return True
2156 2202
2157 2203 # Case 3
2158 2204 # We store the code object so that threaded shells and
2159 2205 # custom exception handlers can access all this info if needed.
2160 2206 # The source corresponding to this can be obtained from the
2161 2207 # buffer attribute as '\n'.join(self.buffer).
2162 2208 self.code_to_run = code
2163 2209 # now actually execute the code object
2164 2210 if self.runcode(code) == 0:
2165 2211 return False
2166 2212 else:
2167 2213 return None
2168 2214
2169 def runcode(self,code_obj):
2215 def runcode(self, code_obj):
2170 2216 """Execute a code object.
2171 2217
2172 2218 When an exception occurs, self.showtraceback() is called to display a
2173 2219 traceback.
2174 2220
2175 2221 Return value: a flag indicating whether the code to be run completed
2176 2222 successfully:
2177 2223
2178 2224 - 0: successful execution.
2179 2225 - 1: an error occurred.
2180 2226 """
2181 2227
2182 2228 # Set our own excepthook in case the user code tries to call it
2183 2229 # directly, so that the IPython crash handler doesn't get triggered
2184 2230 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2185 2231
2186 2232 # we save the original sys.excepthook in the instance, in case config
2187 2233 # code (such as magics) needs access to it.
2188 2234 self.sys_excepthook = old_excepthook
2189 2235 outflag = 1 # happens in more places, so it's easier as default
2190 2236 try:
2191 2237 try:
2192 2238 self.hooks.pre_runcode_hook()
2193 2239 #rprint('Running code') # dbg
2194 2240 exec code_obj in self.user_global_ns, self.user_ns
2195 2241 finally:
2196 2242 # Reset our crash handler in place
2197 2243 sys.excepthook = old_excepthook
2198 2244 except SystemExit:
2199 2245 self.resetbuffer()
2200 2246 self.showtraceback(exception_only=True)
2201 2247 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2202 2248 except self.custom_exceptions:
2203 2249 etype,value,tb = sys.exc_info()
2204 2250 self.CustomTB(etype,value,tb)
2205 2251 except:
2206 2252 self.showtraceback()
2207 2253 else:
2208 2254 outflag = 0
2209 2255 if softspace(sys.stdout, 0):
2210 2256 print
2211 2257 # Flush out code object which has been run (and source)
2212 2258 self.code_to_run = None
2213 2259 return outflag
2214 2260
2215 2261 def push_line(self, line):
2216 2262 """Push a line to the interpreter.
2217 2263
2218 2264 The line should not have a trailing newline; it may have
2219 2265 internal newlines. The line is appended to a buffer and the
2220 2266 interpreter's runsource() method is called with the
2221 2267 concatenated contents of the buffer as source. If this
2222 2268 indicates that the command was executed or invalid, the buffer
2223 2269 is reset; otherwise, the command is incomplete, and the buffer
2224 2270 is left as it was after the line was appended. The return
2225 2271 value is 1 if more input is required, 0 if the line was dealt
2226 2272 with in some way (this is the same as runsource()).
2227 2273 """
2228 2274
2229 2275 # autoindent management should be done here, and not in the
2230 2276 # interactive loop, since that one is only seen by keyboard input. We
2231 2277 # need this done correctly even for code run via runlines (which uses
2232 2278 # push).
2233 2279
2234 2280 #print 'push line: <%s>' % line # dbg
2235 2281 for subline in line.splitlines():
2236 2282 self._autoindent_update(subline)
2237 2283 self.buffer.append(line)
2238 2284 more = self.runsource('\n'.join(self.buffer), self.filename)
2239 2285 if not more:
2240 2286 self.resetbuffer()
2241 2287 return more
2242 2288
2243 2289 def resetbuffer(self):
2244 2290 """Reset the input buffer."""
2245 2291 self.buffer[:] = []
2246 2292
2247 2293 def _is_secondary_block_start(self, s):
2248 2294 if not s.endswith(':'):
2249 2295 return False
2250 2296 if (s.startswith('elif') or
2251 2297 s.startswith('else') or
2252 2298 s.startswith('except') or
2253 2299 s.startswith('finally')):
2254 2300 return True
2255 2301
2256 2302 def _cleanup_ipy_script(self, script):
2257 2303 """Make a script safe for self.runlines()
2258 2304
2259 2305 Currently, IPython is lines based, with blocks being detected by
2260 2306 empty lines. This is a problem for block based scripts that may
2261 2307 not have empty lines after blocks. This script adds those empty
2262 2308 lines to make scripts safe for running in the current line based
2263 2309 IPython.
2264 2310 """
2265 2311 res = []
2266 2312 lines = script.splitlines()
2267 2313 level = 0
2268 2314
2269 2315 for l in lines:
2270 2316 lstripped = l.lstrip()
2271 2317 stripped = l.strip()
2272 2318 if not stripped:
2273 2319 continue
2274 2320 newlevel = len(l) - len(lstripped)
2275 2321 if level > 0 and newlevel == 0 and \
2276 2322 not self._is_secondary_block_start(stripped):
2277 2323 # add empty line
2278 2324 res.append('')
2279 2325 res.append(l)
2280 2326 level = newlevel
2281 2327
2282 2328 return '\n'.join(res) + '\n'
2283 2329
2284 2330 def _autoindent_update(self,line):
2285 2331 """Keep track of the indent level."""
2286 2332
2287 2333 #debugx('line')
2288 2334 #debugx('self.indent_current_nsp')
2289 2335 if self.autoindent:
2290 2336 if line:
2291 2337 inisp = num_ini_spaces(line)
2292 2338 if inisp < self.indent_current_nsp:
2293 2339 self.indent_current_nsp = inisp
2294 2340
2295 2341 if line[-1] == ':':
2296 2342 self.indent_current_nsp += 4
2297 2343 elif dedent_re.match(line):
2298 2344 self.indent_current_nsp -= 4
2299 2345 else:
2300 2346 self.indent_current_nsp = 0
2301 2347
2302 2348 #-------------------------------------------------------------------------
2303 2349 # Things related to GUI support and pylab
2304 2350 #-------------------------------------------------------------------------
2305 2351
2306 2352 def enable_pylab(self, gui=None):
2307 2353 raise NotImplementedError('Implement enable_pylab in a subclass')
2308 2354
2309 2355 #-------------------------------------------------------------------------
2310 2356 # Utilities
2311 2357 #-------------------------------------------------------------------------
2312 2358
2313 2359 def var_expand(self,cmd,depth=0):
2314 2360 """Expand python variables in a string.
2315 2361
2316 2362 The depth argument indicates how many frames above the caller should
2317 2363 be walked to look for the local namespace where to expand variables.
2318 2364
2319 2365 The global namespace for expansion is always the user's interactive
2320 2366 namespace.
2321 2367 """
2322 2368
2323 2369 return str(ItplNS(cmd,
2324 2370 self.user_ns, # globals
2325 2371 # Skip our own frame in searching for locals:
2326 2372 sys._getframe(depth+1).f_locals # locals
2327 2373 ))
2328 2374
2329 2375 def mktempfile(self,data=None):
2330 2376 """Make a new tempfile and return its filename.
2331 2377
2332 2378 This makes a call to tempfile.mktemp, but it registers the created
2333 2379 filename internally so ipython cleans it up at exit time.
2334 2380
2335 2381 Optional inputs:
2336 2382
2337 2383 - data(None): if data is given, it gets written out to the temp file
2338 2384 immediately, and the file is closed again."""
2339 2385
2340 2386 filename = tempfile.mktemp('.py','ipython_edit_')
2341 2387 self.tempfiles.append(filename)
2342 2388
2343 2389 if data:
2344 2390 tmp_file = open(filename,'w')
2345 2391 tmp_file.write(data)
2346 2392 tmp_file.close()
2347 2393 return filename
2348 2394
2349 2395 # TODO: This should be removed when Term is refactored.
2350 2396 def write(self,data):
2351 2397 """Write a string to the default output"""
2352 2398 io.Term.cout.write(data)
2353 2399
2354 2400 # TODO: This should be removed when Term is refactored.
2355 2401 def write_err(self,data):
2356 2402 """Write a string to the default error output"""
2357 2403 io.Term.cerr.write(data)
2358 2404
2359 2405 def ask_yes_no(self,prompt,default=True):
2360 2406 if self.quiet:
2361 2407 return True
2362 2408 return ask_yes_no(prompt,default)
2363 2409
2364 2410 def show_usage(self):
2365 2411 """Show a usage message"""
2366 2412 page.page(IPython.core.usage.interactive_usage)
2367 2413
2368 2414 #-------------------------------------------------------------------------
2369 2415 # Things related to IPython exiting
2370 2416 #-------------------------------------------------------------------------
2371 2417 def atexit_operations(self):
2372 2418 """This will be executed at the time of exit.
2373 2419
2374 2420 Cleanup operations and saving of persistent data that is done
2375 2421 unconditionally by IPython should be performed here.
2376 2422
2377 2423 For things that may depend on startup flags or platform specifics (such
2378 2424 as having readline or not), register a separate atexit function in the
2379 2425 code that has the appropriate information, rather than trying to
2380 2426 clutter
2381 2427 """
2382 2428 # Cleanup all tempfiles left around
2383 2429 for tfile in self.tempfiles:
2384 2430 try:
2385 2431 os.unlink(tfile)
2386 2432 except OSError:
2387 2433 pass
2388 2434
2389 2435 # Clear all user namespaces to release all references cleanly.
2390 2436 self.reset()
2391 2437
2392 2438 # Run user hooks
2393 2439 self.hooks.shutdown_hook()
2394 2440
2395 2441 def cleanup(self):
2396 2442 self.restore_sys_module_state()
2397 2443
2398 2444
2399 2445 class InteractiveShellABC(object):
2400 2446 """An abstract base class for InteractiveShell."""
2401 2447 __metaclass__ = abc.ABCMeta
2402 2448
2403 2449 InteractiveShellABC.register(InteractiveShell)
@@ -1,649 +1,649
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for the inputsplitter module.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2010 The IPython Development Team
6 6 #
7 7 # Distributed under the terms of the BSD License. The full license is in
8 8 # the file COPYING, distributed as part of this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14 # stdlib
15 15 import unittest
16 16 import sys
17 17
18 18 # Third party
19 19 import nose.tools as nt
20 20
21 21 # Our own
22 22 from IPython.core import inputsplitter as isp
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Semi-complete examples (also used as tests)
26 26 #-----------------------------------------------------------------------------
27 27
28 28 # Note: at the bottom, there's a slightly more complete version of this that
29 29 # can be useful during development of code here.
30 30
31 31 def mini_interactive_loop(raw_input):
32 32 """Minimal example of the logic of an interactive interpreter loop.
33 33
34 34 This serves as an example, and it is used by the test system with a fake
35 35 raw_input that simulates interactive input."""
36 36
37 37 from IPython.core.inputsplitter import InputSplitter
38 38
39 39 isp = InputSplitter()
40 40 # In practice, this input loop would be wrapped in an outside loop to read
41 41 # input indefinitely, until some exit/quit command was issued. Here we
42 42 # only illustrate the basic inner loop.
43 43 while isp.push_accepts_more():
44 44 indent = ' '*isp.indent_spaces
45 45 prompt = '>>> ' + indent
46 46 line = indent + raw_input(prompt)
47 47 isp.push(line)
48 48
49 49 # Here we just return input so we can use it in a test suite, but a real
50 50 # interpreter would instead send it for execution somewhere.
51 51 src = isp.source_reset()
52 52 #print 'Input source was:\n', src # dbg
53 53 return src
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Test utilities, just for local use
57 57 #-----------------------------------------------------------------------------
58 58
59 59 def assemble(block):
60 60 """Assemble a block into multi-line sub-blocks."""
61 61 return ['\n'.join(sub_block)+'\n' for sub_block in block]
62 62
63 63
64 64 def pseudo_input(lines):
65 65 """Return a function that acts like raw_input but feeds the input list."""
66 66 ilines = iter(lines)
67 67 def raw_in(prompt):
68 68 try:
69 69 return next(ilines)
70 70 except StopIteration:
71 71 return ''
72 72 return raw_in
73 73
74 74 #-----------------------------------------------------------------------------
75 75 # Tests
76 76 #-----------------------------------------------------------------------------
77 77 def test_spaces():
78 78 tests = [('', 0),
79 79 (' ', 1),
80 80 ('\n', 0),
81 81 (' \n', 1),
82 82 ('x', 0),
83 83 (' x', 1),
84 84 (' x',2),
85 85 (' x',4),
86 86 # Note: tabs are counted as a single whitespace!
87 87 ('\tx', 1),
88 88 ('\t x', 2),
89 89 ]
90 90
91 91 for s, nsp in tests:
92 92 nt.assert_equal(isp.num_ini_spaces(s), nsp)
93 93
94 94
95 95 def test_remove_comments():
96 96 tests = [('text', 'text'),
97 97 ('text # comment', 'text '),
98 98 ('text # comment\n', 'text \n'),
99 99 ('text # comment \n', 'text \n'),
100 100 ('line # c \nline\n','line \nline\n'),
101 101 ('line # c \nline#c2 \nline\nline #c\n\n',
102 102 'line \nline\nline\nline \n\n'),
103 103 ]
104 104
105 105 for inp, out in tests:
106 106 nt.assert_equal(isp.remove_comments(inp), out)
107 107
108 108
109 109 def test_get_input_encoding():
110 110 encoding = isp.get_input_encoding()
111 111 nt.assert_true(isinstance(encoding, basestring))
112 112 # simple-minded check that at least encoding a simple string works with the
113 113 # encoding we got.
114 114 nt.assert_equal('test'.encode(encoding), 'test')
115 115
116 116
117 117 class NoInputEncodingTestCase(unittest.TestCase):
118 118 def setUp(self):
119 119 self.old_stdin = sys.stdin
120 120 class X: pass
121 121 fake_stdin = X()
122 122 sys.stdin = fake_stdin
123 123
124 124 def test(self):
125 125 # Verify that if sys.stdin has no 'encoding' attribute we do the right
126 126 # thing
127 127 enc = isp.get_input_encoding()
128 128 self.assertEqual(enc, 'ascii')
129 129
130 130 def tearDown(self):
131 131 sys.stdin = self.old_stdin
132 132
133 133
134 134 class InputSplitterTestCase(unittest.TestCase):
135 135 def setUp(self):
136 136 self.isp = isp.InputSplitter()
137 137
138 138 def test_reset(self):
139 139 isp = self.isp
140 140 isp.push('x=1')
141 141 isp.reset()
142 142 self.assertEqual(isp._buffer, [])
143 143 self.assertEqual(isp.indent_spaces, 0)
144 144 self.assertEqual(isp.source, '')
145 145 self.assertEqual(isp.code, None)
146 146 self.assertEqual(isp._is_complete, False)
147 147
148 148 def test_source(self):
149 149 self.isp._store('1')
150 150 self.isp._store('2')
151 151 self.assertEqual(self.isp.source, '1\n2\n')
152 152 self.assertTrue(len(self.isp._buffer)>0)
153 153 self.assertEqual(self.isp.source_reset(), '1\n2\n')
154 154 self.assertEqual(self.isp._buffer, [])
155 155 self.assertEqual(self.isp.source, '')
156 156
157 157 def test_indent(self):
158 158 isp = self.isp # shorthand
159 159 isp.push('x=1')
160 160 self.assertEqual(isp.indent_spaces, 0)
161 161 isp.push('if 1:\n x=1')
162 162 self.assertEqual(isp.indent_spaces, 4)
163 163 isp.push('y=2\n')
164 164 self.assertEqual(isp.indent_spaces, 0)
165 165 isp.push('if 1:')
166 166 self.assertEqual(isp.indent_spaces, 4)
167 167 isp.push(' x=1')
168 168 self.assertEqual(isp.indent_spaces, 4)
169 169 # Blank lines shouldn't change the indent level
170 170 isp.push(' '*2)
171 171 self.assertEqual(isp.indent_spaces, 4)
172 172
173 173 def test_indent2(self):
174 174 isp = self.isp
175 175 # When a multiline statement contains parens or multiline strings, we
176 176 # shouldn't get confused.
177 177 isp.push("if 1:")
178 178 isp.push(" x = (1+\n 2)")
179 179 self.assertEqual(isp.indent_spaces, 4)
180 180
181 181 def test_dedent(self):
182 182 isp = self.isp # shorthand
183 183 isp.push('if 1:')
184 184 self.assertEqual(isp.indent_spaces, 4)
185 185 isp.push(' pass')
186 186 self.assertEqual(isp.indent_spaces, 0)
187 187
188 188 def test_push(self):
189 189 isp = self.isp
190 190 self.assertTrue(isp.push('x=1'))
191 191
192 192 def test_push2(self):
193 193 isp = self.isp
194 194 self.assertFalse(isp.push('if 1:'))
195 195 for line in [' x=1', '# a comment', ' y=2']:
196 196 self.assertTrue(isp.push(line))
197 197
198 198 def test_push3(self):
199 199 """Test input with leading whitespace"""
200 200 isp = self.isp
201 201 isp.push(' x=1')
202 202 isp.push(' y=2')
203 203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
204 204
205 205 def test_replace_mode(self):
206 206 isp = self.isp
207 207 isp.input_mode = 'block'
208 208 isp.push('x=1')
209 209 self.assertEqual(isp.source, 'x=1\n')
210 210 isp.push('x=2')
211 211 self.assertEqual(isp.source, 'x=2\n')
212 212
213 213 def test_push_accepts_more(self):
214 214 isp = self.isp
215 215 isp.push('x=1')
216 216 self.assertFalse(isp.push_accepts_more())
217 217
218 218 def test_push_accepts_more2(self):
219 219 isp = self.isp
220 220 isp.push('if 1:')
221 221 self.assertTrue(isp.push_accepts_more())
222 222 isp.push(' x=1')
223 223 self.assertTrue(isp.push_accepts_more())
224 224 isp.push('')
225 225 self.assertFalse(isp.push_accepts_more())
226 226
227 227 def test_push_accepts_more3(self):
228 228 isp = self.isp
229 229 isp.push("x = (2+\n3)")
230 230 self.assertFalse(isp.push_accepts_more())
231 231
232 232 def test_push_accepts_more4(self):
233 233 isp = self.isp
234 234 # When a multiline statement contains parens or multiline strings, we
235 235 # shouldn't get confused.
236 236 # FIXME: we should be able to better handle de-dents in statements like
237 237 # multiline strings and multiline expressions (continued with \ or
238 238 # parens). Right now we aren't handling the indentation tracking quite
239 239 # correctly with this, though in practice it may not be too much of a
240 240 # problem. We'll need to see.
241 241 isp.push("if 1:")
242 242 isp.push(" x = (2+")
243 243 isp.push(" 3)")
244 244 self.assertTrue(isp.push_accepts_more())
245 245 isp.push(" y = 3")
246 246 self.assertTrue(isp.push_accepts_more())
247 247 isp.push('')
248 248 self.assertFalse(isp.push_accepts_more())
249 249
250 250 def test_syntax_error(self):
251 251 isp = self.isp
252 252 # Syntax errors immediately produce a 'ready' block, so the invalid
253 253 # Python can be sent to the kernel for evaluation with possible ipython
254 254 # special-syntax conversion.
255 255 isp.push('run foo')
256 256 self.assertFalse(isp.push_accepts_more())
257 257
258 258 def check_split(self, block_lines, compile=True):
259 259 blocks = assemble(block_lines)
260 260 lines = ''.join(blocks)
261 261 oblock = self.isp.split_blocks(lines)
262 262 self.assertEqual(oblock, blocks)
263 263 if compile:
264 264 for block in blocks:
265 265 self.isp._compile(block)
266 266
267 267 def test_split(self):
268 268 # All blocks of input we want to test in a list. The format for each
269 269 # block is a list of lists, with each inner lists consisting of all the
270 270 # lines (as single-lines) that should make up a sub-block.
271 271
272 272 # Note: do NOT put here sub-blocks that don't compile, as the
273 273 # check_split() routine makes a final verification pass to check that
274 274 # each sub_block, as returned by split_blocks(), does compile
275 275 # correctly.
276 276 all_blocks = [ [['x=1']],
277 277
278 278 [['x=1'],
279 279 ['y=2']],
280 280
281 [['x=1'],
282 ['# a comment'],
281 [['x=1',
282 '# a comment'],
283 283 ['y=11']],
284 284
285 285 [['if 1:',
286 286 ' x=1'],
287 287 ['y=3']],
288 288
289 289 [['def f(x):',
290 290 ' return x'],
291 291 ['x=1']],
292 292
293 293 [['def f(x):',
294 294 ' x+=1',
295 295 ' ',
296 296 ' return x'],
297 297 ['x=1']],
298 298
299 299 [['def f(x):',
300 300 ' if x>0:',
301 301 ' y=1',
302 302 ' # a comment',
303 303 ' else:',
304 304 ' y=4',
305 305 ' ',
306 306 ' return y'],
307 307 ['x=1'],
308 308 ['if 1:',
309 309 ' y=11'] ],
310 310
311 311 [['for i in range(10):'
312 312 ' x=i**2']],
313 313
314 314 [['for i in range(10):'
315 315 ' x=i**2'],
316 316 ['z = 1']],
317 317 ]
318 318 for block_lines in all_blocks:
319 319 self.check_split(block_lines)
320 320
321 321 def test_split_syntax_errors(self):
322 322 # Block splitting with invalid syntax
323 323 all_blocks = [ [['a syntax error']],
324 324
325 [['x=1'],
326 ['a syntax error']],
325 [['x=1',
326 'another syntax error']],
327 327
328 328 [['for i in range(10):'
329 ' an error']],
329 ' yet another error']],
330 330
331 331 ]
332 332 for block_lines in all_blocks:
333 333 self.check_split(block_lines, compile=False)
334 334
335 335
336 336 class InteractiveLoopTestCase(unittest.TestCase):
337 337 """Tests for an interactive loop like a python shell.
338 338 """
339 339 def check_ns(self, lines, ns):
340 340 """Validate that the given input lines produce the resulting namespace.
341 341
342 342 Note: the input lines are given exactly as they would be typed in an
343 343 auto-indenting environment, as mini_interactive_loop above already does
344 344 auto-indenting and prepends spaces to the input.
345 345 """
346 346 src = mini_interactive_loop(pseudo_input(lines))
347 347 test_ns = {}
348 348 exec src in test_ns
349 349 # We can't check that the provided ns is identical to the test_ns,
350 350 # because Python fills test_ns with extra keys (copyright, etc). But
351 351 # we can check that the given dict is *contained* in test_ns
352 352 for k,v in ns.items():
353 353 self.assertEqual(test_ns[k], v)
354 354
355 355 def test_simple(self):
356 356 self.check_ns(['x=1'], dict(x=1))
357 357
358 358 def test_simple2(self):
359 359 self.check_ns(['if 1:', 'x=2'], dict(x=2))
360 360
361 361 def test_xy(self):
362 362 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
363 363
364 364 def test_abc(self):
365 365 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
366 366
367 367 def test_multi(self):
368 368 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
369 369
370 370
371 371 def test_LineInfo():
372 372 """Simple test for LineInfo construction and str()"""
373 373 linfo = isp.LineInfo(' %cd /home')
374 374 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
375 375
376 376
377 377 def test_split_user_input():
378 378 """Unicode test - split_user_input already has good doctests"""
379 379 line = u"PΓ©rez Fernando"
380 380 parts = isp.split_user_input(line)
381 381 parts_expected = (u'', u'', u'', line)
382 382 nt.assert_equal(parts, parts_expected)
383 383
384 384
385 385 # Transformer tests
386 386 def transform_checker(tests, func):
387 387 """Utility to loop over test inputs"""
388 388 for inp, tr in tests:
389 389 nt.assert_equals(func(inp), tr)
390 390
391 391 # Data for all the syntax tests in the form of lists of pairs of
392 392 # raw/transformed input. We store it here as a global dict so that we can use
393 393 # it both within single-function tests and also to validate the behavior of the
394 394 # larger objects
395 395
396 396 syntax = \
397 397 dict(assign_system =
398 398 [('a =! ls', 'a = get_ipython().magic("sc -l = ls")'),
399 399 ('b = !ls', 'b = get_ipython().magic("sc -l = ls")'),
400 400 ('x=1', 'x=1'), # normal input is unmodified
401 401 (' ',' '), # blank lines are kept intact
402 402 ],
403 403
404 404 assign_magic =
405 405 [('a =% who', 'a = get_ipython().magic("who")'),
406 406 ('b = %who', 'b = get_ipython().magic("who")'),
407 407 ('x=1', 'x=1'), # normal input is unmodified
408 408 (' ',' '), # blank lines are kept intact
409 409 ],
410 410
411 411 classic_prompt =
412 412 [('>>> x=1', 'x=1'),
413 413 ('x=1', 'x=1'), # normal input is unmodified
414 414 (' ', ' '), # blank lines are kept intact
415 415 ('... ', ''), # continuation prompts
416 416 ],
417 417
418 418 ipy_prompt =
419 419 [('In [1]: x=1', 'x=1'),
420 420 ('x=1', 'x=1'), # normal input is unmodified
421 421 (' ',' '), # blank lines are kept intact
422 422 (' ....: ', ''), # continuation prompts
423 423 ],
424 424
425 425 # Tests for the escape transformer to leave normal code alone
426 426 escaped_noesc =
427 427 [ (' ', ' '),
428 428 ('x=1', 'x=1'),
429 429 ],
430 430
431 431 # System calls
432 432 escaped_shell =
433 433 [ ('!ls', 'get_ipython().system("ls")'),
434 434 # Double-escape shell, this means to capture the output of the
435 435 # subprocess and return it
436 436 ('!!ls', 'get_ipython().getoutput("ls")'),
437 437 ],
438 438
439 439 # Help/object info
440 440 escaped_help =
441 441 [ ('?', 'get_ipython().show_usage()'),
442 442 ('?x1', 'get_ipython().magic("pinfo x1")'),
443 443 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
444 444 ('x3?', 'get_ipython().magic("pinfo x3")'),
445 445 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
446 446 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
447 447 ],
448 448
449 449 # Explicit magic calls
450 450 escaped_magic =
451 451 [ ('%cd', 'get_ipython().magic("cd")'),
452 452 ('%cd /home', 'get_ipython().magic("cd /home")'),
453 453 (' %magic', ' get_ipython().magic("magic")'),
454 454 ],
455 455
456 456 # Quoting with separate arguments
457 457 escaped_quote =
458 458 [ (',f', 'f("")'),
459 459 (',f x', 'f("x")'),
460 460 (' ,f y', ' f("y")'),
461 461 (',f a b', 'f("a", "b")'),
462 462 ],
463 463
464 464 # Quoting with single argument
465 465 escaped_quote2 =
466 466 [ (';f', 'f("")'),
467 467 (';f x', 'f("x")'),
468 468 (' ;f y', ' f("y")'),
469 469 (';f a b', 'f("a b")'),
470 470 ],
471 471
472 472 # Simply apply parens
473 473 escaped_paren =
474 474 [ ('/f', 'f()'),
475 475 ('/f x', 'f(x)'),
476 476 (' /f y', ' f(y)'),
477 477 ('/f a b', 'f(a, b)'),
478 478 ],
479 479
480 480 )
481 481
482 482 # multiline syntax examples. Each of these should be a list of lists, with
483 483 # each entry itself having pairs of raw/transformed input. The union (with
484 484 # '\n'.join() of the transformed inputs is what the splitter should produce
485 485 # when fed the raw lines one at a time via push.
486 486 syntax_ml = \
487 487 dict(classic_prompt =
488 488 [ [('>>> for i in range(10):','for i in range(10):'),
489 489 ('... print i',' print i'),
490 490 ('... ', ''),
491 491 ],
492 492 ],
493 493
494 494 ipy_prompt =
495 495 [ [('In [24]: for i in range(10):','for i in range(10):'),
496 496 (' ....: print i',' print i'),
497 497 (' ....: ', ''),
498 498 ],
499 499 ],
500 500 )
501 501
502 502
503 503 def test_assign_system():
504 504 transform_checker(syntax['assign_system'], isp.transform_assign_system)
505 505
506 506
507 507 def test_assign_magic():
508 508 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
509 509
510 510
511 511 def test_classic_prompt():
512 512 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
513 513 for example in syntax_ml['classic_prompt']:
514 514 transform_checker(example, isp.transform_classic_prompt)
515 515
516 516
517 517 def test_ipy_prompt():
518 518 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
519 519 for example in syntax_ml['ipy_prompt']:
520 520 transform_checker(example, isp.transform_ipy_prompt)
521 521
522 522
523 523 def test_escaped_noesc():
524 524 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
525 525
526 526
527 527 def test_escaped_shell():
528 528 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
529 529
530 530
531 531 def test_escaped_help():
532 532 transform_checker(syntax['escaped_help'], isp.transform_escaped)
533 533
534 534
535 535 def test_escaped_magic():
536 536 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
537 537
538 538
539 539 def test_escaped_quote():
540 540 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
541 541
542 542
543 543 def test_escaped_quote2():
544 544 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
545 545
546 546
547 547 def test_escaped_paren():
548 548 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
549 549
550 550
551 551 class IPythonInputTestCase(InputSplitterTestCase):
552 552 """By just creating a new class whose .isp is a different instance, we
553 553 re-run the same test battery on the new input splitter.
554 554
555 555 In addition, this runs the tests over the syntax and syntax_ml dicts that
556 556 were tested by individual functions, as part of the OO interface.
557 557 """
558 558
559 559 def setUp(self):
560 560 self.isp = isp.IPythonInputSplitter(input_mode='line')
561 561
562 562 def test_syntax(self):
563 563 """Call all single-line syntax tests from the main object"""
564 564 isp = self.isp
565 565 for example in syntax.itervalues():
566 566 for raw, out_t in example:
567 567 if raw.startswith(' '):
568 568 continue
569 569
570 570 isp.push(raw)
571 571 out = isp.source_reset().rstrip()
572 572 self.assertEqual(out, out_t)
573 573
574 574 def test_syntax_multiline(self):
575 575 isp = self.isp
576 576 for example in syntax_ml.itervalues():
577 577 out_t_parts = []
578 578 for line_pairs in example:
579 579 for raw, out_t_part in line_pairs:
580 580 isp.push(raw)
581 581 out_t_parts.append(out_t_part)
582 582
583 583 out = isp.source_reset().rstrip()
584 584 out_t = '\n'.join(out_t_parts).rstrip()
585 585 self.assertEqual(out, out_t)
586 586
587 587
588 588 class BlockIPythonInputTestCase(IPythonInputTestCase):
589 589
590 590 # Deactivate tests that don't make sense for the block mode
591 591 test_push3 = test_split = lambda s: None
592 592
593 593 def setUp(self):
594 594 self.isp = isp.IPythonInputSplitter(input_mode='block')
595 595
596 596 def test_syntax_multiline(self):
597 597 isp = self.isp
598 598 for example in syntax_ml.itervalues():
599 599 raw_parts = []
600 600 out_t_parts = []
601 601 for line_pairs in example:
602 602 for raw, out_t_part in line_pairs:
603 603 raw_parts.append(raw)
604 604 out_t_parts.append(out_t_part)
605 605
606 606 raw = '\n'.join(raw_parts)
607 607 out_t = '\n'.join(out_t_parts)
608 608
609 609 isp.push(raw)
610 610 out = isp.source_reset()
611 611 # Match ignoring trailing whitespace
612 612 self.assertEqual(out.rstrip(), out_t.rstrip())
613 613
614 614
615 615 #-----------------------------------------------------------------------------
616 616 # Main - use as a script, mostly for developer experiments
617 617 #-----------------------------------------------------------------------------
618 618
619 619 if __name__ == '__main__':
620 620 # A simple demo for interactive experimentation. This code will not get
621 621 # picked up by any test suite.
622 622 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
623 623
624 624 # configure here the syntax to use, prompt and whether to autoindent
625 625 #isp, start_prompt = InputSplitter(), '>>> '
626 626 isp, start_prompt = IPythonInputSplitter(), 'In> '
627 627
628 628 autoindent = True
629 629 #autoindent = False
630 630
631 631 try:
632 632 while True:
633 633 prompt = start_prompt
634 634 while isp.push_accepts_more():
635 635 indent = ' '*isp.indent_spaces
636 636 if autoindent:
637 637 line = indent + raw_input(prompt+indent)
638 638 else:
639 639 line = raw_input(prompt)
640 640 isp.push(line)
641 641 prompt = '... '
642 642
643 643 # Here we just return input so we can use it in a test suite, but a
644 644 # real interpreter would instead send it for execution somewhere.
645 645 #src = isp.source; raise EOFError # dbg
646 646 src = isp.source_reset()
647 647 print 'Input source was:\n', src
648 648 except EOFError:
649 649 print 'Bye'
@@ -1,547 +1,552
1 1 #!/usr/bin/env python
2 2 """A simple interactive kernel that talks to a frontend over 0MQ.
3 3
4 4 Things to do:
5 5
6 6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 7 call set_parent on all the PUB objects with the message about to be executed.
8 8 * Implement random port and security key logic.
9 9 * Implement control messages.
10 10 * Implement event loop and poll version.
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Standard library imports.
19 19 import __builtin__
20 20 import sys
21 21 import time
22 22 import traceback
23 23
24 24 # System library imports.
25 25 import zmq
26 26
27 27 # Local imports.
28 28 from IPython.config.configurable import Configurable
29 29 from IPython.utils import io
30 30 from IPython.utils.jsonutil import json_clean
31 31 from IPython.lib import pylabtools
32 32 from IPython.utils.traitlets import Instance, Float
33 33 from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \
34 34 start_kernel
35 35 from iostream import OutStream
36 36 from session import Session, Message
37 37 from zmqshell import ZMQInteractiveShell
38 38
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Main kernel class
42 42 #-----------------------------------------------------------------------------
43 43
44 44 class Kernel(Configurable):
45 45
46 46 #---------------------------------------------------------------------------
47 47 # Kernel interface
48 48 #---------------------------------------------------------------------------
49 49
50 50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 51 session = Instance(Session)
52 52 reply_socket = Instance('zmq.Socket')
53 53 pub_socket = Instance('zmq.Socket')
54 54 req_socket = Instance('zmq.Socket')
55 55
56 56 # Private interface
57 57
58 58 # Time to sleep after flushing the stdout/err buffers in each execute
59 59 # cycle. While this introduces a hard limit on the minimal latency of the
60 60 # execute cycle, it helps prevent output synchronization problems for
61 61 # clients.
62 62 # Units are in seconds. The minimum zmq latency on local host is probably
63 63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 64 # a little if it's not enough after more interactive testing.
65 65 _execute_sleep = Float(0.0005, config=True)
66 66
67 67 # Frequency of the kernel's event loop.
68 68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 69 # adapt to milliseconds.
70 70 _poll_interval = Float(0.05, config=True)
71 71
72 72 def __init__(self, **kwargs):
73 73 super(Kernel, self).__init__(**kwargs)
74 74
75 75 # Initialize the InteractiveShell subclass
76 76 self.shell = ZMQInteractiveShell.instance()
77 77 self.shell.displayhook.session = self.session
78 78 self.shell.displayhook.pub_socket = self.pub_socket
79 79
80 80 # TMP - hack while developing
81 81 self.shell._reply_content = None
82 82
83 83 # Build dict of handlers for message types
84 84 msg_types = [ 'execute_request', 'complete_request',
85 85 'object_info_request', 'history_request' ]
86 86 self.handlers = {}
87 87 for msg_type in msg_types:
88 88 self.handlers[msg_type] = getattr(self, msg_type)
89 89
90 90 def do_one_iteration(self):
91 91 """Do one iteration of the kernel's evaluation loop.
92 92 """
93 93 try:
94 94 ident = self.reply_socket.recv(zmq.NOBLOCK)
95 95 except zmq.ZMQError, e:
96 96 if e.errno == zmq.EAGAIN:
97 97 return
98 98 else:
99 99 raise
100 100 # FIXME: Bug in pyzmq/zmq?
101 101 # assert self.reply_socket.rcvmore(), "Missing message part."
102 102 msg = self.reply_socket.recv_json()
103 103
104 104 # Print some info about this message and leave a '--->' marker, so it's
105 105 # easier to trace visually the message chain when debugging. Each
106 106 # handler prints its message at the end.
107 107 # Eventually we'll move these from stdout to a logger.
108 108 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
109 109 io.raw_print(' Content: ', msg['content'],
110 110 '\n --->\n ', sep='', end='')
111 111
112 112 # Find and call actual handler for message
113 113 handler = self.handlers.get(msg['msg_type'], None)
114 114 if handler is None:
115 115 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
116 116 else:
117 117 handler(ident, msg)
118 118
119 119 # Check whether we should exit, in case the incoming message set the
120 120 # exit flag on
121 121 if self.shell.exit_now:
122 122 io.raw_print('\nExiting IPython kernel...')
123 123 # We do a normal, clean exit, which allows any actions registered
124 124 # via atexit (such as history saving) to take place.
125 125 sys.exit(0)
126 126
127 127
128 128 def start(self):
129 129 """ Start the kernel main loop.
130 130 """
131 131 while True:
132 132 time.sleep(self._poll_interval)
133 133 self.do_one_iteration()
134 134
135 135 #---------------------------------------------------------------------------
136 136 # Kernel request handlers
137 137 #---------------------------------------------------------------------------
138 138
139 139 def _publish_pyin(self, code, parent):
140 140 """Publish the code request on the pyin stream."""
141 141
142 142 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
143 143 self.pub_socket.send_json(pyin_msg)
144 144
145 145 def execute_request(self, ident, parent):
146 146 try:
147 147 content = parent[u'content']
148 148 code = content[u'code']
149 149 silent = content[u'silent']
150 150 except:
151 151 io.raw_print_err("Got bad msg: ")
152 152 io.raw_print_err(Message(parent))
153 153 return
154 154
155 155 shell = self.shell # we'll need this a lot here
156 156
157 157 # Replace raw_input. Note that is not sufficient to replace
158 158 # raw_input in the user namespace.
159 159 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
160 160 __builtin__.raw_input = raw_input
161 161
162 162 # Set the parent message of the display hook and out streams.
163 163 shell.displayhook.set_parent(parent)
164 164 sys.stdout.set_parent(parent)
165 165 sys.stderr.set_parent(parent)
166 166
167 167 # Re-broadcast our input for the benefit of listening clients, and
168 168 # start computing output
169 169 if not silent:
170 170 self._publish_pyin(code, parent)
171 171
172 172 reply_content = {}
173 173 try:
174 174 if silent:
175 175 # runcode uses 'exec' mode, so no displayhook will fire, and it
176 176 # doesn't call logging or history manipulations. Print
177 177 # statements in that code will obviously still execute.
178 178 shell.runcode(code)
179 179 else:
180 180 # FIXME: runlines calls the exception handler itself.
181 181 shell._reply_content = None
182 shell.runlines(code)
182
183 # Experimental: cell mode! Test more before turning into
184 # default and removing the hacks around runlines.
185 shell.run_cell(code)
186 # For now leave this here until we're sure we can stop using it
187 #shell.runlines(code)
183 188 except:
184 189 status = u'error'
185 190 # FIXME: this code right now isn't being used yet by default,
186 191 # because the runlines() call above directly fires off exception
187 192 # reporting. This code, therefore, is only active in the scenario
188 193 # where runlines itself has an unhandled exception. We need to
189 194 # uniformize this, for all exception construction to come from a
190 195 # single location in the codbase.
191 196 etype, evalue, tb = sys.exc_info()
192 197 tb_list = traceback.format_exception(etype, evalue, tb)
193 198 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
194 199 else:
195 200 status = u'ok'
196 201 reply_content[u'payload'] = shell.payload_manager.read_payload()
197 202 # Be agressive about clearing the payload because we don't want
198 203 # it to sit in memory until the next execute_request comes in.
199 204 shell.payload_manager.clear_payload()
200 205
201 206 reply_content[u'status'] = status
202 207 # Compute the execution counter so clients can display prompts
203 208 reply_content['execution_count'] = shell.displayhook.prompt_count
204 209
205 210 # FIXME - fish exception info out of shell, possibly left there by
206 211 # runlines. We'll need to clean up this logic later.
207 212 if shell._reply_content is not None:
208 213 reply_content.update(shell._reply_content)
209 214
210 215 # At this point, we can tell whether the main code execution succeeded
211 216 # or not. If it did, we proceed to evaluate user_variables/expressions
212 217 if reply_content['status'] == 'ok':
213 218 reply_content[u'user_variables'] = \
214 219 shell.get_user_variables(content[u'user_variables'])
215 220 reply_content[u'user_expressions'] = \
216 221 shell.eval_expressions(content[u'user_expressions'])
217 222 else:
218 223 # If there was an error, don't even try to compute variables or
219 224 # expressions
220 225 reply_content[u'user_variables'] = {}
221 226 reply_content[u'user_expressions'] = {}
222 227
223 228 # Send the reply.
224 229 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
225 230 io.raw_print(reply_msg)
226 231
227 232 # Flush output before sending the reply.
228 233 sys.stdout.flush()
229 234 sys.stderr.flush()
230 235 # FIXME: on rare occasions, the flush doesn't seem to make it to the
231 236 # clients... This seems to mitigate the problem, but we definitely need
232 237 # to better understand what's going on.
233 238 if self._execute_sleep:
234 239 time.sleep(self._execute_sleep)
235 240
236 241 self.reply_socket.send(ident, zmq.SNDMORE)
237 242 self.reply_socket.send_json(reply_msg)
238 243 if reply_msg['content']['status'] == u'error':
239 244 self._abort_queue()
240 245
241 246 def complete_request(self, ident, parent):
242 247 txt, matches = self._complete(parent)
243 248 matches = {'matches' : matches,
244 249 'matched_text' : txt,
245 250 'status' : 'ok'}
246 251 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
247 252 matches, parent, ident)
248 253 io.raw_print(completion_msg)
249 254
250 255 def object_info_request(self, ident, parent):
251 256 object_info = self.shell.object_inspect(parent['content']['oname'])
252 257 # Before we send this object over, we turn it into a dict and we scrub
253 258 # it for JSON usage
254 259 oinfo = json_clean(object_info._asdict())
255 260 msg = self.session.send(self.reply_socket, 'object_info_reply',
256 261 oinfo, parent, ident)
257 262 io.raw_print(msg)
258 263
259 264 def history_request(self, ident, parent):
260 265 output = parent['content']['output']
261 266 index = parent['content']['index']
262 267 raw = parent['content']['raw']
263 268 hist = self.shell.get_history(index=index, raw=raw, output=output)
264 269 content = {'history' : hist}
265 270 msg = self.session.send(self.reply_socket, 'history_reply',
266 271 content, parent, ident)
267 272 io.raw_print(msg)
268 273
269 274 #---------------------------------------------------------------------------
270 275 # Protected interface
271 276 #---------------------------------------------------------------------------
272 277
273 278 def _abort_queue(self):
274 279 while True:
275 280 try:
276 281 ident = self.reply_socket.recv(zmq.NOBLOCK)
277 282 except zmq.ZMQError, e:
278 283 if e.errno == zmq.EAGAIN:
279 284 break
280 285 else:
281 286 assert self.reply_socket.rcvmore(), \
282 287 "Unexpected missing message part."
283 288 msg = self.reply_socket.recv_json()
284 289 io.raw_print("Aborting:\n", Message(msg))
285 290 msg_type = msg['msg_type']
286 291 reply_type = msg_type.split('_')[0] + '_reply'
287 292 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
288 293 io.raw_print(reply_msg)
289 294 self.reply_socket.send(ident,zmq.SNDMORE)
290 295 self.reply_socket.send_json(reply_msg)
291 296 # We need to wait a bit for requests to come in. This can probably
292 297 # be set shorter for true asynchronous clients.
293 298 time.sleep(0.1)
294 299
295 300 def _raw_input(self, prompt, ident, parent):
296 301 # Flush output before making the request.
297 302 sys.stderr.flush()
298 303 sys.stdout.flush()
299 304
300 305 # Send the input request.
301 306 content = dict(prompt=prompt)
302 307 msg = self.session.msg(u'input_request', content, parent)
303 308 self.req_socket.send_json(msg)
304 309
305 310 # Await a response.
306 311 reply = self.req_socket.recv_json()
307 312 try:
308 313 value = reply['content']['value']
309 314 except:
310 315 io.raw_print_err("Got bad raw_input reply: ")
311 316 io.raw_print_err(Message(parent))
312 317 value = ''
313 318 return value
314 319
315 320 def _complete(self, msg):
316 321 c = msg['content']
317 322 try:
318 323 cpos = int(c['cursor_pos'])
319 324 except:
320 325 # If we don't get something that we can convert to an integer, at
321 326 # least attempt the completion guessing the cursor is at the end of
322 327 # the text, if there's any, and otherwise of the line
323 328 cpos = len(c['text'])
324 329 if cpos==0:
325 330 cpos = len(c['line'])
326 331 return self.shell.complete(c['text'], c['line'], cpos)
327 332
328 333 def _object_info(self, context):
329 334 symbol, leftover = self._symbol_from_context(context)
330 335 if symbol is not None and not leftover:
331 336 doc = getattr(symbol, '__doc__', '')
332 337 else:
333 338 doc = ''
334 339 object_info = dict(docstring = doc)
335 340 return object_info
336 341
337 342 def _symbol_from_context(self, context):
338 343 if not context:
339 344 return None, context
340 345
341 346 base_symbol_string = context[0]
342 347 symbol = self.shell.user_ns.get(base_symbol_string, None)
343 348 if symbol is None:
344 349 symbol = __builtin__.__dict__.get(base_symbol_string, None)
345 350 if symbol is None:
346 351 return None, context
347 352
348 353 context = context[1:]
349 354 for i, name in enumerate(context):
350 355 new_symbol = getattr(symbol, name, None)
351 356 if new_symbol is None:
352 357 return symbol, context[i:]
353 358 else:
354 359 symbol = new_symbol
355 360
356 361 return symbol, []
357 362
358 363
359 364 class QtKernel(Kernel):
360 365 """A Kernel subclass with Qt support."""
361 366
362 367 def start(self):
363 368 """Start a kernel with QtPy4 event loop integration."""
364 369
365 370 from PyQt4 import QtGui, QtCore
366 371 from IPython.lib.guisupport import (
367 372 get_app_qt4, start_event_loop_qt4
368 373 )
369 374 self.app = get_app_qt4([" "])
370 375 self.app.setQuitOnLastWindowClosed(False)
371 376 self.timer = QtCore.QTimer()
372 377 self.timer.timeout.connect(self.do_one_iteration)
373 378 # Units for the timer are in milliseconds
374 379 self.timer.start(1000*self._poll_interval)
375 380 start_event_loop_qt4(self.app)
376 381
377 382
378 383 class WxKernel(Kernel):
379 384 """A Kernel subclass with Wx support."""
380 385
381 386 def start(self):
382 387 """Start a kernel with wx event loop support."""
383 388
384 389 import wx
385 390 from IPython.lib.guisupport import start_event_loop_wx
386 391 doi = self.do_one_iteration
387 392 # Wx uses milliseconds
388 393 poll_interval = int(1000*self._poll_interval)
389 394
390 395 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
391 396 # We make the Frame hidden when we create it in the main app below.
392 397 class TimerFrame(wx.Frame):
393 398 def __init__(self, func):
394 399 wx.Frame.__init__(self, None, -1)
395 400 self.timer = wx.Timer(self)
396 401 # Units for the timer are in milliseconds
397 402 self.timer.Start(poll_interval)
398 403 self.Bind(wx.EVT_TIMER, self.on_timer)
399 404 self.func = func
400 405
401 406 def on_timer(self, event):
402 407 self.func()
403 408
404 409 # We need a custom wx.App to create our Frame subclass that has the
405 410 # wx.Timer to drive the ZMQ event loop.
406 411 class IPWxApp(wx.App):
407 412 def OnInit(self):
408 413 self.frame = TimerFrame(doi)
409 414 self.frame.Show(False)
410 415 return True
411 416
412 417 # The redirect=False here makes sure that wx doesn't replace
413 418 # sys.stdout/stderr with its own classes.
414 419 self.app = IPWxApp(redirect=False)
415 420 start_event_loop_wx(self.app)
416 421
417 422
418 423 class TkKernel(Kernel):
419 424 """A Kernel subclass with Tk support."""
420 425
421 426 def start(self):
422 427 """Start a Tk enabled event loop."""
423 428
424 429 import Tkinter
425 430 doi = self.do_one_iteration
426 431 # Tk uses milliseconds
427 432 poll_interval = int(1000*self._poll_interval)
428 433 # For Tkinter, we create a Tk object and call its withdraw method.
429 434 class Timer(object):
430 435 def __init__(self, func):
431 436 self.app = Tkinter.Tk()
432 437 self.app.withdraw()
433 438 self.func = func
434 439
435 440 def on_timer(self):
436 441 self.func()
437 442 self.app.after(poll_interval, self.on_timer)
438 443
439 444 def start(self):
440 445 self.on_timer() # Call it once to get things going.
441 446 self.app.mainloop()
442 447
443 448 self.timer = Timer(doi)
444 449 self.timer.start()
445 450
446 451
447 452 class GTKKernel(Kernel):
448 453 """A Kernel subclass with GTK support."""
449 454
450 455 def start(self):
451 456 """Start the kernel, coordinating with the GTK event loop"""
452 457 from .gui.gtkembed import GTKEmbed
453 458
454 459 gtk_kernel = GTKEmbed(self)
455 460 gtk_kernel.start()
456 461
457 462
458 463 #-----------------------------------------------------------------------------
459 464 # Kernel main and launch functions
460 465 #-----------------------------------------------------------------------------
461 466
462 467 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
463 468 independent=False, pylab=False):
464 469 """Launches a localhost kernel, binding to the specified ports.
465 470
466 471 Parameters
467 472 ----------
468 473 xrep_port : int, optional
469 474 The port to use for XREP channel.
470 475
471 476 pub_port : int, optional
472 477 The port to use for the SUB channel.
473 478
474 479 req_port : int, optional
475 480 The port to use for the REQ (raw input) channel.
476 481
477 482 hb_port : int, optional
478 483 The port to use for the hearbeat REP channel.
479 484
480 485 independent : bool, optional (default False)
481 486 If set, the kernel process is guaranteed to survive if this process
482 487 dies. If not set, an effort is made to ensure that the kernel is killed
483 488 when this process dies. Note that in this case it is still good practice
484 489 to kill kernels manually before exiting.
485 490
486 491 pylab : bool or string, optional (default False)
487 492 If not False, the kernel will be launched with pylab enabled. If a
488 493 string is passed, matplotlib will use the specified backend. Otherwise,
489 494 matplotlib's default backend will be used.
490 495
491 496 Returns
492 497 -------
493 498 A tuple of form:
494 499 (kernel_process, xrep_port, pub_port, req_port)
495 500 where kernel_process is a Popen object and the ports are integers.
496 501 """
497 502 extra_arguments = []
498 503 if pylab:
499 504 extra_arguments.append('--pylab')
500 505 if isinstance(pylab, basestring):
501 506 extra_arguments.append(pylab)
502 507 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
503 508 xrep_port, pub_port, req_port, hb_port,
504 509 independent, extra_arguments)
505 510
506 511
507 512 def main():
508 513 """ The IPython kernel main entry point.
509 514 """
510 515 parser = make_argument_parser()
511 516 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
512 517 const='auto', help = \
513 518 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
514 519 given, the GUI backend is matplotlib's, otherwise use one of: \
515 520 ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].")
516 521 namespace = parser.parse_args()
517 522
518 523 kernel_class = Kernel
519 524
520 525 kernel_classes = {
521 526 'qt' : QtKernel,
522 527 'qt4': QtKernel,
523 528 'payload-svg': Kernel,
524 529 'wx' : WxKernel,
525 530 'tk' : TkKernel,
526 531 'gtk': GTKKernel,
527 532 }
528 533 if namespace.pylab:
529 534 if namespace.pylab == 'auto':
530 535 gui, backend = pylabtools.find_gui_and_backend()
531 536 else:
532 537 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
533 538 kernel_class = kernel_classes.get(gui)
534 539 if kernel_class is None:
535 540 raise ValueError('GUI is not supported: %r' % gui)
536 541 pylabtools.activate_matplotlib(backend)
537 542
538 543 kernel = make_kernel(namespace, kernel_class, OutStream)
539 544
540 545 if namespace.pylab:
541 546 pylabtools.import_pylab(kernel.shell.user_ns)
542 547
543 548 start_kernel(namespace, kernel)
544 549
545 550
546 551 if __name__ == '__main__':
547 552 main()
@@ -1,485 +1,485
1 1 """A ZMQ-based subclass of InteractiveShell.
2 2
3 3 This code is meant to ease the refactoring of the base InteractiveShell into
4 4 something with a cleaner architecture for 2-process use, without actually
5 5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 6 we subclass and override what we want to fix. Once this is working well, we
7 7 can go back to the base class and refactor the code for a cleaner inheritance
8 8 implementation that doesn't rely on so much monkeypatching.
9 9
10 10 But this lets us maintain a fully working IPython as we develop the new
11 11 machinery. This should thus be thought of as scaffolding.
12 12 """
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Stdlib
19 19 import inspect
20 20 import os
21 21 import re
22 22
23 23 # Our own
24 24 from IPython.core.interactiveshell import (
25 25 InteractiveShell, InteractiveShellABC
26 26 )
27 27 from IPython.core.displayhook import DisplayHook
28 28 from IPython.core.macro import Macro
29 from IPython.core.payloadpage import install_payload_page
29 30 from IPython.utils.path import get_py_filename
30 31 from IPython.utils.text import StringTypes
31 32 from IPython.utils.traitlets import Instance, Type, Dict
32 33 from IPython.utils.warn import warn
33 34 from IPython.zmq.session import extract_header
34 from IPython.core.payloadpage import install_payload_page
35 35 from session import Session
36 36
37 37 #-----------------------------------------------------------------------------
38 38 # Globals and side-effects
39 39 #-----------------------------------------------------------------------------
40 40
41 41 # Install the payload version of page.
42 42 install_payload_page()
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # Functions and classes
46 46 #-----------------------------------------------------------------------------
47 47
48 48 class ZMQDisplayHook(DisplayHook):
49 49
50 50 session = Instance(Session)
51 51 pub_socket = Instance('zmq.Socket')
52 52 parent_header = Dict({})
53 53
54 54 def set_parent(self, parent):
55 55 """Set the parent for outbound messages."""
56 56 self.parent_header = extract_header(parent)
57 57
58 58 def start_displayhook(self):
59 59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
60 60
61 61 def write_output_prompt(self):
62 62 """Write the output prompt."""
63 63 if self.do_full_cache:
64 64 self.msg['content']['execution_count'] = self.prompt_count
65 65
66 66 def write_result_repr(self, result_repr):
67 67 self.msg['content']['data'] = result_repr
68 68
69 69 def finish_displayhook(self):
70 70 """Finish up all displayhook activities."""
71 71 self.pub_socket.send_json(self.msg)
72 72 self.msg = None
73 73
74 74
75 75 class ZMQInteractiveShell(InteractiveShell):
76 76 """A subclass of InteractiveShell for ZMQ."""
77 77
78 78 displayhook_class = Type(ZMQDisplayHook)
79 79
80 80 def init_io(self):
81 81 # This will just use sys.stdout and sys.stderr. If you want to
82 82 # override sys.stdout and sys.stderr themselves, you need to do that
83 83 # *before* instantiating this class, because Term holds onto
84 84 # references to the underlying streams.
85 85 import IPython.utils.io
86 86 Term = IPython.utils.io.IOTerm()
87 87 IPython.utils.io.Term = Term
88 88
89 89 def magic_doctest_mode(self,parameter_s=''):
90 90 """Toggle doctest mode on and off.
91 91
92 92 This mode is intended to make IPython behave as much as possible like a
93 93 plain Python shell, from the perspective of how its prompts, exceptions
94 94 and output look. This makes it easy to copy and paste parts of a
95 95 session into doctests. It does so by:
96 96
97 97 - Changing the prompts to the classic ``>>>`` ones.
98 98 - Changing the exception reporting mode to 'Plain'.
99 99 - Disabling pretty-printing of output.
100 100
101 101 Note that IPython also supports the pasting of code snippets that have
102 102 leading '>>>' and '...' prompts in them. This means that you can paste
103 103 doctests from files or docstrings (even if they have leading
104 104 whitespace), and the code will execute correctly. You can then use
105 105 '%history -t' to see the translated history; this will give you the
106 106 input after removal of all the leading prompts and whitespace, which
107 107 can be pasted back into an editor.
108 108
109 109 With these features, you can switch into this mode easily whenever you
110 110 need to do testing and changes to doctests, without having to leave
111 111 your existing IPython session.
112 112 """
113 113
114 114 from IPython.utils.ipstruct import Struct
115 115
116 116 # Shorthands
117 117 shell = self.shell
118 118 # dstore is a data store kept in the instance metadata bag to track any
119 119 # changes we make, so we can undo them later.
120 120 dstore = shell.meta.setdefault('doctest_mode', Struct())
121 121 save_dstore = dstore.setdefault
122 122
123 123 # save a few values we'll need to recover later
124 124 mode = save_dstore('mode', False)
125 125 save_dstore('rc_pprint', shell.pprint)
126 126 save_dstore('xmode', shell.InteractiveTB.mode)
127 127
128 128 if mode == False:
129 129 # turn on
130 130 shell.pprint = False
131 131 shell.magic_xmode('Plain')
132 132 else:
133 133 # turn off
134 134 shell.pprint = dstore.rc_pprint
135 135 shell.magic_xmode(dstore.xmode)
136 136
137 137 # Store new mode and inform on console
138 138 dstore.mode = bool(1-int(mode))
139 139 mode_label = ['OFF','ON'][dstore.mode]
140 140 print('Doctest mode is:', mode_label)
141 141
142 142 # Send the payload back so that clients can modify their prompt display
143 143 payload = dict(
144 144 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
145 145 mode=dstore.mode)
146 146 self.payload_manager.write_payload(payload)
147 147
148 148 def magic_edit(self,parameter_s='',last_call=['','']):
149 149 """Bring up an editor and execute the resulting code.
150 150
151 151 Usage:
152 152 %edit [options] [args]
153 153
154 154 %edit runs IPython's editor hook. The default version of this hook is
155 155 set to call the __IPYTHON__.rc.editor command. This is read from your
156 156 environment variable $EDITOR. If this isn't found, it will default to
157 157 vi under Linux/Unix and to notepad under Windows. See the end of this
158 158 docstring for how to change the editor hook.
159 159
160 160 You can also set the value of this editor via the command line option
161 161 '-editor' or in your ipythonrc file. This is useful if you wish to use
162 162 specifically for IPython an editor different from your typical default
163 163 (and for Windows users who typically don't set environment variables).
164 164
165 165 This command allows you to conveniently edit multi-line code right in
166 166 your IPython session.
167 167
168 168 If called without arguments, %edit opens up an empty editor with a
169 169 temporary file and will execute the contents of this file when you
170 170 close it (don't forget to save it!).
171 171
172 172
173 173 Options:
174 174
175 175 -n <number>: open the editor at a specified line number. By default,
176 176 the IPython editor hook uses the unix syntax 'editor +N filename', but
177 177 you can configure this by providing your own modified hook if your
178 178 favorite editor supports line-number specifications with a different
179 179 syntax.
180 180
181 181 -p: this will call the editor with the same data as the previous time
182 182 it was used, regardless of how long ago (in your current session) it
183 183 was.
184 184
185 185 -r: use 'raw' input. This option only applies to input taken from the
186 186 user's history. By default, the 'processed' history is used, so that
187 187 magics are loaded in their transformed version to valid Python. If
188 188 this option is given, the raw input as typed as the command line is
189 189 used instead. When you exit the editor, it will be executed by
190 190 IPython's own processor.
191 191
192 192 -x: do not execute the edited code immediately upon exit. This is
193 193 mainly useful if you are editing programs which need to be called with
194 194 command line arguments, which you can then do using %run.
195 195
196 196
197 197 Arguments:
198 198
199 199 If arguments are given, the following possibilites exist:
200 200
201 201 - The arguments are numbers or pairs of colon-separated numbers (like
202 202 1 4:8 9). These are interpreted as lines of previous input to be
203 203 loaded into the editor. The syntax is the same of the %macro command.
204 204
205 205 - If the argument doesn't start with a number, it is evaluated as a
206 206 variable and its contents loaded into the editor. You can thus edit
207 207 any string which contains python code (including the result of
208 208 previous edits).
209 209
210 210 - If the argument is the name of an object (other than a string),
211 211 IPython will try to locate the file where it was defined and open the
212 212 editor at the point where it is defined. You can use `%edit function`
213 213 to load an editor exactly at the point where 'function' is defined,
214 214 edit it and have the file be executed automatically.
215 215
216 216 If the object is a macro (see %macro for details), this opens up your
217 217 specified editor with a temporary file containing the macro's data.
218 218 Upon exit, the macro is reloaded with the contents of the file.
219 219
220 220 Note: opening at an exact line is only supported under Unix, and some
221 221 editors (like kedit and gedit up to Gnome 2.8) do not understand the
222 222 '+NUMBER' parameter necessary for this feature. Good editors like
223 223 (X)Emacs, vi, jed, pico and joe all do.
224 224
225 225 - If the argument is not found as a variable, IPython will look for a
226 226 file with that name (adding .py if necessary) and load it into the
227 227 editor. It will execute its contents with execfile() when you exit,
228 228 loading any code in the file into your interactive namespace.
229 229
230 230 After executing your code, %edit will return as output the code you
231 231 typed in the editor (except when it was an existing file). This way
232 232 you can reload the code in further invocations of %edit as a variable,
233 233 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
234 234 the output.
235 235
236 236 Note that %edit is also available through the alias %ed.
237 237
238 238 This is an example of creating a simple function inside the editor and
239 239 then modifying it. First, start up the editor:
240 240
241 241 In [1]: ed
242 242 Editing... done. Executing edited code...
243 243 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
244 244
245 245 We can then call the function foo():
246 246
247 247 In [2]: foo()
248 248 foo() was defined in an editing session
249 249
250 250 Now we edit foo. IPython automatically loads the editor with the
251 251 (temporary) file where foo() was previously defined:
252 252
253 253 In [3]: ed foo
254 254 Editing... done. Executing edited code...
255 255
256 256 And if we call foo() again we get the modified version:
257 257
258 258 In [4]: foo()
259 259 foo() has now been changed!
260 260
261 261 Here is an example of how to edit a code snippet successive
262 262 times. First we call the editor:
263 263
264 264 In [5]: ed
265 265 Editing... done. Executing edited code...
266 266 hello
267 267 Out[5]: "print 'hello'n"
268 268
269 269 Now we call it again with the previous output (stored in _):
270 270
271 271 In [6]: ed _
272 272 Editing... done. Executing edited code...
273 273 hello world
274 274 Out[6]: "print 'hello world'n"
275 275
276 276 Now we call it with the output #8 (stored in _8, also as Out[8]):
277 277
278 278 In [7]: ed _8
279 279 Editing... done. Executing edited code...
280 280 hello again
281 281 Out[7]: "print 'hello again'n"
282 282
283 283
284 284 Changing the default editor hook:
285 285
286 286 If you wish to write your own editor hook, you can put it in a
287 287 configuration file which you load at startup time. The default hook
288 288 is defined in the IPython.core.hooks module, and you can use that as a
289 289 starting example for further modifications. That file also has
290 290 general instructions on how to set a new hook for use once you've
291 291 defined it."""
292 292
293 293 # FIXME: This function has become a convoluted mess. It needs a
294 294 # ground-up rewrite with clean, simple logic.
295 295
296 296 def make_filename(arg):
297 297 "Make a filename from the given args"
298 298 try:
299 299 filename = get_py_filename(arg)
300 300 except IOError:
301 301 if args.endswith('.py'):
302 302 filename = arg
303 303 else:
304 304 filename = None
305 305 return filename
306 306
307 307 # custom exceptions
308 308 class DataIsObject(Exception): pass
309 309
310 310 opts,args = self.parse_options(parameter_s,'prn:')
311 311 # Set a few locals from the options for convenience:
312 312 opts_p = opts.has_key('p')
313 313 opts_r = opts.has_key('r')
314 314
315 315 # Default line number value
316 316 lineno = opts.get('n',None)
317 317 if lineno is not None:
318 318 try:
319 319 lineno = int(lineno)
320 320 except:
321 321 warn("The -n argument must be an integer.")
322 322 return
323 323
324 324 if opts_p:
325 325 args = '_%s' % last_call[0]
326 326 if not self.shell.user_ns.has_key(args):
327 327 args = last_call[1]
328 328
329 329 # use last_call to remember the state of the previous call, but don't
330 330 # let it be clobbered by successive '-p' calls.
331 331 try:
332 332 last_call[0] = self.shell.displayhook.prompt_count
333 333 if not opts_p:
334 334 last_call[1] = parameter_s
335 335 except:
336 336 pass
337 337
338 338 # by default this is done with temp files, except when the given
339 339 # arg is a filename
340 340 use_temp = 1
341 341
342 342 if re.match(r'\d',args):
343 343 # Mode where user specifies ranges of lines, like in %macro.
344 344 # This means that you can't edit files whose names begin with
345 345 # numbers this way. Tough.
346 346 ranges = args.split()
347 347 data = ''.join(self.extract_input_slices(ranges,opts_r))
348 348 elif args.endswith('.py'):
349 349 filename = make_filename(args)
350 350 data = ''
351 351 use_temp = 0
352 352 elif args:
353 353 try:
354 354 # Load the parameter given as a variable. If not a string,
355 355 # process it as an object instead (below)
356 356
357 357 #print '*** args',args,'type',type(args) # dbg
358 358 data = eval(args,self.shell.user_ns)
359 359 if not type(data) in StringTypes:
360 360 raise DataIsObject
361 361
362 362 except (NameError,SyntaxError):
363 363 # given argument is not a variable, try as a filename
364 364 filename = make_filename(args)
365 365 if filename is None:
366 366 warn("Argument given (%s) can't be found as a variable "
367 367 "or as a filename." % args)
368 368 return
369 369
370 370 data = ''
371 371 use_temp = 0
372 372 except DataIsObject:
373 373
374 374 # macros have a special edit function
375 375 if isinstance(data,Macro):
376 376 self._edit_macro(args,data)
377 377 return
378 378
379 379 # For objects, try to edit the file where they are defined
380 380 try:
381 381 filename = inspect.getabsfile(data)
382 382 if 'fakemodule' in filename.lower() and inspect.isclass(data):
383 383 # class created by %edit? Try to find source
384 384 # by looking for method definitions instead, the
385 385 # __module__ in those classes is FakeModule.
386 386 attrs = [getattr(data, aname) for aname in dir(data)]
387 387 for attr in attrs:
388 388 if not inspect.ismethod(attr):
389 389 continue
390 390 filename = inspect.getabsfile(attr)
391 391 if filename and 'fakemodule' not in filename.lower():
392 392 # change the attribute to be the edit target instead
393 393 data = attr
394 394 break
395 395
396 396 datafile = 1
397 397 except TypeError:
398 398 filename = make_filename(args)
399 399 datafile = 1
400 400 warn('Could not find file where `%s` is defined.\n'
401 401 'Opening a file named `%s`' % (args,filename))
402 402 # Now, make sure we can actually read the source (if it was in
403 403 # a temp file it's gone by now).
404 404 if datafile:
405 405 try:
406 406 if lineno is None:
407 407 lineno = inspect.getsourcelines(data)[1]
408 408 except IOError:
409 409 filename = make_filename(args)
410 410 if filename is None:
411 411 warn('The file `%s` where `%s` was defined cannot '
412 412 'be read.' % (filename,data))
413 413 return
414 414 use_temp = 0
415 415 else:
416 416 data = ''
417 417
418 418 if use_temp:
419 419 filename = self.shell.mktempfile(data)
420 420 print('IPython will make a temporary file named:', filename)
421 421
422 422 # Make sure we send to the client an absolute path, in case the working
423 423 # directory of client and kernel don't match
424 424 filename = os.path.abspath(filename)
425 425
426 426 payload = {
427 427 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
428 428 'filename' : filename,
429 429 'line_number' : lineno
430 430 }
431 431 self.payload_manager.write_payload(payload)
432 432
433 433 def magic_gui(self, *args, **kwargs):
434 434 raise NotImplementedError('GUI support must be enabled in command line options.')
435 435
436 436 def magic_pylab(self, *args, **kwargs):
437 437 raise NotImplementedError('pylab support must be enabled in commandl in options.')
438 438
439 439 def auto_rewrite_input(self, cmd):
440 440 """Called to show the auto-rewritten input for autocall and friends.
441 441
442 442 FIXME: this payload is currently not correctly processed by the
443 443 frontend.
444 444 """
445 445 new = self.displayhook.prompt1.auto_rewrite() + cmd
446 446 payload = dict(
447 447 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
448 448 transformed_input=new,
449 449 )
450 450 self.payload_manager.write_payload(payload)
451 451
452 452 def ask_exit(self):
453 453 """Engage the exit actions."""
454 454 payload = dict(
455 455 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
456 456 exit=True,
457 457 )
458 458 self.payload_manager.write_payload(payload)
459 459
460 460 def _showtraceback(self, etype, evalue, stb):
461 461
462 462 exc_content = {
463 463 u'traceback' : stb,
464 464 u'ename' : unicode(etype.__name__),
465 465 u'evalue' : unicode(evalue)
466 466 }
467 467
468 468 dh = self.displayhook
469 469 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
470 470 # Send exception info over pub socket for other clients than the caller
471 471 # to pick up
472 472 dh.pub_socket.send_json(exc_msg)
473 473
474 474 # FIXME - Hack: store exception info in shell object. Right now, the
475 475 # caller is reading this info after the fact, we need to fix this logic
476 476 # to remove this hack. Even uglier, we need to store the error status
477 477 # here, because in the main loop, the logic that sets it is being
478 478 # skipped because runlines swallows the exceptions.
479 479 exc_content[u'status'] = u'error'
480 480 self._reply_content = exc_content
481 481 # /FIXME
482 482
483 483 return exc_content
484 484
485 485 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now