##// END OF EJS Templates
Simplify - call ast.parse inline, rather than via a separate method.
Thomas Kluyver -
Show More
@@ -1,1030 +1,1013 b''
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 from __future__ import print_function
64 64
65 65 #-----------------------------------------------------------------------------
66 66 # Imports
67 67 #-----------------------------------------------------------------------------
68 68 # stdlib
69 69 import ast
70 70 import codeop
71 71 import re
72 72 import sys
73 73
74 74 # IPython modules
75 75 from IPython.utils.text import make_quoted_expr
76 76
77 77 #-----------------------------------------------------------------------------
78 78 # Globals
79 79 #-----------------------------------------------------------------------------
80 80
81 81 # The escape sequences that define the syntax transformations IPython will
82 82 # apply to user input. These can NOT be just changed here: many regular
83 83 # expressions and other parts of the code may use their hardcoded values, and
84 84 # for all intents and purposes they constitute the 'IPython syntax', so they
85 85 # should be considered fixed.
86 86
87 87 ESC_SHELL = '!' # Send line to underlying system shell
88 88 ESC_SH_CAP = '!!' # Send line to system shell and capture output
89 89 ESC_HELP = '?' # Find information about object
90 90 ESC_HELP2 = '??' # Find extra-detailed information about object
91 91 ESC_MAGIC = '%' # Call magic function
92 92 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
93 93 ESC_QUOTE2 = ';' # Quote all args as a single string, call
94 94 ESC_PAREN = '/' # Call first argument with rest of line as arguments
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Utilities
98 98 #-----------------------------------------------------------------------------
99 99
100 100 # FIXME: These are general-purpose utilities that later can be moved to the
101 101 # general ward. Kept here for now because we're being very strict about test
102 102 # coverage with this code, and this lets us ensure that we keep 100% coverage
103 103 # while developing.
104 104
105 105 # compiled regexps for autoindent management
106 106 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
107 107 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
108 108
109 109 # regexp to match pure comment lines so we don't accidentally insert 'if 1:'
110 110 # before pure comments
111 111 comment_line_re = re.compile('^\s*\#')
112 112
113 113
114 114 def num_ini_spaces(s):
115 115 """Return the number of initial spaces in a string.
116 116
117 117 Note that tabs are counted as a single space. For now, we do *not* support
118 118 mixing of tabs and spaces in the user's input.
119 119
120 120 Parameters
121 121 ----------
122 122 s : string
123 123
124 124 Returns
125 125 -------
126 126 n : int
127 127 """
128 128
129 129 ini_spaces = ini_spaces_re.match(s)
130 130 if ini_spaces:
131 131 return ini_spaces.end()
132 132 else:
133 133 return 0
134 134
135 135
136 136 def remove_comments(src):
137 137 """Remove all comments from input source.
138 138
139 139 Note: comments are NOT recognized inside of strings!
140 140
141 141 Parameters
142 142 ----------
143 143 src : string
144 144 A single or multiline input string.
145 145
146 146 Returns
147 147 -------
148 148 String with all Python comments removed.
149 149 """
150 150
151 151 return re.sub('#.*', '', src)
152 152
153 153
154 154 def get_input_encoding():
155 155 """Return the default standard input encoding.
156 156
157 157 If sys.stdin has no encoding, 'ascii' is returned."""
158 158 # There are strange environments for which sys.stdin.encoding is None. We
159 159 # ensure that a valid encoding is returned.
160 160 encoding = getattr(sys.stdin, 'encoding', None)
161 161 if encoding is None:
162 162 encoding = 'ascii'
163 163 return encoding
164 164
165 165 #-----------------------------------------------------------------------------
166 166 # Classes and functions for normal Python syntax handling
167 167 #-----------------------------------------------------------------------------
168 168
169 169 # HACK! This implementation, written by Robert K a while ago using the
170 170 # compiler module, is more robust than the other one below, but it expects its
171 171 # input to be pure python (no ipython syntax). For now we're using it as a
172 172 # second-pass splitter after the first pass transforms the input to pure
173 173 # python.
174 174
175 175 def split_blocks(python):
176 176 """ Split multiple lines of code into discrete commands that can be
177 177 executed singly.
178 178
179 179 Parameters
180 180 ----------
181 181 python : str
182 182 Pure, exec'able Python code.
183 183
184 184 Returns
185 185 -------
186 186 commands : list of str
187 187 Separate commands that can be exec'ed independently.
188 188 """
189 189 # compiler.parse treats trailing spaces after a newline as a
190 190 # SyntaxError. This is different than codeop.CommandCompiler, which
191 191 # will compile the trailng spaces just fine. We simply strip any
192 192 # trailing whitespace off. Passing a string with trailing whitespace
193 193 # to exec will fail however. There seems to be some inconsistency in
194 194 # how trailing whitespace is handled, but this seems to work.
195 195 python_ori = python # save original in case we bail on error
196 196 python = python.strip()
197 197
198 198 # The compiler module will parse the code into an abstract syntax tree.
199 199 # This has a bug with str("a\nb"), but not str("""a\nb""")!!!
200 200 try:
201 201 code_ast = ast.parse(python)
202 202 except:
203 203 return [python_ori]
204 204
205 205 # Uncomment to help debug the ast tree
206 206 # for n in code_ast.body:
207 207 # print n.lineno,'->',n
208 208
209 209 # Each separate command is available by iterating over ast.node. The
210 210 # lineno attribute is the line number (1-indexed) beginning the commands
211 211 # suite.
212 212 # lines ending with ";" yield a Discard Node that doesn't have a lineno
213 213 # attribute. These nodes can and should be discarded. But there are
214 214 # other situations that cause Discard nodes that shouldn't be discarded.
215 215 # We might eventually discover other cases where lineno is None and have
216 216 # to put in a more sophisticated test.
217 217 linenos = [x.lineno-1 for x in code_ast.body if x.lineno is not None]
218 218
219 219 # When we finally get the slices, we will need to slice all the way to
220 220 # the end even though we don't have a line number for it. Fortunately,
221 221 # None does the job nicely.
222 222 linenos.append(None)
223 223
224 224 # Same problem at the other end: sometimes the ast tree has its
225 225 # first complete statement not starting on line 0. In this case
226 226 # we might miss part of it. This fixes ticket 266993. Thanks Gael!
227 227 linenos[0] = 0
228 228
229 229 lines = python.splitlines()
230 230
231 231 # Create a list of atomic commands.
232 232 cmds = []
233 233 for i, j in zip(linenos[:-1], linenos[1:]):
234 234 cmd = lines[i:j]
235 235 if cmd:
236 236 cmds.append('\n'.join(cmd)+'\n')
237 237
238 238 return cmds
239 239
240 240
241 241 class InputSplitter(object):
242 242 """An object that can split Python source input in executable blocks.
243 243
244 244 This object is designed to be used in one of two basic modes:
245 245
246 246 1. By feeding it python source line-by-line, using :meth:`push`. In this
247 247 mode, it will return on each push whether the currently pushed code
248 248 could be executed already. In addition, it provides a method called
249 249 :meth:`push_accepts_more` that can be used to query whether more input
250 250 can be pushed into a single interactive block.
251 251
252 252 2. By calling :meth:`split_blocks` with a single, multiline Python string,
253 253 that is then split into blocks each of which can be executed
254 254 interactively as a single statement.
255 255
256 256 This is a simple example of how an interactive terminal-based client can use
257 257 this tool::
258 258
259 259 isp = InputSplitter()
260 260 while isp.push_accepts_more():
261 261 indent = ' '*isp.indent_spaces
262 262 prompt = '>>> ' + indent
263 263 line = indent + raw_input(prompt)
264 264 isp.push(line)
265 265 print 'Input source was:\n', isp.source_reset(),
266 266 """
267 267 # Number of spaces of indentation computed from input that has been pushed
268 268 # so far. This is the attributes callers should query to get the current
269 269 # indentation level, in order to provide auto-indent facilities.
270 270 indent_spaces = 0
271 271 # String, indicating the default input encoding. It is computed by default
272 272 # at initialization time via get_input_encoding(), but it can be reset by a
273 273 # client with specific knowledge of the encoding.
274 274 encoding = ''
275 275 # String where the current full source input is stored, properly encoded.
276 276 # Reading this attribute is the normal way of querying the currently pushed
277 277 # source code, that has been properly encoded.
278 278 source = ''
279 279 # Code object corresponding to the current source. It is automatically
280 280 # synced to the source, so it can be queried at any time to obtain the code
281 281 # object; it will be None if the source doesn't compile to valid Python.
282 282 code = None
283 283 # Input mode
284 284 input_mode = 'line'
285 285
286 286 # Private attributes
287 287
288 288 # List with lines of input accumulated so far
289 289 _buffer = None
290 290 # Command compiler
291 291 _compile = None
292 292 # Mark when input has changed indentation all the way back to flush-left
293 293 _full_dedent = False
294 294 # Boolean indicating whether the current block is complete
295 295 _is_complete = None
296 296
297 297 def __init__(self, input_mode=None):
298 298 """Create a new InputSplitter instance.
299 299
300 300 Parameters
301 301 ----------
302 302 input_mode : str
303 303
304 304 One of ['line', 'cell']; default is 'line'.
305 305
306 306 The input_mode parameter controls how new inputs are used when fed via
307 307 the :meth:`push` method:
308 308
309 309 - 'line': meant for line-oriented clients, inputs are appended one at a
310 310 time to the internal buffer and the whole buffer is compiled.
311 311
312 312 - 'cell': meant for clients that can edit multi-line 'cells' of text at
313 313 a time. A cell can contain one or more blocks that can be compile in
314 314 'single' mode by Python. In this mode, each new input new input
315 315 completely replaces all prior inputs. Cell mode is thus equivalent
316 316 to prepending a full reset() to every push() call.
317 317 """
318 318 self._buffer = []
319 319 self._compile = codeop.CommandCompiler()
320 320 self.encoding = get_input_encoding()
321 321 self.input_mode = InputSplitter.input_mode if input_mode is None \
322 322 else input_mode
323 323
324 324 def reset(self):
325 325 """Reset the input buffer and associated state."""
326 326 self.indent_spaces = 0
327 327 self._buffer[:] = []
328 328 self.source = ''
329 329 self.code = None
330 330 self._is_complete = False
331 331 self._full_dedent = False
332 332
333 333 def source_reset(self):
334 334 """Return the input source and perform a full reset.
335 335 """
336 336 out = self.source
337 337 self.reset()
338 338 return out
339 339
340 340 def push(self, lines):
341 341 """Push one or more lines of input.
342 342
343 343 This stores the given lines and returns a status code indicating
344 344 whether the code forms a complete Python block or not.
345 345
346 346 Any exceptions generated in compilation are swallowed, but if an
347 347 exception was produced, the method returns True.
348 348
349 349 Parameters
350 350 ----------
351 351 lines : string
352 352 One or more lines of Python input.
353 353
354 354 Returns
355 355 -------
356 356 is_complete : boolean
357 357 True if the current input source (the result of the current input
358 358 plus prior inputs) forms a complete Python execution block. Note that
359 359 this value is also stored as a private attribute (_is_complete), so it
360 360 can be queried at any time.
361 361 """
362 362 if self.input_mode == 'cell':
363 363 self.reset()
364 364
365 365 self._store(lines)
366 366 source = self.source
367 367
368 368 # Before calling _compile(), reset the code object to None so that if an
369 369 # exception is raised in compilation, we don't mislead by having
370 370 # inconsistent code/source attributes.
371 371 self.code, self._is_complete = None, None
372 372
373 373 # Honor termination lines properly
374 374 if source.rstrip().endswith('\\'):
375 375 return False
376 376
377 377 self._update_indent(lines)
378 378 try:
379 379 self.code = self._compile(source)
380 380 # Invalid syntax can produce any of a number of different errors from
381 381 # inside the compiler, so we have to catch them all. Syntax errors
382 382 # immediately produce a 'ready' block, so the invalid Python can be
383 383 # sent to the kernel for evaluation with possible ipython
384 384 # special-syntax conversion.
385 385 except (SyntaxError, OverflowError, ValueError, TypeError,
386 386 MemoryError):
387 387 self._is_complete = True
388 388 else:
389 389 # Compilation didn't produce any exceptions (though it may not have
390 390 # given a complete code object)
391 391 self._is_complete = self.code is not None
392 392
393 393 return self._is_complete
394 394
395 395 def push_accepts_more(self):
396 396 """Return whether a block of interactive input can accept more input.
397 397
398 398 This method is meant to be used by line-oriented frontends, who need to
399 399 guess whether a block is complete or not based solely on prior and
400 400 current input lines. The InputSplitter considers it has a complete
401 401 interactive block and will not accept more input only when either a
402 402 SyntaxError is raised, or *all* of the following are true:
403 403
404 404 1. The input compiles to a complete statement.
405 405
406 406 2. The indentation level is flush-left (because if we are indented,
407 407 like inside a function definition or for loop, we need to keep
408 408 reading new input).
409 409
410 410 3. There is one extra line consisting only of whitespace.
411 411
412 412 Because of condition #3, this method should be used only by
413 413 *line-oriented* frontends, since it means that intermediate blank lines
414 414 are not allowed in function definitions (or any other indented block).
415 415
416 416 Block-oriented frontends that have a separate keyboard event to
417 417 indicate execution should use the :meth:`split_blocks` method instead.
418 418
419 419 If the current input produces a syntax error, this method immediately
420 420 returns False but does *not* raise the syntax error exception, as
421 421 typically clients will want to send invalid syntax to an execution
422 422 backend which might convert the invalid syntax into valid Python via
423 423 one of the dynamic IPython mechanisms.
424 424 """
425 425
426 426 # With incomplete input, unconditionally accept more
427 427 if not self._is_complete:
428 428 return True
429 429
430 430 # If we already have complete input and we're flush left, the answer
431 431 # depends. In line mode, if there hasn't been any indentation,
432 432 # that's it. If we've come back from some indentation, we need
433 433 # the blank final line to finish.
434 434 # In cell mode, we need to check how many blocks the input so far
435 435 # compiles into, because if there's already more than one full
436 436 # independent block of input, then the client has entered full
437 437 # 'cell' mode and is feeding lines that each is complete. In this
438 438 # case we should then keep accepting. The Qt terminal-like console
439 439 # does precisely this, to provide the convenience of terminal-like
440 440 # input of single expressions, but allowing the user (with a
441 441 # separate keystroke) to switch to 'cell' mode and type multiple
442 442 # expressions in one shot.
443 443 if self.indent_spaces==0:
444 444 if self.input_mode=='line':
445 445 if not self._full_dedent:
446 446 return False
447 447 else:
448 448 try:
449 nodes = self.ast_nodes()
449 code_ast = ast.parse(u''.join(self._buffer))
450 450 except Exception:
451 451 return False
452 452 else:
453 if len(nodes) == 1:
453 if len(code_ast.body) == 1:
454 454 return False
455 455
456 456 # When input is complete, then termination is marked by an extra blank
457 457 # line at the end.
458 458 last_line = self.source.splitlines()[-1]
459 459 return bool(last_line and not last_line.isspace())
460 460
461 461 def split_blocks(self, lines):
462 462 """Split a multiline string into multiple input blocks.
463 463
464 464 Note: this method starts by performing a full reset().
465 465
466 466 Parameters
467 467 ----------
468 468 lines : str
469 469 A possibly multiline string.
470 470
471 471 Returns
472 472 -------
473 473 blocks : list
474 474 A list of strings, each possibly multiline. Each string corresponds
475 475 to a single block that can be compiled in 'single' mode (unless it
476 476 has a syntax error)."""
477 477
478 478 # This code is fairly delicate. If you make any changes here, make
479 479 # absolutely sure that you do run the full test suite and ALL tests
480 480 # pass.
481 481
482 482 self.reset()
483 483 blocks = []
484 484
485 485 # Reversed copy so we can use pop() efficiently and consume the input
486 486 # as a stack
487 487 lines = lines.splitlines()[::-1]
488 488 # Outer loop over all input
489 489 while lines:
490 490 #print 'Current lines:', lines # dbg
491 491 # Inner loop to build each block
492 492 while True:
493 493 # Safety exit from inner loop
494 494 if not lines:
495 495 break
496 496 # Grab next line but don't push it yet
497 497 next_line = lines.pop()
498 498 # Blank/empty lines are pushed as-is
499 499 if not next_line or next_line.isspace():
500 500 self.push(next_line)
501 501 continue
502 502
503 503 # Check indentation changes caused by the *next* line
504 504 indent_spaces, _full_dedent = self._find_indent(next_line)
505 505
506 506 # If the next line causes a dedent, it can be for two differnt
507 507 # reasons: either an explicit de-dent by the user or a
508 508 # return/raise/pass statement. These MUST be handled
509 509 # separately:
510 510 #
511 511 # 1. the first case is only detected when the actual explicit
512 512 # dedent happens, and that would be the *first* line of a *new*
513 513 # block. Thus, we must put the line back into the input buffer
514 514 # so that it starts a new block on the next pass.
515 515 #
516 516 # 2. the second case is detected in the line before the actual
517 517 # dedent happens, so , we consume the line and we can break out
518 518 # to start a new block.
519 519
520 520 # Case 1, explicit dedent causes a break.
521 521 # Note: check that we weren't on the very last line, else we'll
522 522 # enter an infinite loop adding/removing the last line.
523 523 if _full_dedent and lines and not next_line.startswith(' '):
524 524 lines.append(next_line)
525 525 break
526 526
527 527 # Otherwise any line is pushed
528 528 self.push(next_line)
529 529
530 530 # Case 2, full dedent with full block ready:
531 531 if _full_dedent or \
532 532 self.indent_spaces==0 and not self.push_accepts_more():
533 533 break
534 534 # Form the new block with the current source input
535 535 blocks.append(self.source_reset())
536 536
537 537 #return blocks
538 538 # HACK!!! Now that our input is in blocks but guaranteed to be pure
539 539 # python syntax, feed it back a second time through the AST-based
540 540 # splitter, which is more accurate than ours.
541 541 return split_blocks(''.join(blocks))
542 542
543 def ast_nodes(self, lines=None):
544 """Turn the lines into a list of AST nodes.
545
546 Parameters
547 ----------
548 lines : str
549 A (possibly multiline) string of Python code. If None (default), it
550 will use the InputSplitter's current code buffer.
551
552 Returns
553 -------
554 A list of AST (abstract syntax tree) nodes representing the code.
555 """
556 if lines is None:
557 lines = u"".join(self._buffer)
558 return ast.parse(lines).body
559
560 543 #------------------------------------------------------------------------
561 544 # Private interface
562 545 #------------------------------------------------------------------------
563 546
564 547 def _find_indent(self, line):
565 548 """Compute the new indentation level for a single line.
566 549
567 550 Parameters
568 551 ----------
569 552 line : str
570 553 A single new line of non-whitespace, non-comment Python input.
571 554
572 555 Returns
573 556 -------
574 557 indent_spaces : int
575 558 New value for the indent level (it may be equal to self.indent_spaces
576 559 if indentation doesn't change.
577 560
578 561 full_dedent : boolean
579 562 Whether the new line causes a full flush-left dedent.
580 563 """
581 564 indent_spaces = self.indent_spaces
582 565 full_dedent = self._full_dedent
583 566
584 567 inisp = num_ini_spaces(line)
585 568 if inisp < indent_spaces:
586 569 indent_spaces = inisp
587 570 if indent_spaces <= 0:
588 571 #print 'Full dedent in text',self.source # dbg
589 572 full_dedent = True
590 573
591 574 if line[-1] == ':':
592 575 indent_spaces += 4
593 576 elif dedent_re.match(line):
594 577 indent_spaces -= 4
595 578 if indent_spaces <= 0:
596 579 full_dedent = True
597 580
598 581 # Safety
599 582 if indent_spaces < 0:
600 583 indent_spaces = 0
601 584 #print 'safety' # dbg
602 585
603 586 return indent_spaces, full_dedent
604 587
605 588 def _update_indent(self, lines):
606 589 for line in remove_comments(lines).splitlines():
607 590 if line and not line.isspace():
608 591 self.indent_spaces, self._full_dedent = self._find_indent(line)
609 592
610 593 def _store(self, lines, buffer=None, store='source'):
611 594 """Store one or more lines of input.
612 595
613 596 If input lines are not newline-terminated, a newline is automatically
614 597 appended."""
615 598
616 599 if buffer is None:
617 600 buffer = self._buffer
618 601
619 602 if lines.endswith('\n'):
620 603 buffer.append(lines)
621 604 else:
622 605 buffer.append(lines+'\n')
623 606 setattr(self, store, self._set_source(buffer))
624 607
625 608 def _set_source(self, buffer):
626 609 return u''.join(buffer)
627 610
628 611
629 612 #-----------------------------------------------------------------------------
630 613 # Functions and classes for IPython-specific syntactic support
631 614 #-----------------------------------------------------------------------------
632 615
633 616 # RegExp for splitting line contents into pre-char//first word-method//rest.
634 617 # For clarity, each group in on one line.
635 618
636 619 line_split = re.compile("""
637 620 ^(\s*) # any leading space
638 621 ([,;/%]|!!?|\?\??) # escape character or characters
639 622 \s*(%?[\w\.\*]*) # function/method, possibly with leading %
640 623 # to correctly treat things like '?%magic'
641 624 (\s+.*$|$) # rest of line
642 625 """, re.VERBOSE)
643 626
644 627
645 628 def split_user_input(line):
646 629 """Split user input into early whitespace, esc-char, function part and rest.
647 630
648 631 This is currently handles lines with '=' in them in a very inconsistent
649 632 manner.
650 633
651 634 Examples
652 635 ========
653 636 >>> split_user_input('x=1')
654 637 ('', '', 'x=1', '')
655 638 >>> split_user_input('?')
656 639 ('', '?', '', '')
657 640 >>> split_user_input('??')
658 641 ('', '??', '', '')
659 642 >>> split_user_input(' ?')
660 643 (' ', '?', '', '')
661 644 >>> split_user_input(' ??')
662 645 (' ', '??', '', '')
663 646 >>> split_user_input('??x')
664 647 ('', '??', 'x', '')
665 648 >>> split_user_input('?x=1')
666 649 ('', '', '?x=1', '')
667 650 >>> split_user_input('!ls')
668 651 ('', '!', 'ls', '')
669 652 >>> split_user_input(' !ls')
670 653 (' ', '!', 'ls', '')
671 654 >>> split_user_input('!!ls')
672 655 ('', '!!', 'ls', '')
673 656 >>> split_user_input(' !!ls')
674 657 (' ', '!!', 'ls', '')
675 658 >>> split_user_input(',ls')
676 659 ('', ',', 'ls', '')
677 660 >>> split_user_input(';ls')
678 661 ('', ';', 'ls', '')
679 662 >>> split_user_input(' ;ls')
680 663 (' ', ';', 'ls', '')
681 664 >>> split_user_input('f.g(x)')
682 665 ('', '', 'f.g(x)', '')
683 666 >>> split_user_input('f.g (x)')
684 667 ('', '', 'f.g', '(x)')
685 668 >>> split_user_input('?%hist')
686 669 ('', '?', '%hist', '')
687 670 >>> split_user_input('?x*')
688 671 ('', '?', 'x*', '')
689 672 """
690 673 match = line_split.match(line)
691 674 if match:
692 675 lspace, esc, fpart, rest = match.groups()
693 676 else:
694 677 # print "match failed for line '%s'" % line
695 678 try:
696 679 fpart, rest = line.split(None, 1)
697 680 except ValueError:
698 681 # print "split failed for line '%s'" % line
699 682 fpart, rest = line,''
700 683 lspace = re.match('^(\s*)(.*)', line).groups()[0]
701 684 esc = ''
702 685
703 686 # fpart has to be a valid python identifier, so it better be only pure
704 687 # ascii, no unicode:
705 688 try:
706 689 fpart = fpart.encode('ascii')
707 690 except UnicodeEncodeError:
708 691 lspace = unicode(lspace)
709 692 rest = fpart + u' ' + rest
710 693 fpart = u''
711 694
712 695 #print 'line:<%s>' % line # dbg
713 696 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
714 697 return lspace, esc, fpart.strip(), rest.lstrip()
715 698
716 699
717 700 # The escaped translators ALL receive a line where their own escape has been
718 701 # stripped. Only '?' is valid at the end of the line, all others can only be
719 702 # placed at the start.
720 703
721 704 class LineInfo(object):
722 705 """A single line of input and associated info.
723 706
724 707 This is a utility class that mostly wraps the output of
725 708 :func:`split_user_input` into a convenient object to be passed around
726 709 during input transformations.
727 710
728 711 Includes the following as properties:
729 712
730 713 line
731 714 The original, raw line
732 715
733 716 lspace
734 717 Any early whitespace before actual text starts.
735 718
736 719 esc
737 720 The initial esc character (or characters, for double-char escapes like
738 721 '??' or '!!').
739 722
740 723 fpart
741 724 The 'function part', which is basically the maximal initial sequence
742 725 of valid python identifiers and the '.' character. This is what is
743 726 checked for alias and magic transformations, used for auto-calling,
744 727 etc.
745 728
746 729 rest
747 730 Everything else on the line.
748 731 """
749 732 def __init__(self, line):
750 733 self.line = line
751 734 self.lspace, self.esc, self.fpart, self.rest = \
752 735 split_user_input(line)
753 736
754 737 def __str__(self):
755 738 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
756 739 self.fpart, self.rest)
757 740
758 741
759 742 # Transformations of the special syntaxes that don't rely on an explicit escape
760 743 # character but instead on patterns on the input line
761 744
762 745 # The core transformations are implemented as standalone functions that can be
763 746 # tested and validated in isolation. Each of these uses a regexp, we
764 747 # pre-compile these and keep them close to each function definition for clarity
765 748
766 749 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
767 750 r'\s*=\s*!\s*(?P<cmd>.*)')
768 751
769 752 def transform_assign_system(line):
770 753 """Handle the `files = !ls` syntax."""
771 754 m = _assign_system_re.match(line)
772 755 if m is not None:
773 756 cmd = m.group('cmd')
774 757 lhs = m.group('lhs')
775 758 expr = make_quoted_expr(cmd)
776 759 new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr)
777 760 return new_line
778 761 return line
779 762
780 763
781 764 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
782 765 r'\s*=\s*%\s*(?P<cmd>.*)')
783 766
784 767 def transform_assign_magic(line):
785 768 """Handle the `a = %who` syntax."""
786 769 m = _assign_magic_re.match(line)
787 770 if m is not None:
788 771 cmd = m.group('cmd')
789 772 lhs = m.group('lhs')
790 773 expr = make_quoted_expr(cmd)
791 774 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
792 775 return new_line
793 776 return line
794 777
795 778
796 779 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
797 780
798 781 def transform_classic_prompt(line):
799 782 """Handle inputs that start with '>>> ' syntax."""
800 783
801 784 if not line or line.isspace():
802 785 return line
803 786 m = _classic_prompt_re.match(line)
804 787 if m:
805 788 return line[len(m.group(0)):]
806 789 else:
807 790 return line
808 791
809 792
810 793 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
811 794
812 795 def transform_ipy_prompt(line):
813 796 """Handle inputs that start classic IPython prompt syntax."""
814 797
815 798 if not line or line.isspace():
816 799 return line
817 800 #print 'LINE: %r' % line # dbg
818 801 m = _ipy_prompt_re.match(line)
819 802 if m:
820 803 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
821 804 return line[len(m.group(0)):]
822 805 else:
823 806 return line
824 807
825 808
826 809 class EscapedTransformer(object):
827 810 """Class to transform lines that are explicitly escaped out."""
828 811
829 812 def __init__(self):
830 813 tr = { ESC_SHELL : self._tr_system,
831 814 ESC_SH_CAP : self._tr_system2,
832 815 ESC_HELP : self._tr_help,
833 816 ESC_HELP2 : self._tr_help,
834 817 ESC_MAGIC : self._tr_magic,
835 818 ESC_QUOTE : self._tr_quote,
836 819 ESC_QUOTE2 : self._tr_quote2,
837 820 ESC_PAREN : self._tr_paren }
838 821 self.tr = tr
839 822
840 823 # Support for syntax transformations that use explicit escapes typed by the
841 824 # user at the beginning of a line
842 825 @staticmethod
843 826 def _tr_system(line_info):
844 827 "Translate lines escaped with: !"
845 828 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
846 829 return '%sget_ipython().system(%s)' % (line_info.lspace,
847 830 make_quoted_expr(cmd))
848 831
849 832 @staticmethod
850 833 def _tr_system2(line_info):
851 834 "Translate lines escaped with: !!"
852 835 cmd = line_info.line.lstrip()[2:]
853 836 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
854 837 make_quoted_expr(cmd))
855 838
856 839 @staticmethod
857 840 def _tr_help(line_info):
858 841 "Translate lines escaped with: ?/??"
859 842 # A naked help line should just fire the intro help screen
860 843 if not line_info.line[1:]:
861 844 return 'get_ipython().show_usage()'
862 845
863 846 # There may be one or two '?' at the end, move them to the front so that
864 847 # the rest of the logic can assume escapes are at the start
865 848 l_ori = line_info
866 849 line = line_info.line
867 850 if line.endswith('?'):
868 851 line = line[-1] + line[:-1]
869 852 if line.endswith('?'):
870 853 line = line[-1] + line[:-1]
871 854 line_info = LineInfo(line)
872 855
873 856 # From here on, simply choose which level of detail to get, and
874 857 # special-case the psearch syntax
875 858 pinfo = 'pinfo' # default
876 859 if '*' in line_info.line:
877 860 pinfo = 'psearch'
878 861 elif line_info.esc == '??':
879 862 pinfo = 'pinfo2'
880 863
881 864 tpl = '%sget_ipython().magic(u"%s %s")'
882 865 return tpl % (line_info.lspace, pinfo,
883 866 ' '.join([line_info.fpart, line_info.rest]).strip())
884 867
885 868 @staticmethod
886 869 def _tr_magic(line_info):
887 870 "Translate lines escaped with: %"
888 871 tpl = '%sget_ipython().magic(%s)'
889 872 cmd = make_quoted_expr(' '.join([line_info.fpart,
890 873 line_info.rest]).strip())
891 874 return tpl % (line_info.lspace, cmd)
892 875
893 876 @staticmethod
894 877 def _tr_quote(line_info):
895 878 "Translate lines escaped with: ,"
896 879 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
897 880 '", "'.join(line_info.rest.split()) )
898 881
899 882 @staticmethod
900 883 def _tr_quote2(line_info):
901 884 "Translate lines escaped with: ;"
902 885 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
903 886 line_info.rest)
904 887
905 888 @staticmethod
906 889 def _tr_paren(line_info):
907 890 "Translate lines escaped with: /"
908 891 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
909 892 ", ".join(line_info.rest.split()))
910 893
911 894 def __call__(self, line):
912 895 """Class to transform lines that are explicitly escaped out.
913 896
914 897 This calls the above _tr_* static methods for the actual line
915 898 translations."""
916 899
917 900 # Empty lines just get returned unmodified
918 901 if not line or line.isspace():
919 902 return line
920 903
921 904 # Get line endpoints, where the escapes can be
922 905 line_info = LineInfo(line)
923 906
924 907 # If the escape is not at the start, only '?' needs to be special-cased.
925 908 # All other escapes are only valid at the start
926 909 if not line_info.esc in self.tr:
927 910 if line.endswith(ESC_HELP):
928 911 return self._tr_help(line_info)
929 912 else:
930 913 # If we don't recognize the escape, don't modify the line
931 914 return line
932 915
933 916 return self.tr[line_info.esc](line_info)
934 917
935 918
936 919 # A function-looking object to be used by the rest of the code. The purpose of
937 920 # the class in this case is to organize related functionality, more than to
938 921 # manage state.
939 922 transform_escaped = EscapedTransformer()
940 923
941 924
942 925 class IPythonInputSplitter(InputSplitter):
943 926 """An input splitter that recognizes all of IPython's special syntax."""
944 927
945 928 # String with raw, untransformed input.
946 929 source_raw = ''
947 930
948 931 # Private attributes
949 932
950 933 # List with lines of raw input accumulated so far.
951 934 _buffer_raw = None
952 935
953 936 def __init__(self, input_mode=None):
954 937 InputSplitter.__init__(self, input_mode)
955 938 self._buffer_raw = []
956 939
957 940 def reset(self):
958 941 """Reset the input buffer and associated state."""
959 942 InputSplitter.reset(self)
960 943 self._buffer_raw[:] = []
961 944 self.source_raw = ''
962 945
963 946 def source_raw_reset(self):
964 947 """Return input and raw source and perform a full reset.
965 948 """
966 949 out = self.source
967 950 out_r = self.source_raw
968 951 self.reset()
969 952 return out, out_r
970 953
971 954 def push(self, lines):
972 955 """Push one or more lines of IPython input.
973 956 """
974 957 if not lines:
975 958 return super(IPythonInputSplitter, self).push(lines)
976 959
977 960 # We must ensure all input is pure unicode
978 961 if type(lines)==str:
979 962 lines = lines.decode(self.encoding)
980 963
981 964 lines_list = lines.splitlines()
982 965
983 966 transforms = [transform_escaped, transform_assign_system,
984 967 transform_assign_magic, transform_ipy_prompt,
985 968 transform_classic_prompt]
986 969
987 970 # Transform logic
988 971 #
989 972 # We only apply the line transformers to the input if we have either no
990 973 # input yet, or complete input, or if the last line of the buffer ends
991 974 # with ':' (opening an indented block). This prevents the accidental
992 975 # transformation of escapes inside multiline expressions like
993 976 # triple-quoted strings or parenthesized expressions.
994 977 #
995 978 # The last heuristic, while ugly, ensures that the first line of an
996 979 # indented block is correctly transformed.
997 980 #
998 981 # FIXME: try to find a cleaner approach for this last bit.
999 982
1000 983 # If we were in 'block' mode, since we're going to pump the parent
1001 984 # class by hand line by line, we need to temporarily switch out to
1002 985 # 'line' mode, do a single manual reset and then feed the lines one
1003 986 # by one. Note that this only matters if the input has more than one
1004 987 # line.
1005 988 changed_input_mode = False
1006 989
1007 990 if self.input_mode == 'cell':
1008 991 self.reset()
1009 992 changed_input_mode = True
1010 993 saved_input_mode = 'cell'
1011 994 self.input_mode = 'line'
1012 995
1013 996 # Store raw source before applying any transformations to it. Note
1014 997 # that this must be done *after* the reset() call that would otherwise
1015 998 # flush the buffer.
1016 999 self._store(lines, self._buffer_raw, 'source_raw')
1017 1000
1018 1001 try:
1019 1002 push = super(IPythonInputSplitter, self).push
1020 1003 for line in lines_list:
1021 1004 if self._is_complete or not self._buffer or \
1022 1005 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
1023 1006 for f in transforms:
1024 1007 line = f(line)
1025 1008
1026 1009 out = push(line)
1027 1010 finally:
1028 1011 if changed_input_mode:
1029 1012 self.input_mode = saved_input_mode
1030 1013 return out
@@ -1,2695 +1,2695 b''
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-2011 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 ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
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.compilerop import CachingCompiler
44 44 from IPython.core.display_trap import DisplayTrap
45 45 from IPython.core.displayhook import DisplayHook
46 46 from IPython.core.displaypub import DisplayPublisher
47 47 from IPython.core.error import TryNext, UsageError
48 48 from IPython.core.extensions import ExtensionManager
49 49 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 50 from IPython.core.formatters import DisplayFormatter
51 51 from IPython.core.history import HistoryManager
52 52 from IPython.core.inputsplitter import IPythonInputSplitter
53 53 from IPython.core.logger import Logger
54 54 from IPython.core.macro import Macro
55 55 from IPython.core.magic import Magic
56 56 from IPython.core.payload import PayloadManager
57 57 from IPython.core.plugin import PluginManager
58 58 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
59 59 from IPython.external.Itpl import ItplNS
60 60 from IPython.utils import PyColorize
61 61 from IPython.utils import io
62 62 from IPython.utils.doctestreload import doctest_reload
63 63 from IPython.utils.io import ask_yes_no, rprint
64 64 from IPython.utils.ipstruct import Struct
65 65 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
66 66 from IPython.utils.pickleshare import PickleShareDB
67 67 from IPython.utils.process import system, getoutput
68 68 from IPython.utils.strdispatch import StrDispatch
69 69 from IPython.utils.syspathcontext import prepended_to_syspath
70 70 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
71 71 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
72 72 List, Unicode, Instance, Type)
73 73 from IPython.utils.warn import warn, error, fatal
74 74 import IPython.core.hooks
75 75
76 76 #-----------------------------------------------------------------------------
77 77 # Globals
78 78 #-----------------------------------------------------------------------------
79 79
80 80 # compiled regexps for autoindent management
81 81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 82
83 83 #-----------------------------------------------------------------------------
84 84 # Utilities
85 85 #-----------------------------------------------------------------------------
86 86
87 87 # store the builtin raw_input globally, and use this always, in case user code
88 88 # overwrites it (like wx.py.PyShell does)
89 89 raw_input_original = raw_input
90 90
91 91 def softspace(file, newvalue):
92 92 """Copied from code.py, to remove the dependency"""
93 93
94 94 oldvalue = 0
95 95 try:
96 96 oldvalue = file.softspace
97 97 except AttributeError:
98 98 pass
99 99 try:
100 100 file.softspace = newvalue
101 101 except (AttributeError, TypeError):
102 102 # "attribute-less object" or "read-only attributes"
103 103 pass
104 104 return oldvalue
105 105
106 106
107 107 def no_op(*a, **kw): pass
108 108
109 109 class SpaceInInput(Exception): pass
110 110
111 111 class Bunch: pass
112 112
113 113
114 114 def get_default_colors():
115 115 if sys.platform=='darwin':
116 116 return "LightBG"
117 117 elif os.name=='nt':
118 118 return 'Linux'
119 119 else:
120 120 return 'Linux'
121 121
122 122
123 123 class SeparateStr(Str):
124 124 """A Str subclass to validate separate_in, separate_out, etc.
125 125
126 126 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
127 127 """
128 128
129 129 def validate(self, obj, value):
130 130 if value == '0': value = ''
131 131 value = value.replace('\\n','\n')
132 132 return super(SeparateStr, self).validate(obj, value)
133 133
134 134 class MultipleInstanceError(Exception):
135 135 pass
136 136
137 137 class ReadlineNoRecord(object):
138 138 """Context manager to execute some code, then reload readline history
139 139 so that interactive input to the code doesn't appear when pressing up."""
140 140 def __init__(self, shell):
141 141 self.shell = shell
142 142 self._nested_level = 0
143 143
144 144 def __enter__(self):
145 145 if self._nested_level == 0:
146 146 self.orig_length = self.current_length()
147 147 self.readline_tail = self.get_readline_tail()
148 148 self._nested_level += 1
149 149
150 150 def __exit__(self, type, value, traceback):
151 151 self._nested_level -= 1
152 152 if self._nested_level == 0:
153 153 # Try clipping the end if it's got longer
154 154 e = self.current_length() - self.orig_length
155 155 if e > 0:
156 156 for _ in range(e):
157 157 self.shell.readline.remove_history_item(self.orig_length)
158 158
159 159 # If it still doesn't match, just reload readline history.
160 160 if self.current_length() != self.orig_length \
161 161 or self.get_readline_tail() != self.readline_tail:
162 162 self.shell.refill_readline_hist()
163 163 # Returning False will cause exceptions to propagate
164 164 return False
165 165
166 166 def current_length(self):
167 167 return self.shell.readline.get_current_history_length()
168 168
169 169 def get_readline_tail(self, n=10):
170 170 """Get the last n items in readline history."""
171 171 end = self.shell.readline.get_current_history_length() + 1
172 172 start = max(end-n, 1)
173 173 ghi = self.shell.readline.get_history_item
174 174 return [ghi(x) for x in range(start, end)]
175 175
176 176
177 177 #-----------------------------------------------------------------------------
178 178 # Main IPython class
179 179 #-----------------------------------------------------------------------------
180 180
181 181 class InteractiveShell(Configurable, Magic):
182 182 """An enhanced, interactive shell for Python."""
183 183
184 184 _instance = None
185 185 autocall = Enum((0,1,2), default_value=1, config=True)
186 186 # TODO: remove all autoindent logic and put into frontends.
187 187 # We can't do this yet because even runlines uses the autoindent.
188 188 autoindent = CBool(True, config=True)
189 189 automagic = CBool(True, config=True)
190 190 cache_size = Int(1000, config=True)
191 191 color_info = CBool(True, config=True)
192 192 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
193 193 default_value=get_default_colors(), config=True)
194 194 debug = CBool(False, config=True)
195 195 deep_reload = CBool(False, config=True)
196 196 display_formatter = Instance(DisplayFormatter)
197 197 displayhook_class = Type(DisplayHook)
198 198 display_pub_class = Type(DisplayPublisher)
199 199
200 200 exit_now = CBool(False)
201 201 # Monotonically increasing execution counter
202 202 execution_count = Int(1)
203 203 filename = Unicode("<ipython console>")
204 204 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
205 205
206 206 # Input splitter, to split entire cells of input into either individual
207 207 # interactive statements or whole blocks.
208 208 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
209 209 (), {})
210 210 logstart = CBool(False, config=True)
211 211 logfile = Unicode('', config=True)
212 212 logappend = Unicode('', config=True)
213 213 object_info_string_level = Enum((0,1,2), default_value=0,
214 214 config=True)
215 215 pdb = CBool(False, config=True)
216 216
217 217 profile = Unicode('', config=True)
218 218 prompt_in1 = Str('In [\\#]: ', config=True)
219 219 prompt_in2 = Str(' .\\D.: ', config=True)
220 220 prompt_out = Str('Out[\\#]: ', config=True)
221 221 prompts_pad_left = CBool(True, config=True)
222 222 quiet = CBool(False, config=True)
223 223
224 224 history_length = Int(10000, config=True)
225 225
226 226 # The readline stuff will eventually be moved to the terminal subclass
227 227 # but for now, we can't do that as readline is welded in everywhere.
228 228 readline_use = CBool(True, config=True)
229 229 readline_merge_completions = CBool(True, config=True)
230 230 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
231 231 readline_remove_delims = Str('-/~', config=True)
232 232 readline_parse_and_bind = List([
233 233 'tab: complete',
234 234 '"\C-l": clear-screen',
235 235 'set show-all-if-ambiguous on',
236 236 '"\C-o": tab-insert',
237 237 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
238 238 # crash IPython.
239 239 '"\M-o": "\d\d\d\d"',
240 240 '"\M-I": "\d\d\d\d"',
241 241 '"\C-r": reverse-search-history',
242 242 '"\C-s": forward-search-history',
243 243 '"\C-p": history-search-backward',
244 244 '"\C-n": history-search-forward',
245 245 '"\e[A": history-search-backward',
246 246 '"\e[B": history-search-forward',
247 247 '"\C-k": kill-line',
248 248 '"\C-u": unix-line-discard',
249 249 ], allow_none=False, config=True)
250 250
251 251 # TODO: this part of prompt management should be moved to the frontends.
252 252 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
253 253 separate_in = SeparateStr('\n', config=True)
254 254 separate_out = SeparateStr('', config=True)
255 255 separate_out2 = SeparateStr('', config=True)
256 256 wildcards_case_sensitive = CBool(True, config=True)
257 257 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
258 258 default_value='Context', config=True)
259 259
260 260 # Subcomponents of InteractiveShell
261 261 alias_manager = Instance('IPython.core.alias.AliasManager')
262 262 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
263 263 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
264 264 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
265 265 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
266 266 plugin_manager = Instance('IPython.core.plugin.PluginManager')
267 267 payload_manager = Instance('IPython.core.payload.PayloadManager')
268 268 history_manager = Instance('IPython.core.history.HistoryManager')
269 269
270 270 # Private interface
271 271 _post_execute = set()
272 272
273 273 def __init__(self, config=None, ipython_dir=None,
274 274 user_ns=None, user_global_ns=None,
275 275 custom_exceptions=((), None)):
276 276
277 277 # This is where traits with a config_key argument are updated
278 278 # from the values on config.
279 279 super(InteractiveShell, self).__init__(config=config)
280 280
281 281 # These are relatively independent and stateless
282 282 self.init_ipython_dir(ipython_dir)
283 283 self.init_instance_attrs()
284 284 self.init_environment()
285 285
286 286 # Create namespaces (user_ns, user_global_ns, etc.)
287 287 self.init_create_namespaces(user_ns, user_global_ns)
288 288 # This has to be done after init_create_namespaces because it uses
289 289 # something in self.user_ns, but before init_sys_modules, which
290 290 # is the first thing to modify sys.
291 291 # TODO: When we override sys.stdout and sys.stderr before this class
292 292 # is created, we are saving the overridden ones here. Not sure if this
293 293 # is what we want to do.
294 294 self.save_sys_module_state()
295 295 self.init_sys_modules()
296 296
297 297 # While we're trying to have each part of the code directly access what
298 298 # it needs without keeping redundant references to objects, we have too
299 299 # much legacy code that expects ip.db to exist.
300 300 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
301 301
302 302 self.init_history()
303 303 self.init_encoding()
304 304 self.init_prefilter()
305 305
306 306 Magic.__init__(self, self)
307 307
308 308 self.init_syntax_highlighting()
309 309 self.init_hooks()
310 310 self.init_pushd_popd_magic()
311 311 # self.init_traceback_handlers use to be here, but we moved it below
312 312 # because it and init_io have to come after init_readline.
313 313 self.init_user_ns()
314 314 self.init_logger()
315 315 self.init_alias()
316 316 self.init_builtins()
317 317
318 318 # pre_config_initialization
319 319
320 320 # The next section should contain everything that was in ipmaker.
321 321 self.init_logstart()
322 322
323 323 # The following was in post_config_initialization
324 324 self.init_inspector()
325 325 # init_readline() must come before init_io(), because init_io uses
326 326 # readline related things.
327 327 self.init_readline()
328 328 # init_completer must come after init_readline, because it needs to
329 329 # know whether readline is present or not system-wide to configure the
330 330 # completers, since the completion machinery can now operate
331 331 # independently of readline (e.g. over the network)
332 332 self.init_completer()
333 333 # TODO: init_io() needs to happen before init_traceback handlers
334 334 # because the traceback handlers hardcode the stdout/stderr streams.
335 335 # This logic in in debugger.Pdb and should eventually be changed.
336 336 self.init_io()
337 337 self.init_traceback_handlers(custom_exceptions)
338 338 self.init_prompts()
339 339 self.init_display_formatter()
340 340 self.init_display_pub()
341 341 self.init_displayhook()
342 342 self.init_reload_doctest()
343 343 self.init_magics()
344 344 self.init_pdb()
345 345 self.init_extension_manager()
346 346 self.init_plugin_manager()
347 347 self.init_payload()
348 348 self.hooks.late_startup_hook()
349 349 atexit.register(self.atexit_operations)
350 350
351 351 @classmethod
352 352 def instance(cls, *args, **kwargs):
353 353 """Returns a global InteractiveShell instance."""
354 354 if cls._instance is None:
355 355 inst = cls(*args, **kwargs)
356 356 # Now make sure that the instance will also be returned by
357 357 # the subclasses instance attribute.
358 358 for subclass in cls.mro():
359 359 if issubclass(cls, subclass) and \
360 360 issubclass(subclass, InteractiveShell):
361 361 subclass._instance = inst
362 362 else:
363 363 break
364 364 if isinstance(cls._instance, cls):
365 365 return cls._instance
366 366 else:
367 367 raise MultipleInstanceError(
368 368 'Multiple incompatible subclass instances of '
369 369 'InteractiveShell are being created.'
370 370 )
371 371
372 372 @classmethod
373 373 def initialized(cls):
374 374 return hasattr(cls, "_instance")
375 375
376 376 def get_ipython(self):
377 377 """Return the currently running IPython instance."""
378 378 return self
379 379
380 380 #-------------------------------------------------------------------------
381 381 # Trait changed handlers
382 382 #-------------------------------------------------------------------------
383 383
384 384 def _ipython_dir_changed(self, name, new):
385 385 if not os.path.isdir(new):
386 386 os.makedirs(new, mode = 0777)
387 387
388 388 def set_autoindent(self,value=None):
389 389 """Set the autoindent flag, checking for readline support.
390 390
391 391 If called with no arguments, it acts as a toggle."""
392 392
393 393 if not self.has_readline:
394 394 if os.name == 'posix':
395 395 warn("The auto-indent feature requires the readline library")
396 396 self.autoindent = 0
397 397 return
398 398 if value is None:
399 399 self.autoindent = not self.autoindent
400 400 else:
401 401 self.autoindent = value
402 402
403 403 #-------------------------------------------------------------------------
404 404 # init_* methods called by __init__
405 405 #-------------------------------------------------------------------------
406 406
407 407 def init_ipython_dir(self, ipython_dir):
408 408 if ipython_dir is not None:
409 409 self.ipython_dir = ipython_dir
410 410 self.config.Global.ipython_dir = self.ipython_dir
411 411 return
412 412
413 413 if hasattr(self.config.Global, 'ipython_dir'):
414 414 self.ipython_dir = self.config.Global.ipython_dir
415 415 else:
416 416 self.ipython_dir = get_ipython_dir()
417 417
418 418 # All children can just read this
419 419 self.config.Global.ipython_dir = self.ipython_dir
420 420
421 421 def init_instance_attrs(self):
422 422 self.more = False
423 423
424 424 # command compiler
425 425 self.compile = CachingCompiler()
426 426
427 427 # User input buffers
428 428 # NOTE: these variables are slated for full removal, once we are 100%
429 429 # sure that the new execution logic is solid. We will delte runlines,
430 430 # push_line and these buffers, as all input will be managed by the
431 431 # frontends via an inputsplitter instance.
432 432 self.buffer = []
433 433 self.buffer_raw = []
434 434
435 435 # Make an empty namespace, which extension writers can rely on both
436 436 # existing and NEVER being used by ipython itself. This gives them a
437 437 # convenient location for storing additional information and state
438 438 # their extensions may require, without fear of collisions with other
439 439 # ipython names that may develop later.
440 440 self.meta = Struct()
441 441
442 442 # Object variable to store code object waiting execution. This is
443 443 # used mainly by the multithreaded shells, but it can come in handy in
444 444 # other situations. No need to use a Queue here, since it's a single
445 445 # item which gets cleared once run.
446 446 self.code_to_run = None
447 447
448 448 # Temporary files used for various purposes. Deleted at exit.
449 449 self.tempfiles = []
450 450
451 451 # Keep track of readline usage (later set by init_readline)
452 452 self.has_readline = False
453 453
454 454 # keep track of where we started running (mainly for crash post-mortem)
455 455 # This is not being used anywhere currently.
456 456 self.starting_dir = os.getcwd()
457 457
458 458 # Indentation management
459 459 self.indent_current_nsp = 0
460 460
461 461 def init_environment(self):
462 462 """Any changes we need to make to the user's environment."""
463 463 pass
464 464
465 465 def init_encoding(self):
466 466 # Get system encoding at startup time. Certain terminals (like Emacs
467 467 # under Win32 have it set to None, and we need to have a known valid
468 468 # encoding to use in the raw_input() method
469 469 try:
470 470 self.stdin_encoding = sys.stdin.encoding or 'ascii'
471 471 except AttributeError:
472 472 self.stdin_encoding = 'ascii'
473 473
474 474 def init_syntax_highlighting(self):
475 475 # Python source parser/formatter for syntax highlighting
476 476 pyformat = PyColorize.Parser().format
477 477 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
478 478
479 479 def init_pushd_popd_magic(self):
480 480 # for pushd/popd management
481 481 try:
482 482 self.home_dir = get_home_dir()
483 483 except HomeDirError, msg:
484 484 fatal(msg)
485 485
486 486 self.dir_stack = []
487 487
488 488 def init_logger(self):
489 489 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
490 490 logmode='rotate')
491 491
492 492 def init_logstart(self):
493 493 """Initialize logging in case it was requested at the command line.
494 494 """
495 495 if self.logappend:
496 496 self.magic_logstart(self.logappend + ' append')
497 497 elif self.logfile:
498 498 self.magic_logstart(self.logfile)
499 499 elif self.logstart:
500 500 self.magic_logstart()
501 501
502 502 def init_builtins(self):
503 503 self.builtin_trap = BuiltinTrap(shell=self)
504 504
505 505 def init_inspector(self):
506 506 # Object inspector
507 507 self.inspector = oinspect.Inspector(oinspect.InspectColors,
508 508 PyColorize.ANSICodeColors,
509 509 'NoColor',
510 510 self.object_info_string_level)
511 511
512 512 def init_io(self):
513 513 # This will just use sys.stdout and sys.stderr. If you want to
514 514 # override sys.stdout and sys.stderr themselves, you need to do that
515 515 # *before* instantiating this class, because Term holds onto
516 516 # references to the underlying streams.
517 517 if sys.platform == 'win32' and self.has_readline:
518 518 Term = io.IOTerm(cout=self.readline._outputfile,
519 519 cerr=self.readline._outputfile)
520 520 else:
521 521 Term = io.IOTerm()
522 522 io.Term = Term
523 523
524 524 def init_prompts(self):
525 525 # TODO: This is a pass for now because the prompts are managed inside
526 526 # the DisplayHook. Once there is a separate prompt manager, this
527 527 # will initialize that object and all prompt related information.
528 528 pass
529 529
530 530 def init_display_formatter(self):
531 531 self.display_formatter = DisplayFormatter(config=self.config)
532 532
533 533 def init_display_pub(self):
534 534 self.display_pub = self.display_pub_class(config=self.config)
535 535
536 536 def init_displayhook(self):
537 537 # Initialize displayhook, set in/out prompts and printing system
538 538 self.displayhook = self.displayhook_class(
539 539 config=self.config,
540 540 shell=self,
541 541 cache_size=self.cache_size,
542 542 input_sep = self.separate_in,
543 543 output_sep = self.separate_out,
544 544 output_sep2 = self.separate_out2,
545 545 ps1 = self.prompt_in1,
546 546 ps2 = self.prompt_in2,
547 547 ps_out = self.prompt_out,
548 548 pad_left = self.prompts_pad_left
549 549 )
550 550 # This is a context manager that installs/revmoes the displayhook at
551 551 # the appropriate time.
552 552 self.display_trap = DisplayTrap(hook=self.displayhook)
553 553
554 554 def init_reload_doctest(self):
555 555 # Do a proper resetting of doctest, including the necessary displayhook
556 556 # monkeypatching
557 557 try:
558 558 doctest_reload()
559 559 except ImportError:
560 560 warn("doctest module does not exist.")
561 561
562 562 #-------------------------------------------------------------------------
563 563 # Things related to injections into the sys module
564 564 #-------------------------------------------------------------------------
565 565
566 566 def save_sys_module_state(self):
567 567 """Save the state of hooks in the sys module.
568 568
569 569 This has to be called after self.user_ns is created.
570 570 """
571 571 self._orig_sys_module_state = {}
572 572 self._orig_sys_module_state['stdin'] = sys.stdin
573 573 self._orig_sys_module_state['stdout'] = sys.stdout
574 574 self._orig_sys_module_state['stderr'] = sys.stderr
575 575 self._orig_sys_module_state['excepthook'] = sys.excepthook
576 576 try:
577 577 self._orig_sys_modules_main_name = self.user_ns['__name__']
578 578 except KeyError:
579 579 pass
580 580
581 581 def restore_sys_module_state(self):
582 582 """Restore the state of the sys module."""
583 583 try:
584 584 for k, v in self._orig_sys_module_state.iteritems():
585 585 setattr(sys, k, v)
586 586 except AttributeError:
587 587 pass
588 588 # Reset what what done in self.init_sys_modules
589 589 try:
590 590 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
591 591 except (AttributeError, KeyError):
592 592 pass
593 593
594 594 #-------------------------------------------------------------------------
595 595 # Things related to hooks
596 596 #-------------------------------------------------------------------------
597 597
598 598 def init_hooks(self):
599 599 # hooks holds pointers used for user-side customizations
600 600 self.hooks = Struct()
601 601
602 602 self.strdispatchers = {}
603 603
604 604 # Set all default hooks, defined in the IPython.hooks module.
605 605 hooks = IPython.core.hooks
606 606 for hook_name in hooks.__all__:
607 607 # default hooks have priority 100, i.e. low; user hooks should have
608 608 # 0-100 priority
609 609 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
610 610
611 611 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
612 612 """set_hook(name,hook) -> sets an internal IPython hook.
613 613
614 614 IPython exposes some of its internal API as user-modifiable hooks. By
615 615 adding your function to one of these hooks, you can modify IPython's
616 616 behavior to call at runtime your own routines."""
617 617
618 618 # At some point in the future, this should validate the hook before it
619 619 # accepts it. Probably at least check that the hook takes the number
620 620 # of args it's supposed to.
621 621
622 622 f = types.MethodType(hook,self)
623 623
624 624 # check if the hook is for strdispatcher first
625 625 if str_key is not None:
626 626 sdp = self.strdispatchers.get(name, StrDispatch())
627 627 sdp.add_s(str_key, f, priority )
628 628 self.strdispatchers[name] = sdp
629 629 return
630 630 if re_key is not None:
631 631 sdp = self.strdispatchers.get(name, StrDispatch())
632 632 sdp.add_re(re.compile(re_key), f, priority )
633 633 self.strdispatchers[name] = sdp
634 634 return
635 635
636 636 dp = getattr(self.hooks, name, None)
637 637 if name not in IPython.core.hooks.__all__:
638 638 print "Warning! Hook '%s' is not one of %s" % \
639 639 (name, IPython.core.hooks.__all__ )
640 640 if not dp:
641 641 dp = IPython.core.hooks.CommandChainDispatcher()
642 642
643 643 try:
644 644 dp.add(f,priority)
645 645 except AttributeError:
646 646 # it was not commandchain, plain old func - replace
647 647 dp = f
648 648
649 649 setattr(self.hooks,name, dp)
650 650
651 651 def register_post_execute(self, func):
652 652 """Register a function for calling after code execution.
653 653 """
654 654 if not callable(func):
655 655 raise ValueError('argument %s must be callable' % func)
656 656 self._post_execute.add(func)
657 657
658 658 #-------------------------------------------------------------------------
659 659 # Things related to the "main" module
660 660 #-------------------------------------------------------------------------
661 661
662 662 def new_main_mod(self,ns=None):
663 663 """Return a new 'main' module object for user code execution.
664 664 """
665 665 main_mod = self._user_main_module
666 666 init_fakemod_dict(main_mod,ns)
667 667 return main_mod
668 668
669 669 def cache_main_mod(self,ns,fname):
670 670 """Cache a main module's namespace.
671 671
672 672 When scripts are executed via %run, we must keep a reference to the
673 673 namespace of their __main__ module (a FakeModule instance) around so
674 674 that Python doesn't clear it, rendering objects defined therein
675 675 useless.
676 676
677 677 This method keeps said reference in a private dict, keyed by the
678 678 absolute path of the module object (which corresponds to the script
679 679 path). This way, for multiple executions of the same script we only
680 680 keep one copy of the namespace (the last one), thus preventing memory
681 681 leaks from old references while allowing the objects from the last
682 682 execution to be accessible.
683 683
684 684 Note: we can not allow the actual FakeModule instances to be deleted,
685 685 because of how Python tears down modules (it hard-sets all their
686 686 references to None without regard for reference counts). This method
687 687 must therefore make a *copy* of the given namespace, to allow the
688 688 original module's __dict__ to be cleared and reused.
689 689
690 690
691 691 Parameters
692 692 ----------
693 693 ns : a namespace (a dict, typically)
694 694
695 695 fname : str
696 696 Filename associated with the namespace.
697 697
698 698 Examples
699 699 --------
700 700
701 701 In [10]: import IPython
702 702
703 703 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
704 704
705 705 In [12]: IPython.__file__ in _ip._main_ns_cache
706 706 Out[12]: True
707 707 """
708 708 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
709 709
710 710 def clear_main_mod_cache(self):
711 711 """Clear the cache of main modules.
712 712
713 713 Mainly for use by utilities like %reset.
714 714
715 715 Examples
716 716 --------
717 717
718 718 In [15]: import IPython
719 719
720 720 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
721 721
722 722 In [17]: len(_ip._main_ns_cache) > 0
723 723 Out[17]: True
724 724
725 725 In [18]: _ip.clear_main_mod_cache()
726 726
727 727 In [19]: len(_ip._main_ns_cache) == 0
728 728 Out[19]: True
729 729 """
730 730 self._main_ns_cache.clear()
731 731
732 732 #-------------------------------------------------------------------------
733 733 # Things related to debugging
734 734 #-------------------------------------------------------------------------
735 735
736 736 def init_pdb(self):
737 737 # Set calling of pdb on exceptions
738 738 # self.call_pdb is a property
739 739 self.call_pdb = self.pdb
740 740
741 741 def _get_call_pdb(self):
742 742 return self._call_pdb
743 743
744 744 def _set_call_pdb(self,val):
745 745
746 746 if val not in (0,1,False,True):
747 747 raise ValueError,'new call_pdb value must be boolean'
748 748
749 749 # store value in instance
750 750 self._call_pdb = val
751 751
752 752 # notify the actual exception handlers
753 753 self.InteractiveTB.call_pdb = val
754 754
755 755 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
756 756 'Control auto-activation of pdb at exceptions')
757 757
758 758 def debugger(self,force=False):
759 759 """Call the pydb/pdb debugger.
760 760
761 761 Keywords:
762 762
763 763 - force(False): by default, this routine checks the instance call_pdb
764 764 flag and does not actually invoke the debugger if the flag is false.
765 765 The 'force' option forces the debugger to activate even if the flag
766 766 is false.
767 767 """
768 768
769 769 if not (force or self.call_pdb):
770 770 return
771 771
772 772 if not hasattr(sys,'last_traceback'):
773 773 error('No traceback has been produced, nothing to debug.')
774 774 return
775 775
776 776 # use pydb if available
777 777 if debugger.has_pydb:
778 778 from pydb import pm
779 779 else:
780 780 # fallback to our internal debugger
781 781 pm = lambda : self.InteractiveTB.debugger(force=True)
782 782
783 783 with self.readline_no_record:
784 784 pm()
785 785
786 786 #-------------------------------------------------------------------------
787 787 # Things related to IPython's various namespaces
788 788 #-------------------------------------------------------------------------
789 789
790 790 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
791 791 # Create the namespace where the user will operate. user_ns is
792 792 # normally the only one used, and it is passed to the exec calls as
793 793 # the locals argument. But we do carry a user_global_ns namespace
794 794 # given as the exec 'globals' argument, This is useful in embedding
795 795 # situations where the ipython shell opens in a context where the
796 796 # distinction between locals and globals is meaningful. For
797 797 # non-embedded contexts, it is just the same object as the user_ns dict.
798 798
799 799 # FIXME. For some strange reason, __builtins__ is showing up at user
800 800 # level as a dict instead of a module. This is a manual fix, but I
801 801 # should really track down where the problem is coming from. Alex
802 802 # Schmolck reported this problem first.
803 803
804 804 # A useful post by Alex Martelli on this topic:
805 805 # Re: inconsistent value from __builtins__
806 806 # Von: Alex Martelli <aleaxit@yahoo.com>
807 807 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
808 808 # Gruppen: comp.lang.python
809 809
810 810 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
811 811 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
812 812 # > <type 'dict'>
813 813 # > >>> print type(__builtins__)
814 814 # > <type 'module'>
815 815 # > Is this difference in return value intentional?
816 816
817 817 # Well, it's documented that '__builtins__' can be either a dictionary
818 818 # or a module, and it's been that way for a long time. Whether it's
819 819 # intentional (or sensible), I don't know. In any case, the idea is
820 820 # that if you need to access the built-in namespace directly, you
821 821 # should start with "import __builtin__" (note, no 's') which will
822 822 # definitely give you a module. Yeah, it's somewhat confusing:-(.
823 823
824 824 # These routines return properly built dicts as needed by the rest of
825 825 # the code, and can also be used by extension writers to generate
826 826 # properly initialized namespaces.
827 827 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
828 828 user_global_ns)
829 829
830 830 # Assign namespaces
831 831 # This is the namespace where all normal user variables live
832 832 self.user_ns = user_ns
833 833 self.user_global_ns = user_global_ns
834 834
835 835 # An auxiliary namespace that checks what parts of the user_ns were
836 836 # loaded at startup, so we can list later only variables defined in
837 837 # actual interactive use. Since it is always a subset of user_ns, it
838 838 # doesn't need to be separately tracked in the ns_table.
839 839 self.user_ns_hidden = {}
840 840
841 841 # A namespace to keep track of internal data structures to prevent
842 842 # them from cluttering user-visible stuff. Will be updated later
843 843 self.internal_ns = {}
844 844
845 845 # Now that FakeModule produces a real module, we've run into a nasty
846 846 # problem: after script execution (via %run), the module where the user
847 847 # code ran is deleted. Now that this object is a true module (needed
848 848 # so docetst and other tools work correctly), the Python module
849 849 # teardown mechanism runs over it, and sets to None every variable
850 850 # present in that module. Top-level references to objects from the
851 851 # script survive, because the user_ns is updated with them. However,
852 852 # calling functions defined in the script that use other things from
853 853 # the script will fail, because the function's closure had references
854 854 # to the original objects, which are now all None. So we must protect
855 855 # these modules from deletion by keeping a cache.
856 856 #
857 857 # To avoid keeping stale modules around (we only need the one from the
858 858 # last run), we use a dict keyed with the full path to the script, so
859 859 # only the last version of the module is held in the cache. Note,
860 860 # however, that we must cache the module *namespace contents* (their
861 861 # __dict__). Because if we try to cache the actual modules, old ones
862 862 # (uncached) could be destroyed while still holding references (such as
863 863 # those held by GUI objects that tend to be long-lived)>
864 864 #
865 865 # The %reset command will flush this cache. See the cache_main_mod()
866 866 # and clear_main_mod_cache() methods for details on use.
867 867
868 868 # This is the cache used for 'main' namespaces
869 869 self._main_ns_cache = {}
870 870 # And this is the single instance of FakeModule whose __dict__ we keep
871 871 # copying and clearing for reuse on each %run
872 872 self._user_main_module = FakeModule()
873 873
874 874 # A table holding all the namespaces IPython deals with, so that
875 875 # introspection facilities can search easily.
876 876 self.ns_table = {'user':user_ns,
877 877 'user_global':user_global_ns,
878 878 'internal':self.internal_ns,
879 879 'builtin':__builtin__.__dict__
880 880 }
881 881
882 882 # Similarly, track all namespaces where references can be held and that
883 883 # we can safely clear (so it can NOT include builtin). This one can be
884 884 # a simple list. Note that the main execution namespaces, user_ns and
885 885 # user_global_ns, can NOT be listed here, as clearing them blindly
886 886 # causes errors in object __del__ methods. Instead, the reset() method
887 887 # clears them manually and carefully.
888 888 self.ns_refs_table = [ self.user_ns_hidden,
889 889 self.internal_ns, self._main_ns_cache ]
890 890
891 891 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
892 892 """Return a valid local and global user interactive namespaces.
893 893
894 894 This builds a dict with the minimal information needed to operate as a
895 895 valid IPython user namespace, which you can pass to the various
896 896 embedding classes in ipython. The default implementation returns the
897 897 same dict for both the locals and the globals to allow functions to
898 898 refer to variables in the namespace. Customized implementations can
899 899 return different dicts. The locals dictionary can actually be anything
900 900 following the basic mapping protocol of a dict, but the globals dict
901 901 must be a true dict, not even a subclass. It is recommended that any
902 902 custom object for the locals namespace synchronize with the globals
903 903 dict somehow.
904 904
905 905 Raises TypeError if the provided globals namespace is not a true dict.
906 906
907 907 Parameters
908 908 ----------
909 909 user_ns : dict-like, optional
910 910 The current user namespace. The items in this namespace should
911 911 be included in the output. If None, an appropriate blank
912 912 namespace should be created.
913 913 user_global_ns : dict, optional
914 914 The current user global namespace. The items in this namespace
915 915 should be included in the output. If None, an appropriate
916 916 blank namespace should be created.
917 917
918 918 Returns
919 919 -------
920 920 A pair of dictionary-like object to be used as the local namespace
921 921 of the interpreter and a dict to be used as the global namespace.
922 922 """
923 923
924 924
925 925 # We must ensure that __builtin__ (without the final 's') is always
926 926 # available and pointing to the __builtin__ *module*. For more details:
927 927 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
928 928
929 929 if user_ns is None:
930 930 # Set __name__ to __main__ to better match the behavior of the
931 931 # normal interpreter.
932 932 user_ns = {'__name__' :'__main__',
933 933 '__builtin__' : __builtin__,
934 934 '__builtins__' : __builtin__,
935 935 }
936 936 else:
937 937 user_ns.setdefault('__name__','__main__')
938 938 user_ns.setdefault('__builtin__',__builtin__)
939 939 user_ns.setdefault('__builtins__',__builtin__)
940 940
941 941 if user_global_ns is None:
942 942 user_global_ns = user_ns
943 943 if type(user_global_ns) is not dict:
944 944 raise TypeError("user_global_ns must be a true dict; got %r"
945 945 % type(user_global_ns))
946 946
947 947 return user_ns, user_global_ns
948 948
949 949 def init_sys_modules(self):
950 950 # We need to insert into sys.modules something that looks like a
951 951 # module but which accesses the IPython namespace, for shelve and
952 952 # pickle to work interactively. Normally they rely on getting
953 953 # everything out of __main__, but for embedding purposes each IPython
954 954 # instance has its own private namespace, so we can't go shoving
955 955 # everything into __main__.
956 956
957 957 # note, however, that we should only do this for non-embedded
958 958 # ipythons, which really mimic the __main__.__dict__ with their own
959 959 # namespace. Embedded instances, on the other hand, should not do
960 960 # this because they need to manage the user local/global namespaces
961 961 # only, but they live within a 'normal' __main__ (meaning, they
962 962 # shouldn't overtake the execution environment of the script they're
963 963 # embedded in).
964 964
965 965 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
966 966
967 967 try:
968 968 main_name = self.user_ns['__name__']
969 969 except KeyError:
970 970 raise KeyError('user_ns dictionary MUST have a "__name__" key')
971 971 else:
972 972 sys.modules[main_name] = FakeModule(self.user_ns)
973 973
974 974 def init_user_ns(self):
975 975 """Initialize all user-visible namespaces to their minimum defaults.
976 976
977 977 Certain history lists are also initialized here, as they effectively
978 978 act as user namespaces.
979 979
980 980 Notes
981 981 -----
982 982 All data structures here are only filled in, they are NOT reset by this
983 983 method. If they were not empty before, data will simply be added to
984 984 therm.
985 985 """
986 986 # This function works in two parts: first we put a few things in
987 987 # user_ns, and we sync that contents into user_ns_hidden so that these
988 988 # initial variables aren't shown by %who. After the sync, we add the
989 989 # rest of what we *do* want the user to see with %who even on a new
990 990 # session (probably nothing, so theye really only see their own stuff)
991 991
992 992 # The user dict must *always* have a __builtin__ reference to the
993 993 # Python standard __builtin__ namespace, which must be imported.
994 994 # This is so that certain operations in prompt evaluation can be
995 995 # reliably executed with builtins. Note that we can NOT use
996 996 # __builtins__ (note the 's'), because that can either be a dict or a
997 997 # module, and can even mutate at runtime, depending on the context
998 998 # (Python makes no guarantees on it). In contrast, __builtin__ is
999 999 # always a module object, though it must be explicitly imported.
1000 1000
1001 1001 # For more details:
1002 1002 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1003 1003 ns = dict(__builtin__ = __builtin__)
1004 1004
1005 1005 # Put 'help' in the user namespace
1006 1006 try:
1007 1007 from site import _Helper
1008 1008 ns['help'] = _Helper()
1009 1009 except ImportError:
1010 1010 warn('help() not available - check site.py')
1011 1011
1012 1012 # make global variables for user access to the histories
1013 1013 ns['_ih'] = self.history_manager.input_hist_parsed
1014 1014 ns['_oh'] = self.history_manager.output_hist
1015 1015 ns['_dh'] = self.history_manager.dir_hist
1016 1016
1017 1017 ns['_sh'] = shadowns
1018 1018
1019 1019 # user aliases to input and output histories. These shouldn't show up
1020 1020 # in %who, as they can have very large reprs.
1021 1021 ns['In'] = self.history_manager.input_hist_parsed
1022 1022 ns['Out'] = self.history_manager.output_hist
1023 1023
1024 1024 # Store myself as the public api!!!
1025 1025 ns['get_ipython'] = self.get_ipython
1026 1026
1027 1027 # Sync what we've added so far to user_ns_hidden so these aren't seen
1028 1028 # by %who
1029 1029 self.user_ns_hidden.update(ns)
1030 1030
1031 1031 # Anything put into ns now would show up in %who. Think twice before
1032 1032 # putting anything here, as we really want %who to show the user their
1033 1033 # stuff, not our variables.
1034 1034
1035 1035 # Finally, update the real user's namespace
1036 1036 self.user_ns.update(ns)
1037 1037
1038 1038 def reset(self, new_session=True):
1039 1039 """Clear all internal namespaces.
1040 1040
1041 1041 Note that this is much more aggressive than %reset, since it clears
1042 1042 fully all namespaces, as well as all input/output lists.
1043 1043
1044 1044 If new_session is True, a new history session will be opened.
1045 1045 """
1046 1046 # Clear histories
1047 1047 self.history_manager.reset(new_session)
1048 1048
1049 1049 # Reset counter used to index all histories
1050 1050 self.execution_count = 0
1051 1051
1052 1052 # Restore the user namespaces to minimal usability
1053 1053 for ns in self.ns_refs_table:
1054 1054 ns.clear()
1055 1055
1056 1056 # The main execution namespaces must be cleared very carefully,
1057 1057 # skipping the deletion of the builtin-related keys, because doing so
1058 1058 # would cause errors in many object's __del__ methods.
1059 1059 for ns in [self.user_ns, self.user_global_ns]:
1060 1060 drop_keys = set(ns.keys())
1061 1061 drop_keys.discard('__builtin__')
1062 1062 drop_keys.discard('__builtins__')
1063 1063 for k in drop_keys:
1064 1064 del ns[k]
1065 1065
1066 1066 # Restore the user namespaces to minimal usability
1067 1067 self.init_user_ns()
1068 1068
1069 1069 # Restore the default and user aliases
1070 1070 self.alias_manager.clear_aliases()
1071 1071 self.alias_manager.init_aliases()
1072 1072
1073 1073 def reset_selective(self, regex=None):
1074 1074 """Clear selective variables from internal namespaces based on a
1075 1075 specified regular expression.
1076 1076
1077 1077 Parameters
1078 1078 ----------
1079 1079 regex : string or compiled pattern, optional
1080 1080 A regular expression pattern that will be used in searching
1081 1081 variable names in the users namespaces.
1082 1082 """
1083 1083 if regex is not None:
1084 1084 try:
1085 1085 m = re.compile(regex)
1086 1086 except TypeError:
1087 1087 raise TypeError('regex must be a string or compiled pattern')
1088 1088 # Search for keys in each namespace that match the given regex
1089 1089 # If a match is found, delete the key/value pair.
1090 1090 for ns in self.ns_refs_table:
1091 1091 for var in ns:
1092 1092 if m.search(var):
1093 1093 del ns[var]
1094 1094
1095 1095 def push(self, variables, interactive=True):
1096 1096 """Inject a group of variables into the IPython user namespace.
1097 1097
1098 1098 Parameters
1099 1099 ----------
1100 1100 variables : dict, str or list/tuple of str
1101 1101 The variables to inject into the user's namespace. If a dict, a
1102 1102 simple update is done. If a str, the string is assumed to have
1103 1103 variable names separated by spaces. A list/tuple of str can also
1104 1104 be used to give the variable names. If just the variable names are
1105 1105 give (list/tuple/str) then the variable values looked up in the
1106 1106 callers frame.
1107 1107 interactive : bool
1108 1108 If True (default), the variables will be listed with the ``who``
1109 1109 magic.
1110 1110 """
1111 1111 vdict = None
1112 1112
1113 1113 # We need a dict of name/value pairs to do namespace updates.
1114 1114 if isinstance(variables, dict):
1115 1115 vdict = variables
1116 1116 elif isinstance(variables, (basestring, list, tuple)):
1117 1117 if isinstance(variables, basestring):
1118 1118 vlist = variables.split()
1119 1119 else:
1120 1120 vlist = variables
1121 1121 vdict = {}
1122 1122 cf = sys._getframe(1)
1123 1123 for name in vlist:
1124 1124 try:
1125 1125 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1126 1126 except:
1127 1127 print ('Could not get variable %s from %s' %
1128 1128 (name,cf.f_code.co_name))
1129 1129 else:
1130 1130 raise ValueError('variables must be a dict/str/list/tuple')
1131 1131
1132 1132 # Propagate variables to user namespace
1133 1133 self.user_ns.update(vdict)
1134 1134
1135 1135 # And configure interactive visibility
1136 1136 config_ns = self.user_ns_hidden
1137 1137 if interactive:
1138 1138 for name, val in vdict.iteritems():
1139 1139 config_ns.pop(name, None)
1140 1140 else:
1141 1141 for name,val in vdict.iteritems():
1142 1142 config_ns[name] = val
1143 1143
1144 1144 #-------------------------------------------------------------------------
1145 1145 # Things related to object introspection
1146 1146 #-------------------------------------------------------------------------
1147 1147
1148 1148 def _ofind(self, oname, namespaces=None):
1149 1149 """Find an object in the available namespaces.
1150 1150
1151 1151 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1152 1152
1153 1153 Has special code to detect magic functions.
1154 1154 """
1155 1155 #oname = oname.strip()
1156 1156 #print '1- oname: <%r>' % oname # dbg
1157 1157 try:
1158 1158 oname = oname.strip().encode('ascii')
1159 1159 #print '2- oname: <%r>' % oname # dbg
1160 1160 except UnicodeEncodeError:
1161 1161 print 'Python identifiers can only contain ascii characters.'
1162 1162 return dict(found=False)
1163 1163
1164 1164 alias_ns = None
1165 1165 if namespaces is None:
1166 1166 # Namespaces to search in:
1167 1167 # Put them in a list. The order is important so that we
1168 1168 # find things in the same order that Python finds them.
1169 1169 namespaces = [ ('Interactive', self.user_ns),
1170 1170 ('IPython internal', self.internal_ns),
1171 1171 ('Python builtin', __builtin__.__dict__),
1172 1172 ('Alias', self.alias_manager.alias_table),
1173 1173 ]
1174 1174 alias_ns = self.alias_manager.alias_table
1175 1175
1176 1176 # initialize results to 'null'
1177 1177 found = False; obj = None; ospace = None; ds = None;
1178 1178 ismagic = False; isalias = False; parent = None
1179 1179
1180 1180 # We need to special-case 'print', which as of python2.6 registers as a
1181 1181 # function but should only be treated as one if print_function was
1182 1182 # loaded with a future import. In this case, just bail.
1183 1183 if (oname == 'print' and not (self.compile.compiler_flags &
1184 1184 __future__.CO_FUTURE_PRINT_FUNCTION)):
1185 1185 return {'found':found, 'obj':obj, 'namespace':ospace,
1186 1186 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1187 1187
1188 1188 # Look for the given name by splitting it in parts. If the head is
1189 1189 # found, then we look for all the remaining parts as members, and only
1190 1190 # declare success if we can find them all.
1191 1191 oname_parts = oname.split('.')
1192 1192 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1193 1193 for nsname,ns in namespaces:
1194 1194 try:
1195 1195 obj = ns[oname_head]
1196 1196 except KeyError:
1197 1197 continue
1198 1198 else:
1199 1199 #print 'oname_rest:', oname_rest # dbg
1200 1200 for part in oname_rest:
1201 1201 try:
1202 1202 parent = obj
1203 1203 obj = getattr(obj,part)
1204 1204 except:
1205 1205 # Blanket except b/c some badly implemented objects
1206 1206 # allow __getattr__ to raise exceptions other than
1207 1207 # AttributeError, which then crashes IPython.
1208 1208 break
1209 1209 else:
1210 1210 # If we finish the for loop (no break), we got all members
1211 1211 found = True
1212 1212 ospace = nsname
1213 1213 if ns == alias_ns:
1214 1214 isalias = True
1215 1215 break # namespace loop
1216 1216
1217 1217 # Try to see if it's magic
1218 1218 if not found:
1219 1219 if oname.startswith(ESC_MAGIC):
1220 1220 oname = oname[1:]
1221 1221 obj = getattr(self,'magic_'+oname,None)
1222 1222 if obj is not None:
1223 1223 found = True
1224 1224 ospace = 'IPython internal'
1225 1225 ismagic = True
1226 1226
1227 1227 # Last try: special-case some literals like '', [], {}, etc:
1228 1228 if not found and oname_head in ["''",'""','[]','{}','()']:
1229 1229 obj = eval(oname_head)
1230 1230 found = True
1231 1231 ospace = 'Interactive'
1232 1232
1233 1233 return {'found':found, 'obj':obj, 'namespace':ospace,
1234 1234 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1235 1235
1236 1236 def _ofind_property(self, oname, info):
1237 1237 """Second part of object finding, to look for property details."""
1238 1238 if info.found:
1239 1239 # Get the docstring of the class property if it exists.
1240 1240 path = oname.split('.')
1241 1241 root = '.'.join(path[:-1])
1242 1242 if info.parent is not None:
1243 1243 try:
1244 1244 target = getattr(info.parent, '__class__')
1245 1245 # The object belongs to a class instance.
1246 1246 try:
1247 1247 target = getattr(target, path[-1])
1248 1248 # The class defines the object.
1249 1249 if isinstance(target, property):
1250 1250 oname = root + '.__class__.' + path[-1]
1251 1251 info = Struct(self._ofind(oname))
1252 1252 except AttributeError: pass
1253 1253 except AttributeError: pass
1254 1254
1255 1255 # We return either the new info or the unmodified input if the object
1256 1256 # hadn't been found
1257 1257 return info
1258 1258
1259 1259 def _object_find(self, oname, namespaces=None):
1260 1260 """Find an object and return a struct with info about it."""
1261 1261 inf = Struct(self._ofind(oname, namespaces))
1262 1262 return Struct(self._ofind_property(oname, inf))
1263 1263
1264 1264 def _inspect(self, meth, oname, namespaces=None, **kw):
1265 1265 """Generic interface to the inspector system.
1266 1266
1267 1267 This function is meant to be called by pdef, pdoc & friends."""
1268 1268 info = self._object_find(oname)
1269 1269 if info.found:
1270 1270 pmethod = getattr(self.inspector, meth)
1271 1271 formatter = format_screen if info.ismagic else None
1272 1272 if meth == 'pdoc':
1273 1273 pmethod(info.obj, oname, formatter)
1274 1274 elif meth == 'pinfo':
1275 1275 pmethod(info.obj, oname, formatter, info, **kw)
1276 1276 else:
1277 1277 pmethod(info.obj, oname)
1278 1278 else:
1279 1279 print 'Object `%s` not found.' % oname
1280 1280 return 'not found' # so callers can take other action
1281 1281
1282 1282 def object_inspect(self, oname):
1283 1283 info = self._object_find(oname)
1284 1284 if info.found:
1285 1285 return self.inspector.info(info.obj, oname, info=info)
1286 1286 else:
1287 1287 return oinspect.object_info(name=oname, found=False)
1288 1288
1289 1289 #-------------------------------------------------------------------------
1290 1290 # Things related to history management
1291 1291 #-------------------------------------------------------------------------
1292 1292
1293 1293 def init_history(self):
1294 1294 """Sets up the command history, and starts regular autosaves."""
1295 1295 self.history_manager = HistoryManager(shell=self, config=self.config)
1296 1296
1297 1297 #-------------------------------------------------------------------------
1298 1298 # Things related to exception handling and tracebacks (not debugging)
1299 1299 #-------------------------------------------------------------------------
1300 1300
1301 1301 def init_traceback_handlers(self, custom_exceptions):
1302 1302 # Syntax error handler.
1303 1303 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1304 1304
1305 1305 # The interactive one is initialized with an offset, meaning we always
1306 1306 # want to remove the topmost item in the traceback, which is our own
1307 1307 # internal code. Valid modes: ['Plain','Context','Verbose']
1308 1308 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1309 1309 color_scheme='NoColor',
1310 1310 tb_offset = 1,
1311 1311 check_cache=self.compile.check_cache)
1312 1312
1313 1313 # The instance will store a pointer to the system-wide exception hook,
1314 1314 # so that runtime code (such as magics) can access it. This is because
1315 1315 # during the read-eval loop, it may get temporarily overwritten.
1316 1316 self.sys_excepthook = sys.excepthook
1317 1317
1318 1318 # and add any custom exception handlers the user may have specified
1319 1319 self.set_custom_exc(*custom_exceptions)
1320 1320
1321 1321 # Set the exception mode
1322 1322 self.InteractiveTB.set_mode(mode=self.xmode)
1323 1323
1324 1324 def set_custom_exc(self, exc_tuple, handler):
1325 1325 """set_custom_exc(exc_tuple,handler)
1326 1326
1327 1327 Set a custom exception handler, which will be called if any of the
1328 1328 exceptions in exc_tuple occur in the mainloop (specifically, in the
1329 1329 run_code() method.
1330 1330
1331 1331 Inputs:
1332 1332
1333 1333 - exc_tuple: a *tuple* of valid exceptions to call the defined
1334 1334 handler for. It is very important that you use a tuple, and NOT A
1335 1335 LIST here, because of the way Python's except statement works. If
1336 1336 you only want to trap a single exception, use a singleton tuple:
1337 1337
1338 1338 exc_tuple == (MyCustomException,)
1339 1339
1340 1340 - handler: this must be defined as a function with the following
1341 1341 basic interface::
1342 1342
1343 1343 def my_handler(self, etype, value, tb, tb_offset=None)
1344 1344 ...
1345 1345 # The return value must be
1346 1346 return structured_traceback
1347 1347
1348 1348 This will be made into an instance method (via types.MethodType)
1349 1349 of IPython itself, and it will be called if any of the exceptions
1350 1350 listed in the exc_tuple are caught. If the handler is None, an
1351 1351 internal basic one is used, which just prints basic info.
1352 1352
1353 1353 WARNING: by putting in your own exception handler into IPython's main
1354 1354 execution loop, you run a very good chance of nasty crashes. This
1355 1355 facility should only be used if you really know what you are doing."""
1356 1356
1357 1357 assert type(exc_tuple)==type(()) , \
1358 1358 "The custom exceptions must be given AS A TUPLE."
1359 1359
1360 1360 def dummy_handler(self,etype,value,tb):
1361 1361 print '*** Simple custom exception handler ***'
1362 1362 print 'Exception type :',etype
1363 1363 print 'Exception value:',value
1364 1364 print 'Traceback :',tb
1365 1365 print 'Source code :','\n'.join(self.buffer)
1366 1366
1367 1367 if handler is None: handler = dummy_handler
1368 1368
1369 1369 self.CustomTB = types.MethodType(handler,self)
1370 1370 self.custom_exceptions = exc_tuple
1371 1371
1372 1372 def excepthook(self, etype, value, tb):
1373 1373 """One more defense for GUI apps that call sys.excepthook.
1374 1374
1375 1375 GUI frameworks like wxPython trap exceptions and call
1376 1376 sys.excepthook themselves. I guess this is a feature that
1377 1377 enables them to keep running after exceptions that would
1378 1378 otherwise kill their mainloop. This is a bother for IPython
1379 1379 which excepts to catch all of the program exceptions with a try:
1380 1380 except: statement.
1381 1381
1382 1382 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1383 1383 any app directly invokes sys.excepthook, it will look to the user like
1384 1384 IPython crashed. In order to work around this, we can disable the
1385 1385 CrashHandler and replace it with this excepthook instead, which prints a
1386 1386 regular traceback using our InteractiveTB. In this fashion, apps which
1387 1387 call sys.excepthook will generate a regular-looking exception from
1388 1388 IPython, and the CrashHandler will only be triggered by real IPython
1389 1389 crashes.
1390 1390
1391 1391 This hook should be used sparingly, only in places which are not likely
1392 1392 to be true IPython errors.
1393 1393 """
1394 1394 self.showtraceback((etype,value,tb),tb_offset=0)
1395 1395
1396 1396 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1397 1397 exception_only=False):
1398 1398 """Display the exception that just occurred.
1399 1399
1400 1400 If nothing is known about the exception, this is the method which
1401 1401 should be used throughout the code for presenting user tracebacks,
1402 1402 rather than directly invoking the InteractiveTB object.
1403 1403
1404 1404 A specific showsyntaxerror() also exists, but this method can take
1405 1405 care of calling it if needed, so unless you are explicitly catching a
1406 1406 SyntaxError exception, don't try to analyze the stack manually and
1407 1407 simply call this method."""
1408 1408
1409 1409 try:
1410 1410 if exc_tuple is None:
1411 1411 etype, value, tb = sys.exc_info()
1412 1412 else:
1413 1413 etype, value, tb = exc_tuple
1414 1414
1415 1415 if etype is None:
1416 1416 if hasattr(sys, 'last_type'):
1417 1417 etype, value, tb = sys.last_type, sys.last_value, \
1418 1418 sys.last_traceback
1419 1419 else:
1420 1420 self.write_err('No traceback available to show.\n')
1421 1421 return
1422 1422
1423 1423 if etype is SyntaxError:
1424 1424 # Though this won't be called by syntax errors in the input
1425 1425 # line, there may be SyntaxError cases whith imported code.
1426 1426 self.showsyntaxerror(filename)
1427 1427 elif etype is UsageError:
1428 1428 print "UsageError:", value
1429 1429 else:
1430 1430 # WARNING: these variables are somewhat deprecated and not
1431 1431 # necessarily safe to use in a threaded environment, but tools
1432 1432 # like pdb depend on their existence, so let's set them. If we
1433 1433 # find problems in the field, we'll need to revisit their use.
1434 1434 sys.last_type = etype
1435 1435 sys.last_value = value
1436 1436 sys.last_traceback = tb
1437 1437
1438 1438 if etype in self.custom_exceptions:
1439 1439 # FIXME: Old custom traceback objects may just return a
1440 1440 # string, in that case we just put it into a list
1441 1441 stb = self.CustomTB(etype, value, tb, tb_offset)
1442 1442 if isinstance(ctb, basestring):
1443 1443 stb = [stb]
1444 1444 else:
1445 1445 if exception_only:
1446 1446 stb = ['An exception has occurred, use %tb to see '
1447 1447 'the full traceback.\n']
1448 1448 stb.extend(self.InteractiveTB.get_exception_only(etype,
1449 1449 value))
1450 1450 else:
1451 1451 stb = self.InteractiveTB.structured_traceback(etype,
1452 1452 value, tb, tb_offset=tb_offset)
1453 1453 # FIXME: the pdb calling should be done by us, not by
1454 1454 # the code computing the traceback.
1455 1455 if self.InteractiveTB.call_pdb:
1456 1456 # pdb mucks up readline, fix it back
1457 1457 self.set_readline_completer()
1458 1458
1459 1459 # Actually show the traceback
1460 1460 self._showtraceback(etype, value, stb)
1461 1461
1462 1462 except KeyboardInterrupt:
1463 1463 self.write_err("\nKeyboardInterrupt\n")
1464 1464
1465 1465 def _showtraceback(self, etype, evalue, stb):
1466 1466 """Actually show a traceback.
1467 1467
1468 1468 Subclasses may override this method to put the traceback on a different
1469 1469 place, like a side channel.
1470 1470 """
1471 1471 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1472 1472
1473 1473 def showsyntaxerror(self, filename=None):
1474 1474 """Display the syntax error that just occurred.
1475 1475
1476 1476 This doesn't display a stack trace because there isn't one.
1477 1477
1478 1478 If a filename is given, it is stuffed in the exception instead
1479 1479 of what was there before (because Python's parser always uses
1480 1480 "<string>" when reading from a string).
1481 1481 """
1482 1482 etype, value, last_traceback = sys.exc_info()
1483 1483
1484 1484 # See note about these variables in showtraceback() above
1485 1485 sys.last_type = etype
1486 1486 sys.last_value = value
1487 1487 sys.last_traceback = last_traceback
1488 1488
1489 1489 if filename and etype is SyntaxError:
1490 1490 # Work hard to stuff the correct filename in the exception
1491 1491 try:
1492 1492 msg, (dummy_filename, lineno, offset, line) = value
1493 1493 except:
1494 1494 # Not the format we expect; leave it alone
1495 1495 pass
1496 1496 else:
1497 1497 # Stuff in the right filename
1498 1498 try:
1499 1499 # Assume SyntaxError is a class exception
1500 1500 value = SyntaxError(msg, (filename, lineno, offset, line))
1501 1501 except:
1502 1502 # If that failed, assume SyntaxError is a string
1503 1503 value = msg, (filename, lineno, offset, line)
1504 1504 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1505 1505 self._showtraceback(etype, value, stb)
1506 1506
1507 1507 #-------------------------------------------------------------------------
1508 1508 # Things related to readline
1509 1509 #-------------------------------------------------------------------------
1510 1510
1511 1511 def init_readline(self):
1512 1512 """Command history completion/saving/reloading."""
1513 1513
1514 1514 if self.readline_use:
1515 1515 import IPython.utils.rlineimpl as readline
1516 1516
1517 1517 self.rl_next_input = None
1518 1518 self.rl_do_indent = False
1519 1519
1520 1520 if not self.readline_use or not readline.have_readline:
1521 1521 self.has_readline = False
1522 1522 self.readline = None
1523 1523 # Set a number of methods that depend on readline to be no-op
1524 1524 self.set_readline_completer = no_op
1525 1525 self.set_custom_completer = no_op
1526 1526 self.set_completer_frame = no_op
1527 1527 warn('Readline services not available or not loaded.')
1528 1528 else:
1529 1529 self.has_readline = True
1530 1530 self.readline = readline
1531 1531 sys.modules['readline'] = readline
1532 1532
1533 1533 # Platform-specific configuration
1534 1534 if os.name == 'nt':
1535 1535 # FIXME - check with Frederick to see if we can harmonize
1536 1536 # naming conventions with pyreadline to avoid this
1537 1537 # platform-dependent check
1538 1538 self.readline_startup_hook = readline.set_pre_input_hook
1539 1539 else:
1540 1540 self.readline_startup_hook = readline.set_startup_hook
1541 1541
1542 1542 # Load user's initrc file (readline config)
1543 1543 # Or if libedit is used, load editrc.
1544 1544 inputrc_name = os.environ.get('INPUTRC')
1545 1545 if inputrc_name is None:
1546 1546 home_dir = get_home_dir()
1547 1547 if home_dir is not None:
1548 1548 inputrc_name = '.inputrc'
1549 1549 if readline.uses_libedit:
1550 1550 inputrc_name = '.editrc'
1551 1551 inputrc_name = os.path.join(home_dir, inputrc_name)
1552 1552 if os.path.isfile(inputrc_name):
1553 1553 try:
1554 1554 readline.read_init_file(inputrc_name)
1555 1555 except:
1556 1556 warn('Problems reading readline initialization file <%s>'
1557 1557 % inputrc_name)
1558 1558
1559 1559 # Configure readline according to user's prefs
1560 1560 # This is only done if GNU readline is being used. If libedit
1561 1561 # is being used (as on Leopard) the readline config is
1562 1562 # not run as the syntax for libedit is different.
1563 1563 if not readline.uses_libedit:
1564 1564 for rlcommand in self.readline_parse_and_bind:
1565 1565 #print "loading rl:",rlcommand # dbg
1566 1566 readline.parse_and_bind(rlcommand)
1567 1567
1568 1568 # Remove some chars from the delimiters list. If we encounter
1569 1569 # unicode chars, discard them.
1570 1570 delims = readline.get_completer_delims().encode("ascii", "ignore")
1571 1571 delims = delims.translate(None, self.readline_remove_delims)
1572 1572 delims = delims.replace(ESC_MAGIC, '')
1573 1573 readline.set_completer_delims(delims)
1574 1574 # otherwise we end up with a monster history after a while:
1575 1575 readline.set_history_length(self.history_length)
1576 1576
1577 1577 self.refill_readline_hist()
1578 1578 self.readline_no_record = ReadlineNoRecord(self)
1579 1579
1580 1580 # Configure auto-indent for all platforms
1581 1581 self.set_autoindent(self.autoindent)
1582 1582
1583 1583 def refill_readline_hist(self):
1584 1584 # Load the last 1000 lines from history
1585 1585 self.readline.clear_history()
1586 1586 stdin_encoding = sys.stdin.encoding or "utf-8"
1587 1587 for _, _, cell in self.history_manager.get_tail(1000,
1588 1588 include_latest=True):
1589 1589 if cell.strip(): # Ignore blank lines
1590 1590 for line in cell.splitlines():
1591 1591 self.readline.add_history(line.encode(stdin_encoding))
1592 1592
1593 1593 def set_next_input(self, s):
1594 1594 """ Sets the 'default' input string for the next command line.
1595 1595
1596 1596 Requires readline.
1597 1597
1598 1598 Example:
1599 1599
1600 1600 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1601 1601 [D:\ipython]|2> Hello Word_ # cursor is here
1602 1602 """
1603 1603
1604 1604 self.rl_next_input = s
1605 1605
1606 1606 # Maybe move this to the terminal subclass?
1607 1607 def pre_readline(self):
1608 1608 """readline hook to be used at the start of each line.
1609 1609
1610 1610 Currently it handles auto-indent only."""
1611 1611
1612 1612 if self.rl_do_indent:
1613 1613 self.readline.insert_text(self._indent_current_str())
1614 1614 if self.rl_next_input is not None:
1615 1615 self.readline.insert_text(self.rl_next_input)
1616 1616 self.rl_next_input = None
1617 1617
1618 1618 def _indent_current_str(self):
1619 1619 """return the current level of indentation as a string"""
1620 1620 return self.input_splitter.indent_spaces * ' '
1621 1621
1622 1622 #-------------------------------------------------------------------------
1623 1623 # Things related to text completion
1624 1624 #-------------------------------------------------------------------------
1625 1625
1626 1626 def init_completer(self):
1627 1627 """Initialize the completion machinery.
1628 1628
1629 1629 This creates completion machinery that can be used by client code,
1630 1630 either interactively in-process (typically triggered by the readline
1631 1631 library), programatically (such as in test suites) or out-of-prcess
1632 1632 (typically over the network by remote frontends).
1633 1633 """
1634 1634 from IPython.core.completer import IPCompleter
1635 1635 from IPython.core.completerlib import (module_completer,
1636 1636 magic_run_completer, cd_completer)
1637 1637
1638 1638 self.Completer = IPCompleter(self,
1639 1639 self.user_ns,
1640 1640 self.user_global_ns,
1641 1641 self.readline_omit__names,
1642 1642 self.alias_manager.alias_table,
1643 1643 self.has_readline)
1644 1644
1645 1645 # Add custom completers to the basic ones built into IPCompleter
1646 1646 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1647 1647 self.strdispatchers['complete_command'] = sdisp
1648 1648 self.Completer.custom_completers = sdisp
1649 1649
1650 1650 self.set_hook('complete_command', module_completer, str_key = 'import')
1651 1651 self.set_hook('complete_command', module_completer, str_key = 'from')
1652 1652 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1653 1653 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1654 1654
1655 1655 # Only configure readline if we truly are using readline. IPython can
1656 1656 # do tab-completion over the network, in GUIs, etc, where readline
1657 1657 # itself may be absent
1658 1658 if self.has_readline:
1659 1659 self.set_readline_completer()
1660 1660
1661 1661 def complete(self, text, line=None, cursor_pos=None):
1662 1662 """Return the completed text and a list of completions.
1663 1663
1664 1664 Parameters
1665 1665 ----------
1666 1666
1667 1667 text : string
1668 1668 A string of text to be completed on. It can be given as empty and
1669 1669 instead a line/position pair are given. In this case, the
1670 1670 completer itself will split the line like readline does.
1671 1671
1672 1672 line : string, optional
1673 1673 The complete line that text is part of.
1674 1674
1675 1675 cursor_pos : int, optional
1676 1676 The position of the cursor on the input line.
1677 1677
1678 1678 Returns
1679 1679 -------
1680 1680 text : string
1681 1681 The actual text that was completed.
1682 1682
1683 1683 matches : list
1684 1684 A sorted list with all possible completions.
1685 1685
1686 1686 The optional arguments allow the completion to take more context into
1687 1687 account, and are part of the low-level completion API.
1688 1688
1689 1689 This is a wrapper around the completion mechanism, similar to what
1690 1690 readline does at the command line when the TAB key is hit. By
1691 1691 exposing it as a method, it can be used by other non-readline
1692 1692 environments (such as GUIs) for text completion.
1693 1693
1694 1694 Simple usage example:
1695 1695
1696 1696 In [1]: x = 'hello'
1697 1697
1698 1698 In [2]: _ip.complete('x.l')
1699 1699 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1700 1700 """
1701 1701
1702 1702 # Inject names into __builtin__ so we can complete on the added names.
1703 1703 with self.builtin_trap:
1704 1704 return self.Completer.complete(text, line, cursor_pos)
1705 1705
1706 1706 def set_custom_completer(self, completer, pos=0):
1707 1707 """Adds a new custom completer function.
1708 1708
1709 1709 The position argument (defaults to 0) is the index in the completers
1710 1710 list where you want the completer to be inserted."""
1711 1711
1712 1712 newcomp = types.MethodType(completer,self.Completer)
1713 1713 self.Completer.matchers.insert(pos,newcomp)
1714 1714
1715 1715 def set_readline_completer(self):
1716 1716 """Reset readline's completer to be our own."""
1717 1717 self.readline.set_completer(self.Completer.rlcomplete)
1718 1718
1719 1719 def set_completer_frame(self, frame=None):
1720 1720 """Set the frame of the completer."""
1721 1721 if frame:
1722 1722 self.Completer.namespace = frame.f_locals
1723 1723 self.Completer.global_namespace = frame.f_globals
1724 1724 else:
1725 1725 self.Completer.namespace = self.user_ns
1726 1726 self.Completer.global_namespace = self.user_global_ns
1727 1727
1728 1728 #-------------------------------------------------------------------------
1729 1729 # Things related to magics
1730 1730 #-------------------------------------------------------------------------
1731 1731
1732 1732 def init_magics(self):
1733 1733 # FIXME: Move the color initialization to the DisplayHook, which
1734 1734 # should be split into a prompt manager and displayhook. We probably
1735 1735 # even need a centralize colors management object.
1736 1736 self.magic_colors(self.colors)
1737 1737 # History was moved to a separate module
1738 1738 from . import history
1739 1739 history.init_ipython(self)
1740 1740
1741 1741 def magic(self,arg_s):
1742 1742 """Call a magic function by name.
1743 1743
1744 1744 Input: a string containing the name of the magic function to call and
1745 1745 any additional arguments to be passed to the magic.
1746 1746
1747 1747 magic('name -opt foo bar') is equivalent to typing at the ipython
1748 1748 prompt:
1749 1749
1750 1750 In[1]: %name -opt foo bar
1751 1751
1752 1752 To call a magic without arguments, simply use magic('name').
1753 1753
1754 1754 This provides a proper Python function to call IPython's magics in any
1755 1755 valid Python code you can type at the interpreter, including loops and
1756 1756 compound statements.
1757 1757 """
1758 1758 args = arg_s.split(' ',1)
1759 1759 magic_name = args[0]
1760 1760 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1761 1761
1762 1762 try:
1763 1763 magic_args = args[1]
1764 1764 except IndexError:
1765 1765 magic_args = ''
1766 1766 fn = getattr(self,'magic_'+magic_name,None)
1767 1767 if fn is None:
1768 1768 error("Magic function `%s` not found." % magic_name)
1769 1769 else:
1770 1770 magic_args = self.var_expand(magic_args,1)
1771 1771 # Grab local namespace if we need it:
1772 1772 if getattr(fn, "needs_local_scope", False):
1773 1773 self._magic_locals = sys._getframe(1).f_locals
1774 1774 with nested(self.builtin_trap,):
1775 1775 result = fn(magic_args)
1776 1776 # Ensure we're not keeping object references around:
1777 1777 self._magic_locals = {}
1778 1778 return result
1779 1779
1780 1780 def define_magic(self, magicname, func):
1781 1781 """Expose own function as magic function for ipython
1782 1782
1783 1783 def foo_impl(self,parameter_s=''):
1784 1784 'My very own magic!. (Use docstrings, IPython reads them).'
1785 1785 print 'Magic function. Passed parameter is between < >:'
1786 1786 print '<%s>' % parameter_s
1787 1787 print 'The self object is:',self
1788 1788
1789 1789 self.define_magic('foo',foo_impl)
1790 1790 """
1791 1791
1792 1792 import new
1793 1793 im = types.MethodType(func,self)
1794 1794 old = getattr(self, "magic_" + magicname, None)
1795 1795 setattr(self, "magic_" + magicname, im)
1796 1796 return old
1797 1797
1798 1798 #-------------------------------------------------------------------------
1799 1799 # Things related to macros
1800 1800 #-------------------------------------------------------------------------
1801 1801
1802 1802 def define_macro(self, name, themacro):
1803 1803 """Define a new macro
1804 1804
1805 1805 Parameters
1806 1806 ----------
1807 1807 name : str
1808 1808 The name of the macro.
1809 1809 themacro : str or Macro
1810 1810 The action to do upon invoking the macro. If a string, a new
1811 1811 Macro object is created by passing the string to it.
1812 1812 """
1813 1813
1814 1814 from IPython.core import macro
1815 1815
1816 1816 if isinstance(themacro, basestring):
1817 1817 themacro = macro.Macro(themacro)
1818 1818 if not isinstance(themacro, macro.Macro):
1819 1819 raise ValueError('A macro must be a string or a Macro instance.')
1820 1820 self.user_ns[name] = themacro
1821 1821
1822 1822 #-------------------------------------------------------------------------
1823 1823 # Things related to the running of system commands
1824 1824 #-------------------------------------------------------------------------
1825 1825
1826 1826 def system(self, cmd):
1827 1827 """Call the given cmd in a subprocess.
1828 1828
1829 1829 Parameters
1830 1830 ----------
1831 1831 cmd : str
1832 1832 Command to execute (can not end in '&', as bacground processes are
1833 1833 not supported.
1834 1834 """
1835 1835 # We do not support backgrounding processes because we either use
1836 1836 # pexpect or pipes to read from. Users can always just call
1837 1837 # os.system() if they really want a background process.
1838 1838 if cmd.endswith('&'):
1839 1839 raise OSError("Background processes not supported.")
1840 1840
1841 1841 return system(self.var_expand(cmd, depth=2))
1842 1842
1843 1843 def getoutput(self, cmd, split=True):
1844 1844 """Get output (possibly including stderr) from a subprocess.
1845 1845
1846 1846 Parameters
1847 1847 ----------
1848 1848 cmd : str
1849 1849 Command to execute (can not end in '&', as background processes are
1850 1850 not supported.
1851 1851 split : bool, optional
1852 1852
1853 1853 If True, split the output into an IPython SList. Otherwise, an
1854 1854 IPython LSString is returned. These are objects similar to normal
1855 1855 lists and strings, with a few convenience attributes for easier
1856 1856 manipulation of line-based output. You can use '?' on them for
1857 1857 details.
1858 1858 """
1859 1859 if cmd.endswith('&'):
1860 1860 raise OSError("Background processes not supported.")
1861 1861 out = getoutput(self.var_expand(cmd, depth=2))
1862 1862 if split:
1863 1863 out = SList(out.splitlines())
1864 1864 else:
1865 1865 out = LSString(out)
1866 1866 return out
1867 1867
1868 1868 #-------------------------------------------------------------------------
1869 1869 # Things related to aliases
1870 1870 #-------------------------------------------------------------------------
1871 1871
1872 1872 def init_alias(self):
1873 1873 self.alias_manager = AliasManager(shell=self, config=self.config)
1874 1874 self.ns_table['alias'] = self.alias_manager.alias_table,
1875 1875
1876 1876 #-------------------------------------------------------------------------
1877 1877 # Things related to extensions and plugins
1878 1878 #-------------------------------------------------------------------------
1879 1879
1880 1880 def init_extension_manager(self):
1881 1881 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1882 1882
1883 1883 def init_plugin_manager(self):
1884 1884 self.plugin_manager = PluginManager(config=self.config)
1885 1885
1886 1886 #-------------------------------------------------------------------------
1887 1887 # Things related to payloads
1888 1888 #-------------------------------------------------------------------------
1889 1889
1890 1890 def init_payload(self):
1891 1891 self.payload_manager = PayloadManager(config=self.config)
1892 1892
1893 1893 #-------------------------------------------------------------------------
1894 1894 # Things related to the prefilter
1895 1895 #-------------------------------------------------------------------------
1896 1896
1897 1897 def init_prefilter(self):
1898 1898 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1899 1899 # Ultimately this will be refactored in the new interpreter code, but
1900 1900 # for now, we should expose the main prefilter method (there's legacy
1901 1901 # code out there that may rely on this).
1902 1902 self.prefilter = self.prefilter_manager.prefilter_lines
1903 1903
1904 1904 def auto_rewrite_input(self, cmd):
1905 1905 """Print to the screen the rewritten form of the user's command.
1906 1906
1907 1907 This shows visual feedback by rewriting input lines that cause
1908 1908 automatic calling to kick in, like::
1909 1909
1910 1910 /f x
1911 1911
1912 1912 into::
1913 1913
1914 1914 ------> f(x)
1915 1915
1916 1916 after the user's input prompt. This helps the user understand that the
1917 1917 input line was transformed automatically by IPython.
1918 1918 """
1919 1919 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1920 1920
1921 1921 try:
1922 1922 # plain ascii works better w/ pyreadline, on some machines, so
1923 1923 # we use it and only print uncolored rewrite if we have unicode
1924 1924 rw = str(rw)
1925 1925 print >> IPython.utils.io.Term.cout, rw
1926 1926 except UnicodeEncodeError:
1927 1927 print "------> " + cmd
1928 1928
1929 1929 #-------------------------------------------------------------------------
1930 1930 # Things related to extracting values/expressions from kernel and user_ns
1931 1931 #-------------------------------------------------------------------------
1932 1932
1933 1933 def _simple_error(self):
1934 1934 etype, value = sys.exc_info()[:2]
1935 1935 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1936 1936
1937 1937 def user_variables(self, names):
1938 1938 """Get a list of variable names from the user's namespace.
1939 1939
1940 1940 Parameters
1941 1941 ----------
1942 1942 names : list of strings
1943 1943 A list of names of variables to be read from the user namespace.
1944 1944
1945 1945 Returns
1946 1946 -------
1947 1947 A dict, keyed by the input names and with the repr() of each value.
1948 1948 """
1949 1949 out = {}
1950 1950 user_ns = self.user_ns
1951 1951 for varname in names:
1952 1952 try:
1953 1953 value = repr(user_ns[varname])
1954 1954 except:
1955 1955 value = self._simple_error()
1956 1956 out[varname] = value
1957 1957 return out
1958 1958
1959 1959 def user_expressions(self, expressions):
1960 1960 """Evaluate a dict of expressions in the user's namespace.
1961 1961
1962 1962 Parameters
1963 1963 ----------
1964 1964 expressions : dict
1965 1965 A dict with string keys and string values. The expression values
1966 1966 should be valid Python expressions, each of which will be evaluated
1967 1967 in the user namespace.
1968 1968
1969 1969 Returns
1970 1970 -------
1971 1971 A dict, keyed like the input expressions dict, with the repr() of each
1972 1972 value.
1973 1973 """
1974 1974 out = {}
1975 1975 user_ns = self.user_ns
1976 1976 global_ns = self.user_global_ns
1977 1977 for key, expr in expressions.iteritems():
1978 1978 try:
1979 1979 value = repr(eval(expr, global_ns, user_ns))
1980 1980 except:
1981 1981 value = self._simple_error()
1982 1982 out[key] = value
1983 1983 return out
1984 1984
1985 1985 #-------------------------------------------------------------------------
1986 1986 # Things related to the running of code
1987 1987 #-------------------------------------------------------------------------
1988 1988
1989 1989 def ex(self, cmd):
1990 1990 """Execute a normal python statement in user namespace."""
1991 1991 with nested(self.builtin_trap,):
1992 1992 exec cmd in self.user_global_ns, self.user_ns
1993 1993
1994 1994 def ev(self, expr):
1995 1995 """Evaluate python expression expr in user namespace.
1996 1996
1997 1997 Returns the result of evaluation
1998 1998 """
1999 1999 with nested(self.builtin_trap,):
2000 2000 return eval(expr, self.user_global_ns, self.user_ns)
2001 2001
2002 2002 def safe_execfile(self, fname, *where, **kw):
2003 2003 """A safe version of the builtin execfile().
2004 2004
2005 2005 This version will never throw an exception, but instead print
2006 2006 helpful error messages to the screen. This only works on pure
2007 2007 Python files with the .py extension.
2008 2008
2009 2009 Parameters
2010 2010 ----------
2011 2011 fname : string
2012 2012 The name of the file to be executed.
2013 2013 where : tuple
2014 2014 One or two namespaces, passed to execfile() as (globals,locals).
2015 2015 If only one is given, it is passed as both.
2016 2016 exit_ignore : bool (False)
2017 2017 If True, then silence SystemExit for non-zero status (it is always
2018 2018 silenced for zero status, as it is so common).
2019 2019 """
2020 2020 kw.setdefault('exit_ignore', False)
2021 2021
2022 2022 fname = os.path.abspath(os.path.expanduser(fname))
2023 2023 # Make sure we have a .py file
2024 2024 if not fname.endswith('.py'):
2025 2025 warn('File must end with .py to be run using execfile: <%s>' % fname)
2026 2026
2027 2027 # Make sure we can open the file
2028 2028 try:
2029 2029 with open(fname) as thefile:
2030 2030 pass
2031 2031 except:
2032 2032 warn('Could not open file <%s> for safe execution.' % fname)
2033 2033 return
2034 2034
2035 2035 # Find things also in current directory. This is needed to mimic the
2036 2036 # behavior of running a script from the system command line, where
2037 2037 # Python inserts the script's directory into sys.path
2038 2038 dname = os.path.dirname(fname)
2039 2039
2040 2040 if isinstance(fname, unicode):
2041 2041 # execfile uses default encoding instead of filesystem encoding
2042 2042 # so unicode filenames will fail
2043 2043 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2044 2044
2045 2045 with prepended_to_syspath(dname):
2046 2046 try:
2047 2047 execfile(fname,*where)
2048 2048 except SystemExit, status:
2049 2049 # If the call was made with 0 or None exit status (sys.exit(0)
2050 2050 # or sys.exit() ), don't bother showing a traceback, as both of
2051 2051 # these are considered normal by the OS:
2052 2052 # > python -c'import sys;sys.exit(0)'; echo $?
2053 2053 # 0
2054 2054 # > python -c'import sys;sys.exit()'; echo $?
2055 2055 # 0
2056 2056 # For other exit status, we show the exception unless
2057 2057 # explicitly silenced, but only in short form.
2058 2058 if status.code not in (0, None) and not kw['exit_ignore']:
2059 2059 self.showtraceback(exception_only=True)
2060 2060 except:
2061 2061 self.showtraceback()
2062 2062
2063 2063 def safe_execfile_ipy(self, fname):
2064 2064 """Like safe_execfile, but for .ipy files with IPython syntax.
2065 2065
2066 2066 Parameters
2067 2067 ----------
2068 2068 fname : str
2069 2069 The name of the file to execute. The filename must have a
2070 2070 .ipy extension.
2071 2071 """
2072 2072 fname = os.path.abspath(os.path.expanduser(fname))
2073 2073
2074 2074 # Make sure we have a .py file
2075 2075 if not fname.endswith('.ipy'):
2076 2076 warn('File must end with .py to be run using execfile: <%s>' % fname)
2077 2077
2078 2078 # Make sure we can open the file
2079 2079 try:
2080 2080 with open(fname) as thefile:
2081 2081 pass
2082 2082 except:
2083 2083 warn('Could not open file <%s> for safe execution.' % fname)
2084 2084 return
2085 2085
2086 2086 # Find things also in current directory. This is needed to mimic the
2087 2087 # behavior of running a script from the system command line, where
2088 2088 # Python inserts the script's directory into sys.path
2089 2089 dname = os.path.dirname(fname)
2090 2090
2091 2091 with prepended_to_syspath(dname):
2092 2092 try:
2093 2093 with open(fname) as thefile:
2094 2094 # self.run_cell currently captures all exceptions
2095 2095 # raised in user code. It would be nice if there were
2096 2096 # versions of runlines, execfile that did raise, so
2097 2097 # we could catch the errors.
2098 2098 self.run_cell(thefile.read(), store_history=False)
2099 2099 except:
2100 2100 self.showtraceback()
2101 2101 warn('Unknown failure executing file: <%s>' % fname)
2102 2102
2103 2103 def run_cell_NODE(self, cell, store_history=True):
2104 2104 """Run a complete IPython cell.
2105 2105
2106 2106 Parameters
2107 2107 ----------
2108 2108 cell : str
2109 2109 The code (including IPython code such as %magic functions) to run.
2110 2110 store_history : bool
2111 2111 If True, the raw and translated cell will be stored in IPython's
2112 2112 history. For user code calling back into IPython's machinery, this
2113 2113 should be set to False.
2114 2114 """
2115 2115 raw_cell = cell
2116 2116 with self.builtin_trap:
2117 2117 cell = self.prefilter_manager.prefilter_lines(cell)
2118 2118
2119 2119 # Store raw and processed history
2120 2120 if store_history:
2121 2121 self.history_manager.store_inputs(self.execution_count,
2122 2122 cell, raw_cell)
2123 2123
2124 2124 self.logger.log(cell, raw_cell)
2125 2125
2126 2126 with self.display_trap:
2127 2127 try:
2128 nodes = self.input_splitter.ast_nodes(cell)
2128 code_ast = ast.parse(cell)
2129 2129 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2130 2130 # Case 1
2131 2131 self.showsyntaxerror(filename)
2132 2132 return None
2133 2133
2134 2134 interactivity = 1 # Last node to be run interactive
2135 2135 if len(cell.splitlines()) == 1:
2136 2136 interactivity = 2 # Single line; run fully interactive
2137 2137
2138 self.run_ast_nodes(nodes, interactivity)
2138 self.run_ast_nodes(code_ast.body, interactivity)
2139 2139
2140 2140 if store_history:
2141 2141 # Write output to the database. Does nothing unless
2142 2142 # history output logging is enabled.
2143 2143 self.history_manager.store_output(self.execution_count)
2144 2144 # Each cell is a *single* input, regardless of how many lines it has
2145 2145 self.execution_count += 1
2146 2146
2147 2147 def run_ast_nodes(self, nodelist, interactivity=1):
2148 2148 """Run a sequence of AST nodes. The execution mode depends on the
2149 2149 interactivity parameter.
2150 2150
2151 2151 Parameters
2152 2152 ----------
2153 2153 nodelist : list
2154 2154 A sequence of AST nodes to run.
2155 2155 interactivity : int
2156 2156 At 0, all nodes are run in 'exec' mode. At '1', the last node alone
2157 2157 is run in interactive mode (so the result of an expression is shown).
2158 2158 At 2, all nodes are run in interactive mode.
2159 2159 """
2160 2160 if not nodelist:
2161 2161 return
2162 2162
2163 2163 if interactivity == 0:
2164 2164 to_run_exec, to_run_interactive = nodelist, []
2165 2165 elif interactivity == 1:
2166 2166 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2167 2167 else:
2168 2168 to_run_exec, to_run_interactive = [], nodelist
2169 2169
2170 2170 if to_run_exec:
2171 2171 mod = ast.Module(to_run_exec)
2172 2172 name = "<ipython-prompt-%d-exec>" % self.execution_count
2173 2173 self.code_to_run = code = compile(mod, name, "exec")
2174 2174 if self.run_code(code) == 1:
2175 2175 return
2176 2176
2177 2177 if to_run_interactive:
2178 2178 mod = ast.Interactive(to_run_interactive)
2179 2179 name = "<ipython-prompt-%d-interactive>" % self.execution_count
2180 2180 self.code_to_run = code = compile(mod, name, "single")
2181 2181 return self.run_code(code)
2182 2182
2183 2183
2184 2184 def run_cell(self, cell, store_history=True):
2185 2185 """Run the contents of an entire multiline 'cell' of code, and store it
2186 2186 in the history.
2187 2187
2188 2188 The cell is split into separate blocks which can be executed
2189 2189 individually. Then, based on how many blocks there are, they are
2190 2190 executed as follows:
2191 2191
2192 2192 - A single block: 'single' mode. If it is also a single line, dynamic
2193 2193 transformations, including automagic and macros, will be applied.
2194 2194
2195 2195 If there's more than one block, it depends:
2196 2196
2197 2197 - if the last one is no more than two lines long, run all but the last
2198 2198 in 'exec' mode and the very last one in 'single' mode. This makes it
2199 2199 easy to type simple expressions at the end to see computed values. -
2200 2200 otherwise (last one is also multiline), run all in 'exec' mode
2201 2201
2202 2202 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2203 2203 results are displayed and output prompts are computed. In 'exec' mode,
2204 2204 no results are displayed unless :func:`print` is called explicitly;
2205 2205 this mode is more akin to running a script.
2206 2206
2207 2207 Parameters
2208 2208 ----------
2209 2209 cell : str
2210 2210 A single or multiline string.
2211 2211 """
2212 2212 # Store the untransformed code
2213 2213 raw_cell = cell
2214 2214
2215 2215 # Code transformation and execution must take place with our
2216 2216 # modifications to builtins.
2217 2217 with self.builtin_trap:
2218 2218
2219 2219 # We need to break up the input into executable blocks that can
2220 2220 # be runin 'single' mode, to provide comfortable user behavior.
2221 2221 blocks = self.input_splitter.split_blocks(cell)
2222 2222
2223 2223 if not blocks: # Blank cell
2224 2224 return
2225 2225
2226 2226 # We only do dynamic transforms on a single line. But a macro
2227 2227 # can be expanded to several lines, so we need to split it
2228 2228 # into input blocks again.
2229 2229 if len(cell.splitlines()) <= 1:
2230 2230 cell = self.prefilter_manager.prefilter_line(blocks[0])
2231 2231 blocks = self.input_splitter.split_blocks(cell)
2232 2232
2233 2233 # Store the 'ipython' version of the cell as well, since
2234 2234 # that's what needs to go into the translated history and get
2235 2235 # executed (the original cell may contain non-python syntax).
2236 2236 cell = ''.join(blocks)
2237 2237
2238 2238 # Store raw and processed history
2239 2239 if store_history:
2240 2240 self.history_manager.store_inputs(self.execution_count,
2241 2241 cell, raw_cell)
2242 2242
2243 2243 self.logger.log(cell, raw_cell)
2244 2244
2245 2245 # All user code execution should take place with our
2246 2246 # modified displayhook.
2247 2247 with self.display_trap:
2248 2248 # Single-block input should behave like an interactive prompt
2249 2249 if len(blocks) == 1:
2250 2250 out = self.run_source(blocks[0])
2251 2251 # Write output to the database. Does nothing unless
2252 2252 # history output logging is enabled.
2253 2253 if store_history:
2254 2254 self.history_manager.store_output(self.execution_count)
2255 2255 # Since we return here, we need to update the
2256 2256 # execution count
2257 2257 self.execution_count += 1
2258 2258 return out
2259 2259
2260 2260 # In multi-block input, if the last block is a simple (one-two
2261 2261 # lines) expression, run it in single mode so it produces output.
2262 2262 # Otherwise just run it all in 'exec' mode. This seems like a
2263 2263 # reasonable usability design.
2264 2264 last = blocks[-1]
2265 2265 last_nlines = len(last.splitlines())
2266 2266
2267 2267 if last_nlines < 2:
2268 2268 # Here we consider the cell split between 'body' and 'last',
2269 2269 # store all history and execute 'body', and if successful, then
2270 2270 # proceed to execute 'last'.
2271 2271
2272 2272 # Get the main body to run as a cell
2273 2273 ipy_body = ''.join(blocks[:-1])
2274 2274 retcode = self.run_source(ipy_body, symbol='exec',
2275 2275 post_execute=False)
2276 2276 if retcode==0:
2277 2277 # Last expression compiled as 'single' so it
2278 2278 # produces output
2279 2279 self.run_source(last)
2280 2280 else:
2281 2281 # Run the whole cell as one entity, storing both raw and
2282 2282 # processed input in history
2283 2283 self.run_source(cell, symbol='exec')
2284 2284
2285 2285 # Write output to the database. Does nothing unless
2286 2286 # history output logging is enabled.
2287 2287 if store_history:
2288 2288 self.history_manager.store_output(self.execution_count)
2289 2289 # Each cell is a *single* input, regardless of how many lines it has
2290 2290 self.execution_count += 1
2291 2291
2292 2292 # PENDING REMOVAL: this method is slated for deletion, once our new
2293 2293 # input logic has been 100% moved to frontends and is stable.
2294 2294 def runlines(self, lines, clean=False):
2295 2295 """Run a string of one or more lines of source.
2296 2296
2297 2297 This method is capable of running a string containing multiple source
2298 2298 lines, as if they had been entered at the IPython prompt. Since it
2299 2299 exposes IPython's processing machinery, the given strings can contain
2300 2300 magic calls (%magic), special shell access (!cmd), etc.
2301 2301 """
2302 2302
2303 2303 if not isinstance(lines, (list, tuple)):
2304 2304 lines = lines.splitlines()
2305 2305
2306 2306 if clean:
2307 2307 lines = self._cleanup_ipy_script(lines)
2308 2308
2309 2309 # We must start with a clean buffer, in case this is run from an
2310 2310 # interactive IPython session (via a magic, for example).
2311 2311 self.reset_buffer()
2312 2312
2313 2313 # Since we will prefilter all lines, store the user's raw input too
2314 2314 # before we apply any transformations
2315 2315 self.buffer_raw[:] = [ l+'\n' for l in lines]
2316 2316
2317 2317 more = False
2318 2318 prefilter_lines = self.prefilter_manager.prefilter_lines
2319 2319 with nested(self.builtin_trap, self.display_trap):
2320 2320 for line in lines:
2321 2321 # skip blank lines so we don't mess up the prompt counter, but
2322 2322 # do NOT skip even a blank line if we are in a code block (more
2323 2323 # is true)
2324 2324
2325 2325 if line or more:
2326 2326 more = self.push_line(prefilter_lines(line, more))
2327 2327 # IPython's run_source returns None if there was an error
2328 2328 # compiling the code. This allows us to stop processing
2329 2329 # right away, so the user gets the error message at the
2330 2330 # right place.
2331 2331 if more is None:
2332 2332 break
2333 2333 # final newline in case the input didn't have it, so that the code
2334 2334 # actually does get executed
2335 2335 if more:
2336 2336 self.push_line('\n')
2337 2337
2338 2338 def run_source(self, source, filename=None,
2339 2339 symbol='single', post_execute=True):
2340 2340 """Compile and run some source in the interpreter.
2341 2341
2342 2342 Arguments are as for compile_command().
2343 2343
2344 2344 One several things can happen:
2345 2345
2346 2346 1) The input is incorrect; compile_command() raised an
2347 2347 exception (SyntaxError or OverflowError). A syntax traceback
2348 2348 will be printed by calling the showsyntaxerror() method.
2349 2349
2350 2350 2) The input is incomplete, and more input is required;
2351 2351 compile_command() returned None. Nothing happens.
2352 2352
2353 2353 3) The input is complete; compile_command() returned a code
2354 2354 object. The code is executed by calling self.run_code() (which
2355 2355 also handles run-time exceptions, except for SystemExit).
2356 2356
2357 2357 The return value is:
2358 2358
2359 2359 - True in case 2
2360 2360
2361 2361 - False in the other cases, unless an exception is raised, where
2362 2362 None is returned instead. This can be used by external callers to
2363 2363 know whether to continue feeding input or not.
2364 2364
2365 2365 The return value can be used to decide whether to use sys.ps1 or
2366 2366 sys.ps2 to prompt the next line."""
2367 2367
2368 2368 # We need to ensure that the source is unicode from here on.
2369 2369 if type(source)==str:
2370 2370 usource = source.decode(self.stdin_encoding)
2371 2371 else:
2372 2372 usource = source
2373 2373
2374 2374 if False: # dbg
2375 2375 print 'Source:', repr(source) # dbg
2376 2376 print 'USource:', repr(usource) # dbg
2377 2377 print 'type:', type(source) # dbg
2378 2378 print 'encoding', self.stdin_encoding # dbg
2379 2379
2380 2380 try:
2381 2381 code = self.compile(usource, symbol, self.execution_count)
2382 2382 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2383 2383 # Case 1
2384 2384 self.showsyntaxerror(filename)
2385 2385 return None
2386 2386
2387 2387 if code is None:
2388 2388 # Case 2
2389 2389 return True
2390 2390
2391 2391 # Case 3
2392 2392 # We store the code object so that threaded shells and
2393 2393 # custom exception handlers can access all this info if needed.
2394 2394 # The source corresponding to this can be obtained from the
2395 2395 # buffer attribute as '\n'.join(self.buffer).
2396 2396 self.code_to_run = code
2397 2397 # now actually execute the code object
2398 2398 if self.run_code(code, post_execute) == 0:
2399 2399 return False
2400 2400 else:
2401 2401 return None
2402 2402
2403 2403 # For backwards compatibility
2404 2404 runsource = run_source
2405 2405
2406 2406 def run_code(self, code_obj, post_execute=True):
2407 2407 """Execute a code object.
2408 2408
2409 2409 When an exception occurs, self.showtraceback() is called to display a
2410 2410 traceback.
2411 2411
2412 2412 Return value: a flag indicating whether the code to be run completed
2413 2413 successfully:
2414 2414
2415 2415 - 0: successful execution.
2416 2416 - 1: an error occurred.
2417 2417 """
2418 2418
2419 2419 # Set our own excepthook in case the user code tries to call it
2420 2420 # directly, so that the IPython crash handler doesn't get triggered
2421 2421 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2422 2422
2423 2423 # we save the original sys.excepthook in the instance, in case config
2424 2424 # code (such as magics) needs access to it.
2425 2425 self.sys_excepthook = old_excepthook
2426 2426 outflag = 1 # happens in more places, so it's easier as default
2427 2427 try:
2428 2428 try:
2429 2429 self.hooks.pre_run_code_hook()
2430 2430 #rprint('Running code', repr(code_obj)) # dbg
2431 2431 exec code_obj in self.user_global_ns, self.user_ns
2432 2432 finally:
2433 2433 # Reset our crash handler in place
2434 2434 sys.excepthook = old_excepthook
2435 2435 except SystemExit:
2436 2436 self.reset_buffer()
2437 2437 self.showtraceback(exception_only=True)
2438 2438 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2439 2439 except self.custom_exceptions:
2440 2440 etype,value,tb = sys.exc_info()
2441 2441 self.CustomTB(etype,value,tb)
2442 2442 except:
2443 2443 self.showtraceback()
2444 2444 else:
2445 2445 outflag = 0
2446 2446 if softspace(sys.stdout, 0):
2447 2447 print
2448 2448
2449 2449 # Execute any registered post-execution functions. Here, any errors
2450 2450 # are reported only minimally and just on the terminal, because the
2451 2451 # main exception channel may be occupied with a user traceback.
2452 2452 # FIXME: we need to think this mechanism a little more carefully.
2453 2453 if post_execute:
2454 2454 for func in self._post_execute:
2455 2455 try:
2456 2456 func()
2457 2457 except:
2458 2458 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2459 2459 func
2460 2460 print >> io.Term.cout, head
2461 2461 print >> io.Term.cout, self._simple_error()
2462 2462 print >> io.Term.cout, 'Removing from post_execute'
2463 2463 self._post_execute.remove(func)
2464 2464
2465 2465 # Flush out code object which has been run (and source)
2466 2466 self.code_to_run = None
2467 2467 return outflag
2468 2468
2469 2469 # For backwards compatibility
2470 2470 runcode = run_code
2471 2471
2472 2472 # PENDING REMOVAL: this method is slated for deletion, once our new
2473 2473 # input logic has been 100% moved to frontends and is stable.
2474 2474 def push_line(self, line):
2475 2475 """Push a line to the interpreter.
2476 2476
2477 2477 The line should not have a trailing newline; it may have
2478 2478 internal newlines. The line is appended to a buffer and the
2479 2479 interpreter's run_source() method is called with the
2480 2480 concatenated contents of the buffer as source. If this
2481 2481 indicates that the command was executed or invalid, the buffer
2482 2482 is reset; otherwise, the command is incomplete, and the buffer
2483 2483 is left as it was after the line was appended. The return
2484 2484 value is 1 if more input is required, 0 if the line was dealt
2485 2485 with in some way (this is the same as run_source()).
2486 2486 """
2487 2487
2488 2488 # autoindent management should be done here, and not in the
2489 2489 # interactive loop, since that one is only seen by keyboard input. We
2490 2490 # need this done correctly even for code run via runlines (which uses
2491 2491 # push).
2492 2492
2493 2493 #print 'push line: <%s>' % line # dbg
2494 2494 self.buffer.append(line)
2495 2495 full_source = '\n'.join(self.buffer)
2496 2496 more = self.run_source(full_source, self.filename)
2497 2497 if not more:
2498 2498 self.history_manager.store_inputs(self.execution_count,
2499 2499 '\n'.join(self.buffer_raw), full_source)
2500 2500 self.reset_buffer()
2501 2501 self.execution_count += 1
2502 2502 return more
2503 2503
2504 2504 def reset_buffer(self):
2505 2505 """Reset the input buffer."""
2506 2506 self.buffer[:] = []
2507 2507 self.buffer_raw[:] = []
2508 2508 self.input_splitter.reset()
2509 2509
2510 2510 # For backwards compatibility
2511 2511 resetbuffer = reset_buffer
2512 2512
2513 2513 def _is_secondary_block_start(self, s):
2514 2514 if not s.endswith(':'):
2515 2515 return False
2516 2516 if (s.startswith('elif') or
2517 2517 s.startswith('else') or
2518 2518 s.startswith('except') or
2519 2519 s.startswith('finally')):
2520 2520 return True
2521 2521
2522 2522 def _cleanup_ipy_script(self, script):
2523 2523 """Make a script safe for self.runlines()
2524 2524
2525 2525 Currently, IPython is lines based, with blocks being detected by
2526 2526 empty lines. This is a problem for block based scripts that may
2527 2527 not have empty lines after blocks. This script adds those empty
2528 2528 lines to make scripts safe for running in the current line based
2529 2529 IPython.
2530 2530 """
2531 2531 res = []
2532 2532 lines = script.splitlines()
2533 2533 level = 0
2534 2534
2535 2535 for l in lines:
2536 2536 lstripped = l.lstrip()
2537 2537 stripped = l.strip()
2538 2538 if not stripped:
2539 2539 continue
2540 2540 newlevel = len(l) - len(lstripped)
2541 2541 if level > 0 and newlevel == 0 and \
2542 2542 not self._is_secondary_block_start(stripped):
2543 2543 # add empty line
2544 2544 res.append('')
2545 2545 res.append(l)
2546 2546 level = newlevel
2547 2547
2548 2548 return '\n'.join(res) + '\n'
2549 2549
2550 2550 #-------------------------------------------------------------------------
2551 2551 # Things related to GUI support and pylab
2552 2552 #-------------------------------------------------------------------------
2553 2553
2554 2554 def enable_pylab(self, gui=None):
2555 2555 raise NotImplementedError('Implement enable_pylab in a subclass')
2556 2556
2557 2557 #-------------------------------------------------------------------------
2558 2558 # Utilities
2559 2559 #-------------------------------------------------------------------------
2560 2560
2561 2561 def var_expand(self,cmd,depth=0):
2562 2562 """Expand python variables in a string.
2563 2563
2564 2564 The depth argument indicates how many frames above the caller should
2565 2565 be walked to look for the local namespace where to expand variables.
2566 2566
2567 2567 The global namespace for expansion is always the user's interactive
2568 2568 namespace.
2569 2569 """
2570 2570 res = ItplNS(cmd, self.user_ns, # globals
2571 2571 # Skip our own frame in searching for locals:
2572 2572 sys._getframe(depth+1).f_locals # locals
2573 2573 )
2574 2574 return str(res).decode(res.codec)
2575 2575
2576 2576 def mktempfile(self, data=None, prefix='ipython_edit_'):
2577 2577 """Make a new tempfile and return its filename.
2578 2578
2579 2579 This makes a call to tempfile.mktemp, but it registers the created
2580 2580 filename internally so ipython cleans it up at exit time.
2581 2581
2582 2582 Optional inputs:
2583 2583
2584 2584 - data(None): if data is given, it gets written out to the temp file
2585 2585 immediately, and the file is closed again."""
2586 2586
2587 2587 filename = tempfile.mktemp('.py', prefix)
2588 2588 self.tempfiles.append(filename)
2589 2589
2590 2590 if data:
2591 2591 tmp_file = open(filename,'w')
2592 2592 tmp_file.write(data)
2593 2593 tmp_file.close()
2594 2594 return filename
2595 2595
2596 2596 # TODO: This should be removed when Term is refactored.
2597 2597 def write(self,data):
2598 2598 """Write a string to the default output"""
2599 2599 io.Term.cout.write(data)
2600 2600
2601 2601 # TODO: This should be removed when Term is refactored.
2602 2602 def write_err(self,data):
2603 2603 """Write a string to the default error output"""
2604 2604 io.Term.cerr.write(data)
2605 2605
2606 2606 def ask_yes_no(self,prompt,default=True):
2607 2607 if self.quiet:
2608 2608 return True
2609 2609 return ask_yes_no(prompt,default)
2610 2610
2611 2611 def show_usage(self):
2612 2612 """Show a usage message"""
2613 2613 page.page(IPython.core.usage.interactive_usage)
2614 2614
2615 2615 def find_user_code(self, target, raw=True):
2616 2616 """Get a code string from history, file, or a string or macro.
2617 2617
2618 2618 This is mainly used by magic functions.
2619 2619
2620 2620 Parameters
2621 2621 ----------
2622 2622 target : str
2623 2623 A string specifying code to retrieve. This will be tried respectively
2624 2624 as: ranges of input history (see %history for syntax), a filename, or
2625 2625 an expression evaluating to a string or Macro in the user namespace.
2626 2626 raw : bool
2627 2627 If true (default), retrieve raw history. Has no effect on the other
2628 2628 retrieval mechanisms.
2629 2629
2630 2630 Returns
2631 2631 -------
2632 2632 A string of code.
2633 2633
2634 2634 ValueError is raised if nothing is found, and TypeError if it evaluates
2635 2635 to an object of another type. In each case, .args[0] is a printable
2636 2636 message.
2637 2637 """
2638 2638 code = self.extract_input_lines(target, raw=raw) # Grab history
2639 2639 if code:
2640 2640 return code
2641 2641 if os.path.isfile(target): # Read file
2642 2642 return open(target, "r").read()
2643 2643
2644 2644 try: # User namespace
2645 2645 codeobj = eval(target, self.user_ns)
2646 2646 except Exception:
2647 2647 raise ValueError(("'%s' was not found in history, as a file, nor in"
2648 2648 " the user namespace.") % target)
2649 2649 if isinstance(codeobj, basestring):
2650 2650 return codeobj
2651 2651 elif isinstance(codeobj, Macro):
2652 2652 return codeobj.value
2653 2653
2654 2654 raise TypeError("%s is neither a string nor a macro." % target,
2655 2655 codeobj)
2656 2656
2657 2657 #-------------------------------------------------------------------------
2658 2658 # Things related to IPython exiting
2659 2659 #-------------------------------------------------------------------------
2660 2660 def atexit_operations(self):
2661 2661 """This will be executed at the time of exit.
2662 2662
2663 2663 Cleanup operations and saving of persistent data that is done
2664 2664 unconditionally by IPython should be performed here.
2665 2665
2666 2666 For things that may depend on startup flags or platform specifics (such
2667 2667 as having readline or not), register a separate atexit function in the
2668 2668 code that has the appropriate information, rather than trying to
2669 2669 clutter
2670 2670 """
2671 2671 # Cleanup all tempfiles left around
2672 2672 for tfile in self.tempfiles:
2673 2673 try:
2674 2674 os.unlink(tfile)
2675 2675 except OSError:
2676 2676 pass
2677 2677
2678 2678 # Close the history session (this stores the end time and line count)
2679 2679 self.history_manager.end_session()
2680 2680
2681 2681 # Clear all user namespaces to release all references cleanly.
2682 2682 self.reset(new_session=False)
2683 2683
2684 2684 # Run user hooks
2685 2685 self.hooks.shutdown_hook()
2686 2686
2687 2687 def cleanup(self):
2688 2688 self.restore_sys_module_state()
2689 2689
2690 2690
2691 2691 class InteractiveShellABC(object):
2692 2692 """An abstract base class for InteractiveShell."""
2693 2693 __metaclass__ = abc.ABCMeta
2694 2694
2695 2695 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now