##// END OF EJS Templates
Fix bugs in x=!cmd; we can't use pexpect at all....
Fernando Perez -
Show More
@@ -1,960 +1,956 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
64 64 #-----------------------------------------------------------------------------
65 65 # Imports
66 66 #-----------------------------------------------------------------------------
67 67 # stdlib
68 68 import codeop
69 69 import re
70 70 import sys
71 71
72 72 # IPython modules
73 73 from IPython.utils.text import make_quoted_expr
74 74 #-----------------------------------------------------------------------------
75 75 # Globals
76 76 #-----------------------------------------------------------------------------
77 77
78 78 # The escape sequences that define the syntax transformations IPython will
79 79 # apply to user input. These can NOT be just changed here: many regular
80 80 # expressions and other parts of the code may use their hardcoded values, and
81 81 # for all intents and purposes they constitute the 'IPython syntax', so they
82 82 # should be considered fixed.
83 83
84 84 ESC_SHELL = '!'
85 85 ESC_SH_CAP = '!!'
86 86 ESC_HELP = '?'
87 87 ESC_HELP2 = '??'
88 88 ESC_MAGIC = '%'
89 89 ESC_QUOTE = ','
90 90 ESC_QUOTE2 = ';'
91 91 ESC_PAREN = '/'
92 92
93 93 #-----------------------------------------------------------------------------
94 94 # Utilities
95 95 #-----------------------------------------------------------------------------
96 96
97 97 # FIXME: These are general-purpose utilities that later can be moved to the
98 98 # general ward. Kept here for now because we're being very strict about test
99 99 # coverage with this code, and this lets us ensure that we keep 100% coverage
100 100 # while developing.
101 101
102 102 # compiled regexps for autoindent management
103 103 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
104 104 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
105 105
106 106 # regexp to match pure comment lines so we don't accidentally insert 'if 1:'
107 107 # before pure comments
108 108 comment_line_re = re.compile('^\s*\#')
109 109
110 110
111 111 def num_ini_spaces(s):
112 112 """Return the number of initial spaces in a string.
113 113
114 114 Note that tabs are counted as a single space. For now, we do *not* support
115 115 mixing of tabs and spaces in the user's input.
116 116
117 117 Parameters
118 118 ----------
119 119 s : string
120 120
121 121 Returns
122 122 -------
123 123 n : int
124 124 """
125 125
126 126 ini_spaces = ini_spaces_re.match(s)
127 127 if ini_spaces:
128 128 return ini_spaces.end()
129 129 else:
130 130 return 0
131 131
132 132
133 133 def remove_comments(src):
134 134 """Remove all comments from input source.
135 135
136 136 Note: comments are NOT recognized inside of strings!
137 137
138 138 Parameters
139 139 ----------
140 140 src : string
141 141 A single or multiline input string.
142 142
143 143 Returns
144 144 -------
145 145 String with all Python comments removed.
146 146 """
147 147
148 148 return re.sub('#.*', '', src)
149 149
150 150
151 151 def get_input_encoding():
152 152 """Return the default standard input encoding.
153 153
154 154 If sys.stdin has no encoding, 'ascii' is returned."""
155 155 # There are strange environments for which sys.stdin.encoding is None. We
156 156 # ensure that a valid encoding is returned.
157 157 encoding = getattr(sys.stdin, 'encoding', None)
158 158 if encoding is None:
159 159 encoding = 'ascii'
160 160 return encoding
161 161
162 162 #-----------------------------------------------------------------------------
163 163 # Classes and functions for normal Python syntax handling
164 164 #-----------------------------------------------------------------------------
165 165
166 166 # HACK! This implementation, written by Robert K a while ago using the
167 167 # compiler module, is more robust than the other one below, but it expects its
168 168 # input to be pure python (no ipython syntax). For now we're using it as a
169 169 # second-pass splitter after the first pass transforms the input to pure
170 170 # python.
171 171
172 172 def split_blocks(python):
173 173 """ Split multiple lines of code into discrete commands that can be
174 174 executed singly.
175 175
176 176 Parameters
177 177 ----------
178 178 python : str
179 179 Pure, exec'able Python code.
180 180
181 181 Returns
182 182 -------
183 183 commands : list of str
184 184 Separate commands that can be exec'ed independently.
185 185 """
186 186
187 187 import compiler
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 does not like unicode. We need to convert
199 199 # it encode it:
200 200 if isinstance(python, unicode):
201 201 # Use the utf-8-sig BOM so the compiler detects this a UTF-8
202 202 # encode string.
203 203 python = '\xef\xbb\xbf' + python.encode('utf-8')
204 204
205 205 # The compiler module will parse the code into an abstract syntax tree.
206 206 # This has a bug with str("a\nb"), but not str("""a\nb""")!!!
207 207 try:
208 208 ast = compiler.parse(python)
209 209 except:
210 210 return [python_ori]
211 211
212 212 # Uncomment to help debug the ast tree
213 213 # for n in ast.node:
214 214 # print n.lineno,'->',n
215 215
216 216 # Each separate command is available by iterating over ast.node. The
217 217 # lineno attribute is the line number (1-indexed) beginning the commands
218 218 # suite.
219 219 # lines ending with ";" yield a Discard Node that doesn't have a lineno
220 220 # attribute. These nodes can and should be discarded. But there are
221 221 # other situations that cause Discard nodes that shouldn't be discarded.
222 222 # We might eventually discover other cases where lineno is None and have
223 223 # to put in a more sophisticated test.
224 224 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
225 225
226 226 # When we finally get the slices, we will need to slice all the way to
227 227 # the end even though we don't have a line number for it. Fortunately,
228 228 # None does the job nicely.
229 229 linenos.append(None)
230 230
231 231 # Same problem at the other end: sometimes the ast tree has its
232 232 # first complete statement not starting on line 0. In this case
233 233 # we might miss part of it. This fixes ticket 266993. Thanks Gael!
234 234 linenos[0] = 0
235 235
236 236 lines = python.splitlines()
237 237
238 238 # Create a list of atomic commands.
239 239 cmds = []
240 240 for i, j in zip(linenos[:-1], linenos[1:]):
241 241 cmd = lines[i:j]
242 242 if cmd:
243 243 cmds.append('\n'.join(cmd)+'\n')
244 244
245 245 return cmds
246 246
247 247
248 248 class InputSplitter(object):
249 249 """An object that can split Python source input in executable blocks.
250 250
251 251 This object is designed to be used in one of two basic modes:
252 252
253 253 1. By feeding it python source line-by-line, using :meth:`push`. In this
254 254 mode, it will return on each push whether the currently pushed code
255 255 could be executed already. In addition, it provides a method called
256 256 :meth:`push_accepts_more` that can be used to query whether more input
257 257 can be pushed into a single interactive block.
258 258
259 259 2. By calling :meth:`split_blocks` with a single, multiline Python string,
260 260 that is then split into blocks each of which can be executed
261 261 interactively as a single statement.
262 262
263 263 This is a simple example of how an interactive terminal-based client can use
264 264 this tool::
265 265
266 266 isp = InputSplitter()
267 267 while isp.push_accepts_more():
268 268 indent = ' '*isp.indent_spaces
269 269 prompt = '>>> ' + indent
270 270 line = indent + raw_input(prompt)
271 271 isp.push(line)
272 272 print 'Input source was:\n', isp.source_reset(),
273 273 """
274 274 # Number of spaces of indentation computed from input that has been pushed
275 275 # so far. This is the attributes callers should query to get the current
276 276 # indentation level, in order to provide auto-indent facilities.
277 277 indent_spaces = 0
278 278 # String, indicating the default input encoding. It is computed by default
279 279 # at initialization time via get_input_encoding(), but it can be reset by a
280 280 # client with specific knowledge of the encoding.
281 281 encoding = ''
282 282 # String where the current full source input is stored, properly encoded.
283 283 # Reading this attribute is the normal way of querying the currently pushed
284 284 # source code, that has been properly encoded.
285 285 source = ''
286 286 # Code object corresponding to the current source. It is automatically
287 287 # synced to the source, so it can be queried at any time to obtain the code
288 288 # object; it will be None if the source doesn't compile to valid Python.
289 289 code = None
290 290 # Input mode
291 291 input_mode = 'line'
292 292
293 293 # Private attributes
294 294
295 295 # List with lines of input accumulated so far
296 296 _buffer = None
297 297 # Command compiler
298 298 _compile = None
299 299 # Mark when input has changed indentation all the way back to flush-left
300 300 _full_dedent = False
301 301 # Boolean indicating whether the current block is complete
302 302 _is_complete = None
303 303
304 304 def __init__(self, input_mode=None):
305 305 """Create a new InputSplitter instance.
306 306
307 307 Parameters
308 308 ----------
309 309 input_mode : str
310 310
311 311 One of ['line', 'block']; default is 'line'.
312 312
313 313 The input_mode parameter controls how new inputs are used when fed via
314 314 the :meth:`push` method:
315 315
316 316 - 'line': meant for line-oriented clients, inputs are appended one at a
317 317 time to the internal buffer and the whole buffer is compiled.
318 318
319 319 - 'block': meant for clients that can edit multi-line blocks of text at
320 320 a time. Each new input new input completely replaces all prior
321 321 inputs. Block mode is thus equivalent to prepending a full reset()
322 322 to every push() call.
323 323 """
324 324 self._buffer = []
325 325 self._compile = codeop.CommandCompiler()
326 326 self.encoding = get_input_encoding()
327 327 self.input_mode = InputSplitter.input_mode if input_mode is None \
328 328 else input_mode
329 329
330 330 def reset(self):
331 331 """Reset the input buffer and associated state."""
332 332 self.indent_spaces = 0
333 333 self._buffer[:] = []
334 334 self.source = ''
335 335 self.code = None
336 336 self._is_complete = False
337 337 self._full_dedent = False
338 338
339 339 def source_reset(self):
340 340 """Return the input source and perform a full reset.
341 341 """
342 342 out = self.source
343 343 self.reset()
344 344 return out
345 345
346 346 def push(self, lines):
347 347 """Push one ore more lines of input.
348 348
349 349 This stores the given lines and returns a status code indicating
350 350 whether the code forms a complete Python block or not.
351 351
352 352 Any exceptions generated in compilation are swallowed, but if an
353 353 exception was produced, the method returns True.
354 354
355 355 Parameters
356 356 ----------
357 357 lines : string
358 358 One or more lines of Python input.
359 359
360 360 Returns
361 361 -------
362 362 is_complete : boolean
363 363 True if the current input source (the result of the current input
364 364 plus prior inputs) forms a complete Python execution block. Note that
365 365 this value is also stored as a private attribute (_is_complete), so it
366 366 can be queried at any time.
367 367 """
368 368 if self.input_mode == 'block':
369 369 self.reset()
370 370
371 371 # If the source code has leading blanks, add 'if 1:\n' to it
372 372 # this allows execution of indented pasted code. It is tempting
373 373 # to add '\n' at the end of source to run commands like ' a=1'
374 374 # directly, but this fails for more complicated scenarios
375 375
376 376 if not self._buffer and lines[:1] in [' ', '\t'] and \
377 377 not comment_line_re.match(lines):
378 378 lines = 'if 1:\n%s' % lines
379 379
380 380 self._store(lines)
381 381 source = self.source
382 382
383 383 # Before calling _compile(), reset the code object to None so that if an
384 384 # exception is raised in compilation, we don't mislead by having
385 385 # inconsistent code/source attributes.
386 386 self.code, self._is_complete = None, None
387 387
388 388 self._update_indent(lines)
389 389 try:
390 390 self.code = self._compile(source)
391 391 # Invalid syntax can produce any of a number of different errors from
392 392 # inside the compiler, so we have to catch them all. Syntax errors
393 393 # immediately produce a 'ready' block, so the invalid Python can be
394 394 # sent to the kernel for evaluation with possible ipython
395 395 # special-syntax conversion.
396 396 except (SyntaxError, OverflowError, ValueError, TypeError,
397 397 MemoryError):
398 398 self._is_complete = True
399 399 else:
400 400 # Compilation didn't produce any exceptions (though it may not have
401 401 # given a complete code object)
402 402 self._is_complete = self.code is not None
403 403
404 404 return self._is_complete
405 405
406 406 def push_accepts_more(self):
407 407 """Return whether a block of interactive input can accept more input.
408 408
409 409 This method is meant to be used by line-oriented frontends, who need to
410 410 guess whether a block is complete or not based solely on prior and
411 411 current input lines. The InputSplitter considers it has a complete
412 412 interactive block and will not accept more input only when either a
413 413 SyntaxError is raised, or *all* of the following are true:
414 414
415 415 1. The input compiles to a complete statement.
416 416
417 417 2. The indentation level is flush-left (because if we are indented,
418 418 like inside a function definition or for loop, we need to keep
419 419 reading new input).
420 420
421 421 3. There is one extra line consisting only of whitespace.
422 422
423 423 Because of condition #3, this method should be used only by
424 424 *line-oriented* frontends, since it means that intermediate blank lines
425 425 are not allowed in function definitions (or any other indented block).
426 426
427 427 Block-oriented frontends that have a separate keyboard event to
428 428 indicate execution should use the :meth:`split_blocks` method instead.
429 429
430 430 If the current input produces a syntax error, this method immediately
431 431 returns False but does *not* raise the syntax error exception, as
432 432 typically clients will want to send invalid syntax to an execution
433 433 backend which might convert the invalid syntax into valid Python via
434 434 one of the dynamic IPython mechanisms.
435 435 """
436 436
437 437 if not self._is_complete:
438 438 return True
439 439
440 440 if self.indent_spaces==0:
441 441 return False
442 442
443 443 last_line = self.source.splitlines()[-1]
444 444 return bool(last_line and not last_line.isspace())
445 445
446 446 def split_blocks(self, lines):
447 447 """Split a multiline string into multiple input blocks.
448 448
449 449 Note: this method starts by performing a full reset().
450 450
451 451 Parameters
452 452 ----------
453 453 lines : str
454 454 A possibly multiline string.
455 455
456 456 Returns
457 457 -------
458 458 blocks : list
459 459 A list of strings, each possibly multiline. Each string corresponds
460 460 to a single block that can be compiled in 'single' mode (unless it
461 461 has a syntax error)."""
462 462
463 463 # This code is fairly delicate. If you make any changes here, make
464 464 # absolutely sure that you do run the full test suite and ALL tests
465 465 # pass.
466 466
467 467 self.reset()
468 468 blocks = []
469 469
470 470 # Reversed copy so we can use pop() efficiently and consume the input
471 471 # as a stack
472 472 lines = lines.splitlines()[::-1]
473 473 # Outer loop over all input
474 474 while lines:
475 475 #print 'Current lines:', lines # dbg
476 476 # Inner loop to build each block
477 477 while True:
478 478 # Safety exit from inner loop
479 479 if not lines:
480 480 break
481 481 # Grab next line but don't push it yet
482 482 next_line = lines.pop()
483 483 # Blank/empty lines are pushed as-is
484 484 if not next_line or next_line.isspace():
485 485 self.push(next_line)
486 486 continue
487 487
488 488 # Check indentation changes caused by the *next* line
489 489 indent_spaces, _full_dedent = self._find_indent(next_line)
490 490
491 491 # If the next line causes a dedent, it can be for two differnt
492 492 # reasons: either an explicit de-dent by the user or a
493 493 # return/raise/pass statement. These MUST be handled
494 494 # separately:
495 495 #
496 496 # 1. the first case is only detected when the actual explicit
497 497 # dedent happens, and that would be the *first* line of a *new*
498 498 # block. Thus, we must put the line back into the input buffer
499 499 # so that it starts a new block on the next pass.
500 500 #
501 501 # 2. the second case is detected in the line before the actual
502 502 # dedent happens, so , we consume the line and we can break out
503 503 # to start a new block.
504 504
505 505 # Case 1, explicit dedent causes a break.
506 506 # Note: check that we weren't on the very last line, else we'll
507 507 # enter an infinite loop adding/removing the last line.
508 508 if _full_dedent and lines and not next_line.startswith(' '):
509 509 lines.append(next_line)
510 510 break
511 511
512 512 # Otherwise any line is pushed
513 513 self.push(next_line)
514 514
515 515 # Case 2, full dedent with full block ready:
516 516 if _full_dedent or \
517 517 self.indent_spaces==0 and not self.push_accepts_more():
518 518 break
519 519 # Form the new block with the current source input
520 520 blocks.append(self.source_reset())
521 521
522 522 #return blocks
523 523 # HACK!!! Now that our input is in blocks but guaranteed to be pure
524 524 # python syntax, feed it back a second time through the AST-based
525 525 # splitter, which is more accurate than ours.
526 526 return split_blocks(''.join(blocks))
527 527
528 528 #------------------------------------------------------------------------
529 529 # Private interface
530 530 #------------------------------------------------------------------------
531 531
532 532 def _find_indent(self, line):
533 533 """Compute the new indentation level for a single line.
534 534
535 535 Parameters
536 536 ----------
537 537 line : str
538 538 A single new line of non-whitespace, non-comment Python input.
539 539
540 540 Returns
541 541 -------
542 542 indent_spaces : int
543 543 New value for the indent level (it may be equal to self.indent_spaces
544 544 if indentation doesn't change.
545 545
546 546 full_dedent : boolean
547 547 Whether the new line causes a full flush-left dedent.
548 548 """
549 549 indent_spaces = self.indent_spaces
550 550 full_dedent = self._full_dedent
551 551
552 552 inisp = num_ini_spaces(line)
553 553 if inisp < indent_spaces:
554 554 indent_spaces = inisp
555 555 if indent_spaces <= 0:
556 556 #print 'Full dedent in text',self.source # dbg
557 557 full_dedent = True
558 558
559 559 if line[-1] == ':':
560 560 indent_spaces += 4
561 561 elif dedent_re.match(line):
562 562 indent_spaces -= 4
563 563 if indent_spaces <= 0:
564 564 full_dedent = True
565 565
566 566 # Safety
567 567 if indent_spaces < 0:
568 568 indent_spaces = 0
569 569 #print 'safety' # dbg
570 570
571 571 return indent_spaces, full_dedent
572 572
573 573 def _update_indent(self, lines):
574 574 for line in remove_comments(lines).splitlines():
575 575 if line and not line.isspace():
576 576 self.indent_spaces, self._full_dedent = self._find_indent(line)
577 577
578 578 def _store(self, lines):
579 579 """Store one or more lines of input.
580 580
581 581 If input lines are not newline-terminated, a newline is automatically
582 582 appended."""
583 583
584 584 if lines.endswith('\n'):
585 585 self._buffer.append(lines)
586 586 else:
587 587 self._buffer.append(lines+'\n')
588 588 self._set_source()
589 589
590 590 def _set_source(self):
591 591 self.source = ''.join(self._buffer).encode(self.encoding)
592 592
593 593
594 594 #-----------------------------------------------------------------------------
595 595 # Functions and classes for IPython-specific syntactic support
596 596 #-----------------------------------------------------------------------------
597 597
598 598 # RegExp for splitting line contents into pre-char//first word-method//rest.
599 599 # For clarity, each group in on one line.
600 600
601 601 line_split = re.compile("""
602 602 ^(\s*) # any leading space
603 603 ([,;/%]|!!?|\?\??) # escape character or characters
604 604 \s*(%?[\w\.]*) # function/method, possibly with leading %
605 605 # to correctly treat things like '?%magic'
606 606 (\s+.*$|$) # rest of line
607 607 """, re.VERBOSE)
608 608
609 609
610 610 def split_user_input(line):
611 611 """Split user input into early whitespace, esc-char, function part and rest.
612 612
613 613 This is currently handles lines with '=' in them in a very inconsistent
614 614 manner.
615 615
616 616 Examples
617 617 ========
618 618 >>> split_user_input('x=1')
619 619 ('', '', 'x=1', '')
620 620 >>> split_user_input('?')
621 621 ('', '?', '', '')
622 622 >>> split_user_input('??')
623 623 ('', '??', '', '')
624 624 >>> split_user_input(' ?')
625 625 (' ', '?', '', '')
626 626 >>> split_user_input(' ??')
627 627 (' ', '??', '', '')
628 628 >>> split_user_input('??x')
629 629 ('', '??', 'x', '')
630 630 >>> split_user_input('?x=1')
631 631 ('', '', '?x=1', '')
632 632 >>> split_user_input('!ls')
633 633 ('', '!', 'ls', '')
634 634 >>> split_user_input(' !ls')
635 635 (' ', '!', 'ls', '')
636 636 >>> split_user_input('!!ls')
637 637 ('', '!!', 'ls', '')
638 638 >>> split_user_input(' !!ls')
639 639 (' ', '!!', 'ls', '')
640 640 >>> split_user_input(',ls')
641 641 ('', ',', 'ls', '')
642 642 >>> split_user_input(';ls')
643 643 ('', ';', 'ls', '')
644 644 >>> split_user_input(' ;ls')
645 645 (' ', ';', 'ls', '')
646 646 >>> split_user_input('f.g(x)')
647 647 ('', '', 'f.g(x)', '')
648 648 >>> split_user_input('f.g (x)')
649 649 ('', '', 'f.g', '(x)')
650 650 >>> split_user_input('?%hist')
651 651 ('', '?', '%hist', '')
652 652 """
653 653 match = line_split.match(line)
654 654 if match:
655 655 lspace, esc, fpart, rest = match.groups()
656 656 else:
657 657 # print "match failed for line '%s'" % line
658 658 try:
659 659 fpart, rest = line.split(None, 1)
660 660 except ValueError:
661 661 # print "split failed for line '%s'" % line
662 662 fpart, rest = line,''
663 663 lspace = re.match('^(\s*)(.*)', line).groups()[0]
664 664 esc = ''
665 665
666 666 # fpart has to be a valid python identifier, so it better be only pure
667 667 # ascii, no unicode:
668 668 try:
669 669 fpart = fpart.encode('ascii')
670 670 except UnicodeEncodeError:
671 671 lspace = unicode(lspace)
672 672 rest = fpart + u' ' + rest
673 673 fpart = u''
674 674
675 675 #print 'line:<%s>' % line # dbg
676 676 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
677 677 return lspace, esc, fpart.strip(), rest.lstrip()
678 678
679 679
680 680 # The escaped translators ALL receive a line where their own escape has been
681 681 # stripped. Only '?' is valid at the end of the line, all others can only be
682 682 # placed at the start.
683 683
684 684 class LineInfo(object):
685 685 """A single line of input and associated info.
686 686
687 687 This is a utility class that mostly wraps the output of
688 688 :func:`split_user_input` into a convenient object to be passed around
689 689 during input transformations.
690 690
691 691 Includes the following as properties:
692 692
693 693 line
694 694 The original, raw line
695 695
696 696 lspace
697 697 Any early whitespace before actual text starts.
698 698
699 699 esc
700 700 The initial esc character (or characters, for double-char escapes like
701 701 '??' or '!!').
702 702
703 703 fpart
704 704 The 'function part', which is basically the maximal initial sequence
705 705 of valid python identifiers and the '.' character. This is what is
706 706 checked for alias and magic transformations, used for auto-calling,
707 707 etc.
708 708
709 709 rest
710 710 Everything else on the line.
711 711 """
712 712 def __init__(self, line):
713 713 self.line = line
714 714 self.lspace, self.esc, self.fpart, self.rest = \
715 715 split_user_input(line)
716 716
717 717 def __str__(self):
718 718 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
719 719 self.fpart, self.rest)
720 720
721 721
722 722 # Transformations of the special syntaxes that don't rely on an explicit escape
723 723 # character but instead on patterns on the input line
724 724
725 725 # The core transformations are implemented as standalone functions that can be
726 726 # tested and validated in isolation. Each of these uses a regexp, we
727 727 # pre-compile these and keep them close to each function definition for clarity
728 728
729 729 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
730 730 r'\s*=\s*!\s*(?P<cmd>.*)')
731 731
732 732 def transform_assign_system(line):
733 733 """Handle the `files = !ls` syntax."""
734 # FIXME: This transforms the line to use %sc, but we've listed that magic
735 # as deprecated. We should then implement this functionality in a
736 # standalone api that we can transform to, without going through a
737 # deprecated magic.
738 734 m = _assign_system_re.match(line)
739 735 if m is not None:
740 736 cmd = m.group('cmd')
741 737 lhs = m.group('lhs')
742 expr = make_quoted_expr("sc -l = %s" % cmd)
743 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
738 expr = make_quoted_expr(cmd)
739 new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr)
744 740 return new_line
745 741 return line
746 742
747 743
748 744 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
749 745 r'\s*=\s*%\s*(?P<cmd>.*)')
750 746
751 747 def transform_assign_magic(line):
752 748 """Handle the `a = %who` syntax."""
753 749 m = _assign_magic_re.match(line)
754 750 if m is not None:
755 751 cmd = m.group('cmd')
756 752 lhs = m.group('lhs')
757 753 expr = make_quoted_expr(cmd)
758 754 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
759 755 return new_line
760 756 return line
761 757
762 758
763 759 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
764 760
765 761 def transform_classic_prompt(line):
766 762 """Handle inputs that start with '>>> ' syntax."""
767 763
768 764 if not line or line.isspace():
769 765 return line
770 766 m = _classic_prompt_re.match(line)
771 767 if m:
772 768 return line[len(m.group(0)):]
773 769 else:
774 770 return line
775 771
776 772
777 773 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
778 774
779 775 def transform_ipy_prompt(line):
780 776 """Handle inputs that start classic IPython prompt syntax."""
781 777
782 778 if not line or line.isspace():
783 779 return line
784 780 #print 'LINE: %r' % line # dbg
785 781 m = _ipy_prompt_re.match(line)
786 782 if m:
787 783 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
788 784 return line[len(m.group(0)):]
789 785 else:
790 786 return line
791 787
792 788
793 789 class EscapedTransformer(object):
794 790 """Class to transform lines that are explicitly escaped out."""
795 791
796 792 def __init__(self):
797 793 tr = { ESC_SHELL : self._tr_system,
798 794 ESC_SH_CAP : self._tr_system2,
799 795 ESC_HELP : self._tr_help,
800 796 ESC_HELP2 : self._tr_help,
801 797 ESC_MAGIC : self._tr_magic,
802 798 ESC_QUOTE : self._tr_quote,
803 799 ESC_QUOTE2 : self._tr_quote2,
804 800 ESC_PAREN : self._tr_paren }
805 801 self.tr = tr
806 802
807 803 # Support for syntax transformations that use explicit escapes typed by the
808 804 # user at the beginning of a line
809 805 @staticmethod
810 806 def _tr_system(line_info):
811 807 "Translate lines escaped with: !"
812 808 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
813 809 return '%sget_ipython().system(%s)' % (line_info.lspace,
814 810 make_quoted_expr(cmd))
815 811
816 812 @staticmethod
817 813 def _tr_system2(line_info):
818 814 "Translate lines escaped with: !!"
819 815 cmd = line_info.line.lstrip()[2:]
820 816 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
821 817 make_quoted_expr(cmd))
822 818
823 819 @staticmethod
824 820 def _tr_help(line_info):
825 821 "Translate lines escaped with: ?/??"
826 822 # A naked help line should just fire the intro help screen
827 823 if not line_info.line[1:]:
828 824 return 'get_ipython().show_usage()'
829 825
830 826 # There may be one or two '?' at the end, move them to the front so that
831 827 # the rest of the logic can assume escapes are at the start
832 828 line = line_info.line
833 829 if line.endswith('?'):
834 830 line = line[-1] + line[:-1]
835 831 if line.endswith('?'):
836 832 line = line[-1] + line[:-1]
837 833 line_info = LineInfo(line)
838 834
839 835 # From here on, simply choose which level of detail to get.
840 836 if line_info.esc == '?':
841 837 pinfo = 'pinfo'
842 838 elif line_info.esc == '??':
843 839 pinfo = 'pinfo2'
844 840
845 841 tpl = '%sget_ipython().magic("%s %s")'
846 842 return tpl % (line_info.lspace, pinfo,
847 843 ' '.join([line_info.fpart, line_info.rest]).strip())
848 844
849 845 @staticmethod
850 846 def _tr_magic(line_info):
851 847 "Translate lines escaped with: %"
852 848 tpl = '%sget_ipython().magic(%s)'
853 849 cmd = make_quoted_expr(' '.join([line_info.fpart,
854 850 line_info.rest]).strip())
855 851 return tpl % (line_info.lspace, cmd)
856 852
857 853 @staticmethod
858 854 def _tr_quote(line_info):
859 855 "Translate lines escaped with: ,"
860 856 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
861 857 '", "'.join(line_info.rest.split()) )
862 858
863 859 @staticmethod
864 860 def _tr_quote2(line_info):
865 861 "Translate lines escaped with: ;"
866 862 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
867 863 line_info.rest)
868 864
869 865 @staticmethod
870 866 def _tr_paren(line_info):
871 867 "Translate lines escaped with: /"
872 868 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
873 869 ", ".join(line_info.rest.split()))
874 870
875 871 def __call__(self, line):
876 872 """Class to transform lines that are explicitly escaped out.
877 873
878 874 This calls the above _tr_* static methods for the actual line
879 875 translations."""
880 876
881 877 # Empty lines just get returned unmodified
882 878 if not line or line.isspace():
883 879 return line
884 880
885 881 # Get line endpoints, where the escapes can be
886 882 line_info = LineInfo(line)
887 883
888 884 # If the escape is not at the start, only '?' needs to be special-cased.
889 885 # All other escapes are only valid at the start
890 886 if not line_info.esc in self.tr:
891 887 if line.endswith(ESC_HELP):
892 888 return self._tr_help(line_info)
893 889 else:
894 890 # If we don't recognize the escape, don't modify the line
895 891 return line
896 892
897 893 return self.tr[line_info.esc](line_info)
898 894
899 895
900 896 # A function-looking object to be used by the rest of the code. The purpose of
901 897 # the class in this case is to organize related functionality, more than to
902 898 # manage state.
903 899 transform_escaped = EscapedTransformer()
904 900
905 901
906 902 class IPythonInputSplitter(InputSplitter):
907 903 """An input splitter that recognizes all of IPython's special syntax."""
908 904
909 905 def push(self, lines):
910 906 """Push one or more lines of IPython input.
911 907 """
912 908 if not lines:
913 909 return super(IPythonInputSplitter, self).push(lines)
914 910
915 911 lines_list = lines.splitlines()
916 912
917 913 transforms = [transform_escaped, transform_assign_system,
918 914 transform_assign_magic, transform_ipy_prompt,
919 915 transform_classic_prompt]
920 916
921 917 # Transform logic
922 918 #
923 919 # We only apply the line transformers to the input if we have either no
924 920 # input yet, or complete input, or if the last line of the buffer ends
925 921 # with ':' (opening an indented block). This prevents the accidental
926 922 # transformation of escapes inside multiline expressions like
927 923 # triple-quoted strings or parenthesized expressions.
928 924 #
929 925 # The last heuristic, while ugly, ensures that the first line of an
930 926 # indented block is correctly transformed.
931 927 #
932 928 # FIXME: try to find a cleaner approach for this last bit.
933 929
934 930 # If we were in 'block' mode, since we're going to pump the parent
935 931 # class by hand line by line, we need to temporarily switch out to
936 932 # 'line' mode, do a single manual reset and then feed the lines one
937 933 # by one. Note that this only matters if the input has more than one
938 934 # line.
939 935 changed_input_mode = False
940 936
941 937 if len(lines_list)>1 and self.input_mode == 'block':
942 938 self.reset()
943 939 changed_input_mode = True
944 940 saved_input_mode = 'block'
945 941 self.input_mode = 'line'
946 942
947 943 try:
948 944 push = super(IPythonInputSplitter, self).push
949 945 for line in lines_list:
950 946 if self._is_complete or not self._buffer or \
951 947 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
952 948 for f in transforms:
953 949 line = f(line)
954 950
955 951 out = push(line)
956 952 finally:
957 953 if changed_input_mode:
958 954 self.input_mode = saved_input_mode
959 955
960 956 return out
@@ -1,2497 +1,2523 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-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import atexit
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.display_trap import DisplayTrap
44 44 from IPython.core.displayhook import DisplayHook
45 45 from IPython.core.error import TryNext, UsageError
46 46 from IPython.core.extensions import ExtensionManager
47 47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 48 from IPython.core.inputlist import InputList
49 49 from IPython.core.inputsplitter import IPythonInputSplitter
50 50 from IPython.core.logger import Logger
51 51 from IPython.core.magic import Magic
52 52 from IPython.core.payload import PayloadManager
53 53 from IPython.core.plugin import PluginManager
54 54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 55 from IPython.external.Itpl import ItplNS
56 56 from IPython.utils import PyColorize
57 57 from IPython.utils import io
58 58 from IPython.utils import pickleshare
59 59 from IPython.utils.doctestreload import doctest_reload
60 60 from IPython.utils.io import ask_yes_no, rprint
61 61 from IPython.utils.ipstruct import Struct
62 62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 63 from IPython.utils.process import system, getoutput
64 64 from IPython.utils.strdispatch import StrDispatch
65 65 from IPython.utils.syspathcontext import prepended_to_syspath
66 from IPython.utils.text import num_ini_spaces, format_screen
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
67 67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 68 List, Unicode, Instance, Type)
69 69 from IPython.utils.warn import warn, error, fatal
70 70 import IPython.core.hooks
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Globals
74 74 #-----------------------------------------------------------------------------
75 75
76 76 # compiled regexps for autoindent management
77 77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78 78
79 79 #-----------------------------------------------------------------------------
80 80 # Utilities
81 81 #-----------------------------------------------------------------------------
82 82
83 83 # store the builtin raw_input globally, and use this always, in case user code
84 84 # overwrites it (like wx.py.PyShell does)
85 85 raw_input_original = raw_input
86 86
87 87 def softspace(file, newvalue):
88 88 """Copied from code.py, to remove the dependency"""
89 89
90 90 oldvalue = 0
91 91 try:
92 92 oldvalue = file.softspace
93 93 except AttributeError:
94 94 pass
95 95 try:
96 96 file.softspace = newvalue
97 97 except (AttributeError, TypeError):
98 98 # "attribute-less object" or "read-only attributes"
99 99 pass
100 100 return oldvalue
101 101
102 102
103 103 def no_op(*a, **kw): pass
104 104
105 105 class SpaceInInput(exceptions.Exception): pass
106 106
107 107 class Bunch: pass
108 108
109 109
110 110 def get_default_colors():
111 111 if sys.platform=='darwin':
112 112 return "LightBG"
113 113 elif os.name=='nt':
114 114 return 'Linux'
115 115 else:
116 116 return 'Linux'
117 117
118 118
119 119 class SeparateStr(Str):
120 120 """A Str subclass to validate separate_in, separate_out, etc.
121 121
122 122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 123 """
124 124
125 125 def validate(self, obj, value):
126 126 if value == '0': value = ''
127 127 value = value.replace('\\n','\n')
128 128 return super(SeparateStr, self).validate(obj, value)
129 129
130 130 class MultipleInstanceError(Exception):
131 131 pass
132 132
133 133
134 134 #-----------------------------------------------------------------------------
135 135 # Main IPython class
136 136 #-----------------------------------------------------------------------------
137 137
138 138
139 139 class InteractiveShell(Configurable, Magic):
140 140 """An enhanced, interactive shell for Python."""
141 141
142 142 _instance = None
143 143 autocall = Enum((0,1,2), default_value=1, config=True)
144 144 # TODO: remove all autoindent logic and put into frontends.
145 145 # We can't do this yet because even runlines uses the autoindent.
146 146 autoindent = CBool(True, config=True)
147 147 automagic = CBool(True, config=True)
148 148 cache_size = Int(1000, config=True)
149 149 color_info = CBool(True, config=True)
150 150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 151 default_value=get_default_colors(), config=True)
152 152 debug = CBool(False, config=True)
153 153 deep_reload = CBool(False, config=True)
154 154 displayhook_class = Type(DisplayHook)
155 155 exit_now = CBool(False)
156 156 filename = Str("<ipython console>")
157 157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 158 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter')
159 159 logstart = CBool(False, config=True)
160 160 logfile = Str('', config=True)
161 161 logappend = Str('', config=True)
162 162 object_info_string_level = Enum((0,1,2), default_value=0,
163 163 config=True)
164 164 pdb = CBool(False, config=True)
165 165
166 166 pprint = CBool(True, config=True)
167 167 profile = Str('', config=True)
168 168 prompt_in1 = Str('In [\\#]: ', config=True)
169 169 prompt_in2 = Str(' .\\D.: ', config=True)
170 170 prompt_out = Str('Out[\\#]: ', config=True)
171 171 prompts_pad_left = CBool(True, config=True)
172 172 quiet = CBool(False, config=True)
173 173
174 174 # The readline stuff will eventually be moved to the terminal subclass
175 175 # but for now, we can't do that as readline is welded in everywhere.
176 176 readline_use = CBool(True, config=True)
177 177 readline_merge_completions = CBool(True, config=True)
178 178 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
179 179 readline_remove_delims = Str('-/~', config=True)
180 180 readline_parse_and_bind = List([
181 181 'tab: complete',
182 182 '"\C-l": clear-screen',
183 183 'set show-all-if-ambiguous on',
184 184 '"\C-o": tab-insert',
185 185 '"\M-i": " "',
186 186 '"\M-o": "\d\d\d\d"',
187 187 '"\M-I": "\d\d\d\d"',
188 188 '"\C-r": reverse-search-history',
189 189 '"\C-s": forward-search-history',
190 190 '"\C-p": history-search-backward',
191 191 '"\C-n": history-search-forward',
192 192 '"\e[A": history-search-backward',
193 193 '"\e[B": history-search-forward',
194 194 '"\C-k": kill-line',
195 195 '"\C-u": unix-line-discard',
196 196 ], allow_none=False, config=True)
197 197
198 198 # TODO: this part of prompt management should be moved to the frontends.
199 199 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
200 200 separate_in = SeparateStr('\n', config=True)
201 201 separate_out = SeparateStr('', config=True)
202 202 separate_out2 = SeparateStr('', config=True)
203 203 wildcards_case_sensitive = CBool(True, config=True)
204 204 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
205 205 default_value='Context', config=True)
206 206
207 207 # Subcomponents of InteractiveShell
208 208 alias_manager = Instance('IPython.core.alias.AliasManager')
209 209 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
210 210 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
211 211 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
212 212 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
213 213 plugin_manager = Instance('IPython.core.plugin.PluginManager')
214 214 payload_manager = Instance('IPython.core.payload.PayloadManager')
215 215
216 216 # Private interface
217 217 _post_execute = set()
218 218
219 219 def __init__(self, config=None, ipython_dir=None,
220 220 user_ns=None, user_global_ns=None,
221 221 custom_exceptions=((), None)):
222 222
223 223 # This is where traits with a config_key argument are updated
224 224 # from the values on config.
225 225 super(InteractiveShell, self).__init__(config=config)
226 226
227 227 # These are relatively independent and stateless
228 228 self.init_ipython_dir(ipython_dir)
229 229 self.init_instance_attrs()
230 230
231 231 # Create namespaces (user_ns, user_global_ns, etc.)
232 232 self.init_create_namespaces(user_ns, user_global_ns)
233 233 # This has to be done after init_create_namespaces because it uses
234 234 # something in self.user_ns, but before init_sys_modules, which
235 235 # is the first thing to modify sys.
236 236 # TODO: When we override sys.stdout and sys.stderr before this class
237 237 # is created, we are saving the overridden ones here. Not sure if this
238 238 # is what we want to do.
239 239 self.save_sys_module_state()
240 240 self.init_sys_modules()
241 241
242 242 self.init_history()
243 243 self.init_encoding()
244 244 self.init_prefilter()
245 245
246 246 Magic.__init__(self, self)
247 247
248 248 self.init_syntax_highlighting()
249 249 self.init_hooks()
250 250 self.init_pushd_popd_magic()
251 251 # self.init_traceback_handlers use to be here, but we moved it below
252 252 # because it and init_io have to come after init_readline.
253 253 self.init_user_ns()
254 254 self.init_logger()
255 255 self.init_alias()
256 256 self.init_builtins()
257 257
258 258 # pre_config_initialization
259 259 self.init_shadow_hist()
260 260
261 261 # The next section should contain everything that was in ipmaker.
262 262 self.init_logstart()
263 263
264 264 # The following was in post_config_initialization
265 265 self.init_inspector()
266 266 # init_readline() must come before init_io(), because init_io uses
267 267 # readline related things.
268 268 self.init_readline()
269 269 # init_completer must come after init_readline, because it needs to
270 270 # know whether readline is present or not system-wide to configure the
271 271 # completers, since the completion machinery can now operate
272 272 # independently of readline (e.g. over the network)
273 273 self.init_completer()
274 274 # TODO: init_io() needs to happen before init_traceback handlers
275 275 # because the traceback handlers hardcode the stdout/stderr streams.
276 276 # This logic in in debugger.Pdb and should eventually be changed.
277 277 self.init_io()
278 278 self.init_traceback_handlers(custom_exceptions)
279 279 self.init_prompts()
280 280 self.init_displayhook()
281 281 self.init_reload_doctest()
282 282 self.init_magics()
283 283 self.init_pdb()
284 284 self.init_extension_manager()
285 285 self.init_plugin_manager()
286 286 self.init_payload()
287 287 self.hooks.late_startup_hook()
288 288 atexit.register(self.atexit_operations)
289 289
290 290 @classmethod
291 291 def instance(cls, *args, **kwargs):
292 292 """Returns a global InteractiveShell instance."""
293 293 if cls._instance is None:
294 294 inst = cls(*args, **kwargs)
295 295 # Now make sure that the instance will also be returned by
296 296 # the subclasses instance attribute.
297 297 for subclass in cls.mro():
298 298 if issubclass(cls, subclass) and \
299 299 issubclass(subclass, InteractiveShell):
300 300 subclass._instance = inst
301 301 else:
302 302 break
303 303 if isinstance(cls._instance, cls):
304 304 return cls._instance
305 305 else:
306 306 raise MultipleInstanceError(
307 307 'Multiple incompatible subclass instances of '
308 308 'InteractiveShell are being created.'
309 309 )
310 310
311 311 @classmethod
312 312 def initialized(cls):
313 313 return hasattr(cls, "_instance")
314 314
315 315 def get_ipython(self):
316 316 """Return the currently running IPython instance."""
317 317 return self
318 318
319 319 #-------------------------------------------------------------------------
320 320 # Trait changed handlers
321 321 #-------------------------------------------------------------------------
322 322
323 323 def _ipython_dir_changed(self, name, new):
324 324 if not os.path.isdir(new):
325 325 os.makedirs(new, mode = 0777)
326 326
327 327 def set_autoindent(self,value=None):
328 328 """Set the autoindent flag, checking for readline support.
329 329
330 330 If called with no arguments, it acts as a toggle."""
331 331
332 332 if not self.has_readline:
333 333 if os.name == 'posix':
334 334 warn("The auto-indent feature requires the readline library")
335 335 self.autoindent = 0
336 336 return
337 337 if value is None:
338 338 self.autoindent = not self.autoindent
339 339 else:
340 340 self.autoindent = value
341 341
342 342 #-------------------------------------------------------------------------
343 343 # init_* methods called by __init__
344 344 #-------------------------------------------------------------------------
345 345
346 346 def init_ipython_dir(self, ipython_dir):
347 347 if ipython_dir is not None:
348 348 self.ipython_dir = ipython_dir
349 349 self.config.Global.ipython_dir = self.ipython_dir
350 350 return
351 351
352 352 if hasattr(self.config.Global, 'ipython_dir'):
353 353 self.ipython_dir = self.config.Global.ipython_dir
354 354 else:
355 355 self.ipython_dir = get_ipython_dir()
356 356
357 357 # All children can just read this
358 358 self.config.Global.ipython_dir = self.ipython_dir
359 359
360 360 def init_instance_attrs(self):
361 361 self.more = False
362 362
363 363 # command compiler
364 364 self.compile = codeop.CommandCompiler()
365 365
366 366 # User input buffer
367 367 self.buffer = []
368 368
369 369 # Make an empty namespace, which extension writers can rely on both
370 370 # existing and NEVER being used by ipython itself. This gives them a
371 371 # convenient location for storing additional information and state
372 372 # their extensions may require, without fear of collisions with other
373 373 # ipython names that may develop later.
374 374 self.meta = Struct()
375 375
376 376 # Object variable to store code object waiting execution. This is
377 377 # used mainly by the multithreaded shells, but it can come in handy in
378 378 # other situations. No need to use a Queue here, since it's a single
379 379 # item which gets cleared once run.
380 380 self.code_to_run = None
381 381
382 382 # Temporary files used for various purposes. Deleted at exit.
383 383 self.tempfiles = []
384 384
385 385 # Keep track of readline usage (later set by init_readline)
386 386 self.has_readline = False
387 387
388 388 # keep track of where we started running (mainly for crash post-mortem)
389 389 # This is not being used anywhere currently.
390 390 self.starting_dir = os.getcwd()
391 391
392 392 # Indentation management
393 393 self.indent_current_nsp = 0
394 394
395 395 # Input splitter, to split entire cells of input into either individual
396 396 # interactive statements or whole blocks.
397 397 self.input_splitter = IPythonInputSplitter()
398 398
399 399 def init_encoding(self):
400 400 # Get system encoding at startup time. Certain terminals (like Emacs
401 401 # under Win32 have it set to None, and we need to have a known valid
402 402 # encoding to use in the raw_input() method
403 403 try:
404 404 self.stdin_encoding = sys.stdin.encoding or 'ascii'
405 405 except AttributeError:
406 406 self.stdin_encoding = 'ascii'
407 407
408 408 def init_syntax_highlighting(self):
409 409 # Python source parser/formatter for syntax highlighting
410 410 pyformat = PyColorize.Parser().format
411 411 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
412 412
413 413 def init_pushd_popd_magic(self):
414 414 # for pushd/popd management
415 415 try:
416 416 self.home_dir = get_home_dir()
417 417 except HomeDirError, msg:
418 418 fatal(msg)
419 419
420 420 self.dir_stack = []
421 421
422 422 def init_logger(self):
423 423 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
424 424 # local shortcut, this is used a LOT
425 425 self.log = self.logger.log
426 426
427 427 def init_logstart(self):
428 428 if self.logappend:
429 429 self.magic_logstart(self.logappend + ' append')
430 430 elif self.logfile:
431 431 self.magic_logstart(self.logfile)
432 432 elif self.logstart:
433 433 self.magic_logstart()
434 434
435 435 def init_builtins(self):
436 436 self.builtin_trap = BuiltinTrap(shell=self)
437 437
438 438 def init_inspector(self):
439 439 # Object inspector
440 440 self.inspector = oinspect.Inspector(oinspect.InspectColors,
441 441 PyColorize.ANSICodeColors,
442 442 'NoColor',
443 443 self.object_info_string_level)
444 444
445 445 def init_io(self):
446 446 # This will just use sys.stdout and sys.stderr. If you want to
447 447 # override sys.stdout and sys.stderr themselves, you need to do that
448 448 # *before* instantiating this class, because Term holds onto
449 449 # references to the underlying streams.
450 450 if sys.platform == 'win32' and self.has_readline:
451 451 Term = io.IOTerm(cout=self.readline._outputfile,
452 452 cerr=self.readline._outputfile)
453 453 else:
454 454 Term = io.IOTerm()
455 455 io.Term = Term
456 456
457 457 def init_prompts(self):
458 458 # TODO: This is a pass for now because the prompts are managed inside
459 459 # the DisplayHook. Once there is a separate prompt manager, this
460 460 # will initialize that object and all prompt related information.
461 461 pass
462 462
463 463 def init_displayhook(self):
464 464 # Initialize displayhook, set in/out prompts and printing system
465 465 self.displayhook = self.displayhook_class(
466 466 shell=self,
467 467 cache_size=self.cache_size,
468 468 input_sep = self.separate_in,
469 469 output_sep = self.separate_out,
470 470 output_sep2 = self.separate_out2,
471 471 ps1 = self.prompt_in1,
472 472 ps2 = self.prompt_in2,
473 473 ps_out = self.prompt_out,
474 474 pad_left = self.prompts_pad_left
475 475 )
476 476 # This is a context manager that installs/revmoes the displayhook at
477 477 # the appropriate time.
478 478 self.display_trap = DisplayTrap(hook=self.displayhook)
479 479
480 480 def init_reload_doctest(self):
481 481 # Do a proper resetting of doctest, including the necessary displayhook
482 482 # monkeypatching
483 483 try:
484 484 doctest_reload()
485 485 except ImportError:
486 486 warn("doctest module does not exist.")
487 487
488 488 #-------------------------------------------------------------------------
489 489 # Things related to injections into the sys module
490 490 #-------------------------------------------------------------------------
491 491
492 492 def save_sys_module_state(self):
493 493 """Save the state of hooks in the sys module.
494 494
495 495 This has to be called after self.user_ns is created.
496 496 """
497 497 self._orig_sys_module_state = {}
498 498 self._orig_sys_module_state['stdin'] = sys.stdin
499 499 self._orig_sys_module_state['stdout'] = sys.stdout
500 500 self._orig_sys_module_state['stderr'] = sys.stderr
501 501 self._orig_sys_module_state['excepthook'] = sys.excepthook
502 502 try:
503 503 self._orig_sys_modules_main_name = self.user_ns['__name__']
504 504 except KeyError:
505 505 pass
506 506
507 507 def restore_sys_module_state(self):
508 508 """Restore the state of the sys module."""
509 509 try:
510 510 for k, v in self._orig_sys_module_state.items():
511 511 setattr(sys, k, v)
512 512 except AttributeError:
513 513 pass
514 514 # Reset what what done in self.init_sys_modules
515 515 try:
516 516 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
517 517 except (AttributeError, KeyError):
518 518 pass
519 519
520 520 #-------------------------------------------------------------------------
521 521 # Things related to hooks
522 522 #-------------------------------------------------------------------------
523 523
524 524 def init_hooks(self):
525 525 # hooks holds pointers used for user-side customizations
526 526 self.hooks = Struct()
527 527
528 528 self.strdispatchers = {}
529 529
530 530 # Set all default hooks, defined in the IPython.hooks module.
531 531 hooks = IPython.core.hooks
532 532 for hook_name in hooks.__all__:
533 533 # default hooks have priority 100, i.e. low; user hooks should have
534 534 # 0-100 priority
535 535 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
536 536
537 537 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
538 538 """set_hook(name,hook) -> sets an internal IPython hook.
539 539
540 540 IPython exposes some of its internal API as user-modifiable hooks. By
541 541 adding your function to one of these hooks, you can modify IPython's
542 542 behavior to call at runtime your own routines."""
543 543
544 544 # At some point in the future, this should validate the hook before it
545 545 # accepts it. Probably at least check that the hook takes the number
546 546 # of args it's supposed to.
547 547
548 548 f = new.instancemethod(hook,self,self.__class__)
549 549
550 550 # check if the hook is for strdispatcher first
551 551 if str_key is not None:
552 552 sdp = self.strdispatchers.get(name, StrDispatch())
553 553 sdp.add_s(str_key, f, priority )
554 554 self.strdispatchers[name] = sdp
555 555 return
556 556 if re_key is not None:
557 557 sdp = self.strdispatchers.get(name, StrDispatch())
558 558 sdp.add_re(re.compile(re_key), f, priority )
559 559 self.strdispatchers[name] = sdp
560 560 return
561 561
562 562 dp = getattr(self.hooks, name, None)
563 563 if name not in IPython.core.hooks.__all__:
564 564 print "Warning! Hook '%s' is not one of %s" % \
565 565 (name, IPython.core.hooks.__all__ )
566 566 if not dp:
567 567 dp = IPython.core.hooks.CommandChainDispatcher()
568 568
569 569 try:
570 570 dp.add(f,priority)
571 571 except AttributeError:
572 572 # it was not commandchain, plain old func - replace
573 573 dp = f
574 574
575 575 setattr(self.hooks,name, dp)
576 576
577 577 def register_post_execute(self, func):
578 578 """Register a function for calling after code execution.
579 579 """
580 580 if not callable(func):
581 581 raise ValueError('argument %s must be callable' % func)
582 582 self._post_execute.add(func)
583 583
584 584 #-------------------------------------------------------------------------
585 585 # Things related to the "main" module
586 586 #-------------------------------------------------------------------------
587 587
588 588 def new_main_mod(self,ns=None):
589 589 """Return a new 'main' module object for user code execution.
590 590 """
591 591 main_mod = self._user_main_module
592 592 init_fakemod_dict(main_mod,ns)
593 593 return main_mod
594 594
595 595 def cache_main_mod(self,ns,fname):
596 596 """Cache a main module's namespace.
597 597
598 598 When scripts are executed via %run, we must keep a reference to the
599 599 namespace of their __main__ module (a FakeModule instance) around so
600 600 that Python doesn't clear it, rendering objects defined therein
601 601 useless.
602 602
603 603 This method keeps said reference in a private dict, keyed by the
604 604 absolute path of the module object (which corresponds to the script
605 605 path). This way, for multiple executions of the same script we only
606 606 keep one copy of the namespace (the last one), thus preventing memory
607 607 leaks from old references while allowing the objects from the last
608 608 execution to be accessible.
609 609
610 610 Note: we can not allow the actual FakeModule instances to be deleted,
611 611 because of how Python tears down modules (it hard-sets all their
612 612 references to None without regard for reference counts). This method
613 613 must therefore make a *copy* of the given namespace, to allow the
614 614 original module's __dict__ to be cleared and reused.
615 615
616 616
617 617 Parameters
618 618 ----------
619 619 ns : a namespace (a dict, typically)
620 620
621 621 fname : str
622 622 Filename associated with the namespace.
623 623
624 624 Examples
625 625 --------
626 626
627 627 In [10]: import IPython
628 628
629 629 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
630 630
631 631 In [12]: IPython.__file__ in _ip._main_ns_cache
632 632 Out[12]: True
633 633 """
634 634 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
635 635
636 636 def clear_main_mod_cache(self):
637 637 """Clear the cache of main modules.
638 638
639 639 Mainly for use by utilities like %reset.
640 640
641 641 Examples
642 642 --------
643 643
644 644 In [15]: import IPython
645 645
646 646 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
647 647
648 648 In [17]: len(_ip._main_ns_cache) > 0
649 649 Out[17]: True
650 650
651 651 In [18]: _ip.clear_main_mod_cache()
652 652
653 653 In [19]: len(_ip._main_ns_cache) == 0
654 654 Out[19]: True
655 655 """
656 656 self._main_ns_cache.clear()
657 657
658 658 #-------------------------------------------------------------------------
659 659 # Things related to debugging
660 660 #-------------------------------------------------------------------------
661 661
662 662 def init_pdb(self):
663 663 # Set calling of pdb on exceptions
664 664 # self.call_pdb is a property
665 665 self.call_pdb = self.pdb
666 666
667 667 def _get_call_pdb(self):
668 668 return self._call_pdb
669 669
670 670 def _set_call_pdb(self,val):
671 671
672 672 if val not in (0,1,False,True):
673 673 raise ValueError,'new call_pdb value must be boolean'
674 674
675 675 # store value in instance
676 676 self._call_pdb = val
677 677
678 678 # notify the actual exception handlers
679 679 self.InteractiveTB.call_pdb = val
680 680
681 681 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
682 682 'Control auto-activation of pdb at exceptions')
683 683
684 684 def debugger(self,force=False):
685 685 """Call the pydb/pdb debugger.
686 686
687 687 Keywords:
688 688
689 689 - force(False): by default, this routine checks the instance call_pdb
690 690 flag and does not actually invoke the debugger if the flag is false.
691 691 The 'force' option forces the debugger to activate even if the flag
692 692 is false.
693 693 """
694 694
695 695 if not (force or self.call_pdb):
696 696 return
697 697
698 698 if not hasattr(sys,'last_traceback'):
699 699 error('No traceback has been produced, nothing to debug.')
700 700 return
701 701
702 702 # use pydb if available
703 703 if debugger.has_pydb:
704 704 from pydb import pm
705 705 else:
706 706 # fallback to our internal debugger
707 707 pm = lambda : self.InteractiveTB.debugger(force=True)
708 708 self.history_saving_wrapper(pm)()
709 709
710 710 #-------------------------------------------------------------------------
711 711 # Things related to IPython's various namespaces
712 712 #-------------------------------------------------------------------------
713 713
714 714 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
715 715 # Create the namespace where the user will operate. user_ns is
716 716 # normally the only one used, and it is passed to the exec calls as
717 717 # the locals argument. But we do carry a user_global_ns namespace
718 718 # given as the exec 'globals' argument, This is useful in embedding
719 719 # situations where the ipython shell opens in a context where the
720 720 # distinction between locals and globals is meaningful. For
721 721 # non-embedded contexts, it is just the same object as the user_ns dict.
722 722
723 723 # FIXME. For some strange reason, __builtins__ is showing up at user
724 724 # level as a dict instead of a module. This is a manual fix, but I
725 725 # should really track down where the problem is coming from. Alex
726 726 # Schmolck reported this problem first.
727 727
728 728 # A useful post by Alex Martelli on this topic:
729 729 # Re: inconsistent value from __builtins__
730 730 # Von: Alex Martelli <aleaxit@yahoo.com>
731 731 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
732 732 # Gruppen: comp.lang.python
733 733
734 734 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
735 735 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
736 736 # > <type 'dict'>
737 737 # > >>> print type(__builtins__)
738 738 # > <type 'module'>
739 739 # > Is this difference in return value intentional?
740 740
741 741 # Well, it's documented that '__builtins__' can be either a dictionary
742 742 # or a module, and it's been that way for a long time. Whether it's
743 743 # intentional (or sensible), I don't know. In any case, the idea is
744 744 # that if you need to access the built-in namespace directly, you
745 745 # should start with "import __builtin__" (note, no 's') which will
746 746 # definitely give you a module. Yeah, it's somewhat confusing:-(.
747 747
748 748 # These routines return properly built dicts as needed by the rest of
749 749 # the code, and can also be used by extension writers to generate
750 750 # properly initialized namespaces.
751 751 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
752 752 user_global_ns)
753 753
754 754 # Assign namespaces
755 755 # This is the namespace where all normal user variables live
756 756 self.user_ns = user_ns
757 757 self.user_global_ns = user_global_ns
758 758
759 759 # An auxiliary namespace that checks what parts of the user_ns were
760 760 # loaded at startup, so we can list later only variables defined in
761 761 # actual interactive use. Since it is always a subset of user_ns, it
762 762 # doesn't need to be separately tracked in the ns_table.
763 763 self.user_ns_hidden = {}
764 764
765 765 # A namespace to keep track of internal data structures to prevent
766 766 # them from cluttering user-visible stuff. Will be updated later
767 767 self.internal_ns = {}
768 768
769 769 # Now that FakeModule produces a real module, we've run into a nasty
770 770 # problem: after script execution (via %run), the module where the user
771 771 # code ran is deleted. Now that this object is a true module (needed
772 772 # so docetst and other tools work correctly), the Python module
773 773 # teardown mechanism runs over it, and sets to None every variable
774 774 # present in that module. Top-level references to objects from the
775 775 # script survive, because the user_ns is updated with them. However,
776 776 # calling functions defined in the script that use other things from
777 777 # the script will fail, because the function's closure had references
778 778 # to the original objects, which are now all None. So we must protect
779 779 # these modules from deletion by keeping a cache.
780 780 #
781 781 # To avoid keeping stale modules around (we only need the one from the
782 782 # last run), we use a dict keyed with the full path to the script, so
783 783 # only the last version of the module is held in the cache. Note,
784 784 # however, that we must cache the module *namespace contents* (their
785 785 # __dict__). Because if we try to cache the actual modules, old ones
786 786 # (uncached) could be destroyed while still holding references (such as
787 787 # those held by GUI objects that tend to be long-lived)>
788 788 #
789 789 # The %reset command will flush this cache. See the cache_main_mod()
790 790 # and clear_main_mod_cache() methods for details on use.
791 791
792 792 # This is the cache used for 'main' namespaces
793 793 self._main_ns_cache = {}
794 794 # And this is the single instance of FakeModule whose __dict__ we keep
795 795 # copying and clearing for reuse on each %run
796 796 self._user_main_module = FakeModule()
797 797
798 798 # A table holding all the namespaces IPython deals with, so that
799 799 # introspection facilities can search easily.
800 800 self.ns_table = {'user':user_ns,
801 801 'user_global':user_global_ns,
802 802 'internal':self.internal_ns,
803 803 'builtin':__builtin__.__dict__
804 804 }
805 805
806 806 # Similarly, track all namespaces where references can be held and that
807 807 # we can safely clear (so it can NOT include builtin). This one can be
808 808 # a simple list.
809 809 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
810 810 self.internal_ns, self._main_ns_cache ]
811 811
812 812 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
813 813 """Return a valid local and global user interactive namespaces.
814 814
815 815 This builds a dict with the minimal information needed to operate as a
816 816 valid IPython user namespace, which you can pass to the various
817 817 embedding classes in ipython. The default implementation returns the
818 818 same dict for both the locals and the globals to allow functions to
819 819 refer to variables in the namespace. Customized implementations can
820 820 return different dicts. The locals dictionary can actually be anything
821 821 following the basic mapping protocol of a dict, but the globals dict
822 822 must be a true dict, not even a subclass. It is recommended that any
823 823 custom object for the locals namespace synchronize with the globals
824 824 dict somehow.
825 825
826 826 Raises TypeError if the provided globals namespace is not a true dict.
827 827
828 828 Parameters
829 829 ----------
830 830 user_ns : dict-like, optional
831 831 The current user namespace. The items in this namespace should
832 832 be included in the output. If None, an appropriate blank
833 833 namespace should be created.
834 834 user_global_ns : dict, optional
835 835 The current user global namespace. The items in this namespace
836 836 should be included in the output. If None, an appropriate
837 837 blank namespace should be created.
838 838
839 839 Returns
840 840 -------
841 841 A pair of dictionary-like object to be used as the local namespace
842 842 of the interpreter and a dict to be used as the global namespace.
843 843 """
844 844
845 845
846 846 # We must ensure that __builtin__ (without the final 's') is always
847 847 # available and pointing to the __builtin__ *module*. For more details:
848 848 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
849 849
850 850 if user_ns is None:
851 851 # Set __name__ to __main__ to better match the behavior of the
852 852 # normal interpreter.
853 853 user_ns = {'__name__' :'__main__',
854 854 '__builtin__' : __builtin__,
855 855 '__builtins__' : __builtin__,
856 856 }
857 857 else:
858 858 user_ns.setdefault('__name__','__main__')
859 859 user_ns.setdefault('__builtin__',__builtin__)
860 860 user_ns.setdefault('__builtins__',__builtin__)
861 861
862 862 if user_global_ns is None:
863 863 user_global_ns = user_ns
864 864 if type(user_global_ns) is not dict:
865 865 raise TypeError("user_global_ns must be a true dict; got %r"
866 866 % type(user_global_ns))
867 867
868 868 return user_ns, user_global_ns
869 869
870 870 def init_sys_modules(self):
871 871 # We need to insert into sys.modules something that looks like a
872 872 # module but which accesses the IPython namespace, for shelve and
873 873 # pickle to work interactively. Normally they rely on getting
874 874 # everything out of __main__, but for embedding purposes each IPython
875 875 # instance has its own private namespace, so we can't go shoving
876 876 # everything into __main__.
877 877
878 878 # note, however, that we should only do this for non-embedded
879 879 # ipythons, which really mimic the __main__.__dict__ with their own
880 880 # namespace. Embedded instances, on the other hand, should not do
881 881 # this because they need to manage the user local/global namespaces
882 882 # only, but they live within a 'normal' __main__ (meaning, they
883 883 # shouldn't overtake the execution environment of the script they're
884 884 # embedded in).
885 885
886 886 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
887 887
888 888 try:
889 889 main_name = self.user_ns['__name__']
890 890 except KeyError:
891 891 raise KeyError('user_ns dictionary MUST have a "__name__" key')
892 892 else:
893 893 sys.modules[main_name] = FakeModule(self.user_ns)
894 894
895 895 def init_user_ns(self):
896 896 """Initialize all user-visible namespaces to their minimum defaults.
897 897
898 898 Certain history lists are also initialized here, as they effectively
899 899 act as user namespaces.
900 900
901 901 Notes
902 902 -----
903 903 All data structures here are only filled in, they are NOT reset by this
904 904 method. If they were not empty before, data will simply be added to
905 905 therm.
906 906 """
907 907 # This function works in two parts: first we put a few things in
908 908 # user_ns, and we sync that contents into user_ns_hidden so that these
909 909 # initial variables aren't shown by %who. After the sync, we add the
910 910 # rest of what we *do* want the user to see with %who even on a new
911 911 # session (probably nothing, so theye really only see their own stuff)
912 912
913 913 # The user dict must *always* have a __builtin__ reference to the
914 914 # Python standard __builtin__ namespace, which must be imported.
915 915 # This is so that certain operations in prompt evaluation can be
916 916 # reliably executed with builtins. Note that we can NOT use
917 917 # __builtins__ (note the 's'), because that can either be a dict or a
918 918 # module, and can even mutate at runtime, depending on the context
919 919 # (Python makes no guarantees on it). In contrast, __builtin__ is
920 920 # always a module object, though it must be explicitly imported.
921 921
922 922 # For more details:
923 923 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
924 924 ns = dict(__builtin__ = __builtin__)
925 925
926 926 # Put 'help' in the user namespace
927 927 try:
928 928 from site import _Helper
929 929 ns['help'] = _Helper()
930 930 except ImportError:
931 931 warn('help() not available - check site.py')
932 932
933 933 # make global variables for user access to the histories
934 934 ns['_ih'] = self.input_hist
935 935 ns['_oh'] = self.output_hist
936 936 ns['_dh'] = self.dir_hist
937 937
938 938 ns['_sh'] = shadowns
939 939
940 940 # user aliases to input and output histories. These shouldn't show up
941 941 # in %who, as they can have very large reprs.
942 942 ns['In'] = self.input_hist
943 943 ns['Out'] = self.output_hist
944 944
945 945 # Store myself as the public api!!!
946 946 ns['get_ipython'] = self.get_ipython
947 947
948 948 # Sync what we've added so far to user_ns_hidden so these aren't seen
949 949 # by %who
950 950 self.user_ns_hidden.update(ns)
951 951
952 952 # Anything put into ns now would show up in %who. Think twice before
953 953 # putting anything here, as we really want %who to show the user their
954 954 # stuff, not our variables.
955 955
956 956 # Finally, update the real user's namespace
957 957 self.user_ns.update(ns)
958 958
959 959
960 960 def reset(self):
961 961 """Clear all internal namespaces.
962 962
963 963 Note that this is much more aggressive than %reset, since it clears
964 964 fully all namespaces, as well as all input/output lists.
965 965 """
966 966 for ns in self.ns_refs_table:
967 967 ns.clear()
968 968
969 969 self.alias_manager.clear_aliases()
970 970
971 971 # Clear input and output histories
972 972 self.input_hist[:] = []
973 973 self.input_hist_raw[:] = []
974 974 self.output_hist.clear()
975 975
976 976 # Restore the user namespaces to minimal usability
977 977 self.init_user_ns()
978 978
979 979 # Restore the default and user aliases
980 980 self.alias_manager.init_aliases()
981 981
982 982 def reset_selective(self, regex=None):
983 983 """Clear selective variables from internal namespaces based on a
984 984 specified regular expression.
985 985
986 986 Parameters
987 987 ----------
988 988 regex : string or compiled pattern, optional
989 989 A regular expression pattern that will be used in searching
990 990 variable names in the users namespaces.
991 991 """
992 992 if regex is not None:
993 993 try:
994 994 m = re.compile(regex)
995 995 except TypeError:
996 996 raise TypeError('regex must be a string or compiled pattern')
997 997 # Search for keys in each namespace that match the given regex
998 998 # If a match is found, delete the key/value pair.
999 999 for ns in self.ns_refs_table:
1000 1000 for var in ns:
1001 1001 if m.search(var):
1002 1002 del ns[var]
1003 1003
1004 1004 def push(self, variables, interactive=True):
1005 1005 """Inject a group of variables into the IPython user namespace.
1006 1006
1007 1007 Parameters
1008 1008 ----------
1009 1009 variables : dict, str or list/tuple of str
1010 1010 The variables to inject into the user's namespace. If a dict, a
1011 1011 simple update is done. If a str, the string is assumed to have
1012 1012 variable names separated by spaces. A list/tuple of str can also
1013 1013 be used to give the variable names. If just the variable names are
1014 1014 give (list/tuple/str) then the variable values looked up in the
1015 1015 callers frame.
1016 1016 interactive : bool
1017 1017 If True (default), the variables will be listed with the ``who``
1018 1018 magic.
1019 1019 """
1020 1020 vdict = None
1021 1021
1022 1022 # We need a dict of name/value pairs to do namespace updates.
1023 1023 if isinstance(variables, dict):
1024 1024 vdict = variables
1025 1025 elif isinstance(variables, (basestring, list, tuple)):
1026 1026 if isinstance(variables, basestring):
1027 1027 vlist = variables.split()
1028 1028 else:
1029 1029 vlist = variables
1030 1030 vdict = {}
1031 1031 cf = sys._getframe(1)
1032 1032 for name in vlist:
1033 1033 try:
1034 1034 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1035 1035 except:
1036 1036 print ('Could not get variable %s from %s' %
1037 1037 (name,cf.f_code.co_name))
1038 1038 else:
1039 1039 raise ValueError('variables must be a dict/str/list/tuple')
1040 1040
1041 1041 # Propagate variables to user namespace
1042 1042 self.user_ns.update(vdict)
1043 1043
1044 1044 # And configure interactive visibility
1045 1045 config_ns = self.user_ns_hidden
1046 1046 if interactive:
1047 1047 for name, val in vdict.iteritems():
1048 1048 config_ns.pop(name, None)
1049 1049 else:
1050 1050 for name,val in vdict.iteritems():
1051 1051 config_ns[name] = val
1052 1052
1053 1053 #-------------------------------------------------------------------------
1054 1054 # Things related to object introspection
1055 1055 #-------------------------------------------------------------------------
1056 1056 def _ofind(self, oname, namespaces=None):
1057 1057 """Find an object in the available namespaces.
1058 1058
1059 1059 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1060 1060
1061 1061 Has special code to detect magic functions.
1062 1062 """
1063 1063 #oname = oname.strip()
1064 1064 #print '1- oname: <%r>' % oname # dbg
1065 1065 try:
1066 1066 oname = oname.strip().encode('ascii')
1067 1067 #print '2- oname: <%r>' % oname # dbg
1068 1068 except UnicodeEncodeError:
1069 1069 print 'Python identifiers can only contain ascii characters.'
1070 1070 return dict(found=False)
1071 1071
1072 1072 alias_ns = None
1073 1073 if namespaces is None:
1074 1074 # Namespaces to search in:
1075 1075 # Put them in a list. The order is important so that we
1076 1076 # find things in the same order that Python finds them.
1077 1077 namespaces = [ ('Interactive', self.user_ns),
1078 1078 ('IPython internal', self.internal_ns),
1079 1079 ('Python builtin', __builtin__.__dict__),
1080 1080 ('Alias', self.alias_manager.alias_table),
1081 1081 ]
1082 1082 alias_ns = self.alias_manager.alias_table
1083 1083
1084 1084 # initialize results to 'null'
1085 1085 found = False; obj = None; ospace = None; ds = None;
1086 1086 ismagic = False; isalias = False; parent = None
1087 1087
1088 1088 # We need to special-case 'print', which as of python2.6 registers as a
1089 1089 # function but should only be treated as one if print_function was
1090 1090 # loaded with a future import. In this case, just bail.
1091 1091 if (oname == 'print' and not (self.compile.compiler.flags &
1092 1092 __future__.CO_FUTURE_PRINT_FUNCTION)):
1093 1093 return {'found':found, 'obj':obj, 'namespace':ospace,
1094 1094 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1095 1095
1096 1096 # Look for the given name by splitting it in parts. If the head is
1097 1097 # found, then we look for all the remaining parts as members, and only
1098 1098 # declare success if we can find them all.
1099 1099 oname_parts = oname.split('.')
1100 1100 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1101 1101 for nsname,ns in namespaces:
1102 1102 try:
1103 1103 obj = ns[oname_head]
1104 1104 except KeyError:
1105 1105 continue
1106 1106 else:
1107 1107 #print 'oname_rest:', oname_rest # dbg
1108 1108 for part in oname_rest:
1109 1109 try:
1110 1110 parent = obj
1111 1111 obj = getattr(obj,part)
1112 1112 except:
1113 1113 # Blanket except b/c some badly implemented objects
1114 1114 # allow __getattr__ to raise exceptions other than
1115 1115 # AttributeError, which then crashes IPython.
1116 1116 break
1117 1117 else:
1118 1118 # If we finish the for loop (no break), we got all members
1119 1119 found = True
1120 1120 ospace = nsname
1121 1121 if ns == alias_ns:
1122 1122 isalias = True
1123 1123 break # namespace loop
1124 1124
1125 1125 # Try to see if it's magic
1126 1126 if not found:
1127 1127 if oname.startswith(ESC_MAGIC):
1128 1128 oname = oname[1:]
1129 1129 obj = getattr(self,'magic_'+oname,None)
1130 1130 if obj is not None:
1131 1131 found = True
1132 1132 ospace = 'IPython internal'
1133 1133 ismagic = True
1134 1134
1135 1135 # Last try: special-case some literals like '', [], {}, etc:
1136 1136 if not found and oname_head in ["''",'""','[]','{}','()']:
1137 1137 obj = eval(oname_head)
1138 1138 found = True
1139 1139 ospace = 'Interactive'
1140 1140
1141 1141 return {'found':found, 'obj':obj, 'namespace':ospace,
1142 1142 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1143 1143
1144 1144 def _ofind_property(self, oname, info):
1145 1145 """Second part of object finding, to look for property details."""
1146 1146 if info.found:
1147 1147 # Get the docstring of the class property if it exists.
1148 1148 path = oname.split('.')
1149 1149 root = '.'.join(path[:-1])
1150 1150 if info.parent is not None:
1151 1151 try:
1152 1152 target = getattr(info.parent, '__class__')
1153 1153 # The object belongs to a class instance.
1154 1154 try:
1155 1155 target = getattr(target, path[-1])
1156 1156 # The class defines the object.
1157 1157 if isinstance(target, property):
1158 1158 oname = root + '.__class__.' + path[-1]
1159 1159 info = Struct(self._ofind(oname))
1160 1160 except AttributeError: pass
1161 1161 except AttributeError: pass
1162 1162
1163 1163 # We return either the new info or the unmodified input if the object
1164 1164 # hadn't been found
1165 1165 return info
1166 1166
1167 1167 def _object_find(self, oname, namespaces=None):
1168 1168 """Find an object and return a struct with info about it."""
1169 1169 inf = Struct(self._ofind(oname, namespaces))
1170 1170 return Struct(self._ofind_property(oname, inf))
1171 1171
1172 1172 def _inspect(self, meth, oname, namespaces=None, **kw):
1173 1173 """Generic interface to the inspector system.
1174 1174
1175 1175 This function is meant to be called by pdef, pdoc & friends."""
1176 1176 info = self._object_find(oname)
1177 1177 if info.found:
1178 1178 pmethod = getattr(self.inspector, meth)
1179 1179 formatter = format_screen if info.ismagic else None
1180 1180 if meth == 'pdoc':
1181 1181 pmethod(info.obj, oname, formatter)
1182 1182 elif meth == 'pinfo':
1183 1183 pmethod(info.obj, oname, formatter, info, **kw)
1184 1184 else:
1185 1185 pmethod(info.obj, oname)
1186 1186 else:
1187 1187 print 'Object `%s` not found.' % oname
1188 1188 return 'not found' # so callers can take other action
1189 1189
1190 1190 def object_inspect(self, oname):
1191 1191 info = self._object_find(oname)
1192 1192 if info.found:
1193 1193 return self.inspector.info(info.obj, info=info)
1194 1194 else:
1195 1195 return oinspect.mk_object_info({'found' : False})
1196 1196
1197 1197 #-------------------------------------------------------------------------
1198 1198 # Things related to history management
1199 1199 #-------------------------------------------------------------------------
1200 1200
1201 1201 def init_history(self):
1202 1202 # List of input with multi-line handling.
1203 1203 self.input_hist = InputList()
1204 1204 # This one will hold the 'raw' input history, without any
1205 1205 # pre-processing. This will allow users to retrieve the input just as
1206 1206 # it was exactly typed in by the user, with %hist -r.
1207 1207 self.input_hist_raw = InputList()
1208 1208
1209 1209 # list of visited directories
1210 1210 try:
1211 1211 self.dir_hist = [os.getcwd()]
1212 1212 except OSError:
1213 1213 self.dir_hist = []
1214 1214
1215 1215 # dict of output history
1216 1216 self.output_hist = {}
1217 1217
1218 1218 # Now the history file
1219 1219 if self.profile:
1220 1220 histfname = 'history-%s' % self.profile
1221 1221 else:
1222 1222 histfname = 'history'
1223 1223 self.histfile = os.path.join(self.ipython_dir, histfname)
1224 1224
1225 1225 # Fill the history zero entry, user counter starts at 1
1226 1226 self.input_hist.append('\n')
1227 1227 self.input_hist_raw.append('\n')
1228 1228
1229 1229 def init_shadow_hist(self):
1230 1230 try:
1231 1231 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1232 1232 except exceptions.UnicodeDecodeError:
1233 1233 print "Your ipython_dir can't be decoded to unicode!"
1234 1234 print "Please set HOME environment variable to something that"
1235 1235 print r"only has ASCII characters, e.g. c:\home"
1236 1236 print "Now it is", self.ipython_dir
1237 1237 sys.exit()
1238 1238 self.shadowhist = ipcorehist.ShadowHist(self.db)
1239 1239
1240 1240 def savehist(self):
1241 1241 """Save input history to a file (via readline library)."""
1242 1242
1243 1243 try:
1244 1244 self.readline.write_history_file(self.histfile)
1245 1245 except:
1246 1246 print 'Unable to save IPython command history to file: ' + \
1247 1247 `self.histfile`
1248 1248
1249 1249 def reloadhist(self):
1250 1250 """Reload the input history from disk file."""
1251 1251
1252 1252 try:
1253 1253 self.readline.clear_history()
1254 1254 self.readline.read_history_file(self.shell.histfile)
1255 1255 except AttributeError:
1256 1256 pass
1257 1257
1258 1258 def history_saving_wrapper(self, func):
1259 1259 """ Wrap func for readline history saving
1260 1260
1261 1261 Convert func into callable that saves & restores
1262 1262 history around the call """
1263 1263
1264 1264 if self.has_readline:
1265 1265 from IPython.utils import rlineimpl as readline
1266 1266 else:
1267 1267 return func
1268 1268
1269 1269 def wrapper():
1270 1270 self.savehist()
1271 1271 try:
1272 1272 func()
1273 1273 finally:
1274 1274 readline.read_history_file(self.histfile)
1275 1275 return wrapper
1276 1276
1277 1277 def get_history(self, index=None, raw=False, output=True):
1278 1278 """Get the history list.
1279 1279
1280 1280 Get the input and output history.
1281 1281
1282 1282 Parameters
1283 1283 ----------
1284 1284 index : n or (n1, n2) or None
1285 1285 If n, then the last entries. If a tuple, then all in
1286 1286 range(n1, n2). If None, then all entries. Raises IndexError if
1287 1287 the format of index is incorrect.
1288 1288 raw : bool
1289 1289 If True, return the raw input.
1290 1290 output : bool
1291 1291 If True, then return the output as well.
1292 1292
1293 1293 Returns
1294 1294 -------
1295 1295 If output is True, then return a dict of tuples, keyed by the prompt
1296 1296 numbers and with values of (input, output). If output is False, then
1297 1297 a dict, keyed by the prompt number with the values of input. Raises
1298 1298 IndexError if no history is found.
1299 1299 """
1300 1300 if raw:
1301 1301 input_hist = self.input_hist_raw
1302 1302 else:
1303 1303 input_hist = self.input_hist
1304 1304 if output:
1305 1305 output_hist = self.user_ns['Out']
1306 1306 n = len(input_hist)
1307 1307 if index is None:
1308 1308 start=0; stop=n
1309 1309 elif isinstance(index, int):
1310 1310 start=n-index; stop=n
1311 1311 elif isinstance(index, tuple) and len(index) == 2:
1312 1312 start=index[0]; stop=index[1]
1313 1313 else:
1314 1314 raise IndexError('Not a valid index for the input history: %r'
1315 1315 % index)
1316 1316 hist = {}
1317 1317 for i in range(start, stop):
1318 1318 if output:
1319 1319 hist[i] = (input_hist[i], output_hist.get(i))
1320 1320 else:
1321 1321 hist[i] = input_hist[i]
1322 1322 if len(hist)==0:
1323 1323 raise IndexError('No history for range of indices: %r' % index)
1324 1324 return hist
1325 1325
1326 1326 #-------------------------------------------------------------------------
1327 1327 # Things related to exception handling and tracebacks (not debugging)
1328 1328 #-------------------------------------------------------------------------
1329 1329
1330 1330 def init_traceback_handlers(self, custom_exceptions):
1331 1331 # Syntax error handler.
1332 1332 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1333 1333
1334 1334 # The interactive one is initialized with an offset, meaning we always
1335 1335 # want to remove the topmost item in the traceback, which is our own
1336 1336 # internal code. Valid modes: ['Plain','Context','Verbose']
1337 1337 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1338 1338 color_scheme='NoColor',
1339 1339 tb_offset = 1)
1340 1340
1341 1341 # The instance will store a pointer to the system-wide exception hook,
1342 1342 # so that runtime code (such as magics) can access it. This is because
1343 1343 # during the read-eval loop, it may get temporarily overwritten.
1344 1344 self.sys_excepthook = sys.excepthook
1345 1345
1346 1346 # and add any custom exception handlers the user may have specified
1347 1347 self.set_custom_exc(*custom_exceptions)
1348 1348
1349 1349 # Set the exception mode
1350 1350 self.InteractiveTB.set_mode(mode=self.xmode)
1351 1351
1352 1352 def set_custom_exc(self, exc_tuple, handler):
1353 1353 """set_custom_exc(exc_tuple,handler)
1354 1354
1355 1355 Set a custom exception handler, which will be called if any of the
1356 1356 exceptions in exc_tuple occur in the mainloop (specifically, in the
1357 1357 runcode() method.
1358 1358
1359 1359 Inputs:
1360 1360
1361 1361 - exc_tuple: a *tuple* of valid exceptions to call the defined
1362 1362 handler for. It is very important that you use a tuple, and NOT A
1363 1363 LIST here, because of the way Python's except statement works. If
1364 1364 you only want to trap a single exception, use a singleton tuple:
1365 1365
1366 1366 exc_tuple == (MyCustomException,)
1367 1367
1368 1368 - handler: this must be defined as a function with the following
1369 1369 basic interface::
1370 1370
1371 1371 def my_handler(self, etype, value, tb, tb_offset=None)
1372 1372 ...
1373 1373 # The return value must be
1374 1374 return structured_traceback
1375 1375
1376 1376 This will be made into an instance method (via new.instancemethod)
1377 1377 of IPython itself, and it will be called if any of the exceptions
1378 1378 listed in the exc_tuple are caught. If the handler is None, an
1379 1379 internal basic one is used, which just prints basic info.
1380 1380
1381 1381 WARNING: by putting in your own exception handler into IPython's main
1382 1382 execution loop, you run a very good chance of nasty crashes. This
1383 1383 facility should only be used if you really know what you are doing."""
1384 1384
1385 1385 assert type(exc_tuple)==type(()) , \
1386 1386 "The custom exceptions must be given AS A TUPLE."
1387 1387
1388 1388 def dummy_handler(self,etype,value,tb):
1389 1389 print '*** Simple custom exception handler ***'
1390 1390 print 'Exception type :',etype
1391 1391 print 'Exception value:',value
1392 1392 print 'Traceback :',tb
1393 1393 print 'Source code :','\n'.join(self.buffer)
1394 1394
1395 1395 if handler is None: handler = dummy_handler
1396 1396
1397 1397 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1398 1398 self.custom_exceptions = exc_tuple
1399 1399
1400 1400 def excepthook(self, etype, value, tb):
1401 1401 """One more defense for GUI apps that call sys.excepthook.
1402 1402
1403 1403 GUI frameworks like wxPython trap exceptions and call
1404 1404 sys.excepthook themselves. I guess this is a feature that
1405 1405 enables them to keep running after exceptions that would
1406 1406 otherwise kill their mainloop. This is a bother for IPython
1407 1407 which excepts to catch all of the program exceptions with a try:
1408 1408 except: statement.
1409 1409
1410 1410 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1411 1411 any app directly invokes sys.excepthook, it will look to the user like
1412 1412 IPython crashed. In order to work around this, we can disable the
1413 1413 CrashHandler and replace it with this excepthook instead, which prints a
1414 1414 regular traceback using our InteractiveTB. In this fashion, apps which
1415 1415 call sys.excepthook will generate a regular-looking exception from
1416 1416 IPython, and the CrashHandler will only be triggered by real IPython
1417 1417 crashes.
1418 1418
1419 1419 This hook should be used sparingly, only in places which are not likely
1420 1420 to be true IPython errors.
1421 1421 """
1422 1422 self.showtraceback((etype,value,tb),tb_offset=0)
1423 1423
1424 1424 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1425 1425 exception_only=False):
1426 1426 """Display the exception that just occurred.
1427 1427
1428 1428 If nothing is known about the exception, this is the method which
1429 1429 should be used throughout the code for presenting user tracebacks,
1430 1430 rather than directly invoking the InteractiveTB object.
1431 1431
1432 1432 A specific showsyntaxerror() also exists, but this method can take
1433 1433 care of calling it if needed, so unless you are explicitly catching a
1434 1434 SyntaxError exception, don't try to analyze the stack manually and
1435 1435 simply call this method."""
1436 1436
1437 1437 try:
1438 1438 if exc_tuple is None:
1439 1439 etype, value, tb = sys.exc_info()
1440 1440 else:
1441 1441 etype, value, tb = exc_tuple
1442 1442
1443 1443 if etype is None:
1444 1444 if hasattr(sys, 'last_type'):
1445 1445 etype, value, tb = sys.last_type, sys.last_value, \
1446 1446 sys.last_traceback
1447 1447 else:
1448 1448 self.write_err('No traceback available to show.\n')
1449 1449 return
1450 1450
1451 1451 if etype is SyntaxError:
1452 1452 # Though this won't be called by syntax errors in the input
1453 1453 # line, there may be SyntaxError cases whith imported code.
1454 1454 self.showsyntaxerror(filename)
1455 1455 elif etype is UsageError:
1456 1456 print "UsageError:", value
1457 1457 else:
1458 1458 # WARNING: these variables are somewhat deprecated and not
1459 1459 # necessarily safe to use in a threaded environment, but tools
1460 1460 # like pdb depend on their existence, so let's set them. If we
1461 1461 # find problems in the field, we'll need to revisit their use.
1462 1462 sys.last_type = etype
1463 1463 sys.last_value = value
1464 1464 sys.last_traceback = tb
1465 1465
1466 1466 if etype in self.custom_exceptions:
1467 1467 # FIXME: Old custom traceback objects may just return a
1468 1468 # string, in that case we just put it into a list
1469 1469 stb = self.CustomTB(etype, value, tb, tb_offset)
1470 1470 if isinstance(ctb, basestring):
1471 1471 stb = [stb]
1472 1472 else:
1473 1473 if exception_only:
1474 1474 stb = ['An exception has occurred, use %tb to see '
1475 1475 'the full traceback.\n']
1476 1476 stb.extend(self.InteractiveTB.get_exception_only(etype,
1477 1477 value))
1478 1478 else:
1479 1479 stb = self.InteractiveTB.structured_traceback(etype,
1480 1480 value, tb, tb_offset=tb_offset)
1481 1481 # FIXME: the pdb calling should be done by us, not by
1482 1482 # the code computing the traceback.
1483 1483 if self.InteractiveTB.call_pdb:
1484 1484 # pdb mucks up readline, fix it back
1485 1485 self.set_readline_completer()
1486 1486
1487 1487 # Actually show the traceback
1488 1488 self._showtraceback(etype, value, stb)
1489 1489
1490 1490 except KeyboardInterrupt:
1491 1491 self.write_err("\nKeyboardInterrupt\n")
1492 1492
1493 1493 def _showtraceback(self, etype, evalue, stb):
1494 1494 """Actually show a traceback.
1495 1495
1496 1496 Subclasses may override this method to put the traceback on a different
1497 1497 place, like a side channel.
1498 1498 """
1499 1499 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1500 1500
1501 1501 def showsyntaxerror(self, filename=None):
1502 1502 """Display the syntax error that just occurred.
1503 1503
1504 1504 This doesn't display a stack trace because there isn't one.
1505 1505
1506 1506 If a filename is given, it is stuffed in the exception instead
1507 1507 of what was there before (because Python's parser always uses
1508 1508 "<string>" when reading from a string).
1509 1509 """
1510 1510 etype, value, last_traceback = sys.exc_info()
1511 1511
1512 1512 # See note about these variables in showtraceback() above
1513 1513 sys.last_type = etype
1514 1514 sys.last_value = value
1515 1515 sys.last_traceback = last_traceback
1516 1516
1517 1517 if filename and etype is SyntaxError:
1518 1518 # Work hard to stuff the correct filename in the exception
1519 1519 try:
1520 1520 msg, (dummy_filename, lineno, offset, line) = value
1521 1521 except:
1522 1522 # Not the format we expect; leave it alone
1523 1523 pass
1524 1524 else:
1525 1525 # Stuff in the right filename
1526 1526 try:
1527 1527 # Assume SyntaxError is a class exception
1528 1528 value = SyntaxError(msg, (filename, lineno, offset, line))
1529 1529 except:
1530 1530 # If that failed, assume SyntaxError is a string
1531 1531 value = msg, (filename, lineno, offset, line)
1532 1532 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1533 1533 self._showtraceback(etype, value, stb)
1534 1534
1535 1535 #-------------------------------------------------------------------------
1536 1536 # Things related to readline
1537 1537 #-------------------------------------------------------------------------
1538 1538
1539 1539 def init_readline(self):
1540 1540 """Command history completion/saving/reloading."""
1541 1541
1542 1542 if self.readline_use:
1543 1543 import IPython.utils.rlineimpl as readline
1544 1544
1545 1545 self.rl_next_input = None
1546 1546 self.rl_do_indent = False
1547 1547
1548 1548 if not self.readline_use or not readline.have_readline:
1549 1549 self.has_readline = False
1550 1550 self.readline = None
1551 1551 # Set a number of methods that depend on readline to be no-op
1552 1552 self.savehist = no_op
1553 1553 self.reloadhist = no_op
1554 1554 self.set_readline_completer = no_op
1555 1555 self.set_custom_completer = no_op
1556 1556 self.set_completer_frame = no_op
1557 1557 warn('Readline services not available or not loaded.')
1558 1558 else:
1559 1559 self.has_readline = True
1560 1560 self.readline = readline
1561 1561 sys.modules['readline'] = readline
1562 1562
1563 1563 # Platform-specific configuration
1564 1564 if os.name == 'nt':
1565 1565 # FIXME - check with Frederick to see if we can harmonize
1566 1566 # naming conventions with pyreadline to avoid this
1567 1567 # platform-dependent check
1568 1568 self.readline_startup_hook = readline.set_pre_input_hook
1569 1569 else:
1570 1570 self.readline_startup_hook = readline.set_startup_hook
1571 1571
1572 1572 # Load user's initrc file (readline config)
1573 1573 # Or if libedit is used, load editrc.
1574 1574 inputrc_name = os.environ.get('INPUTRC')
1575 1575 if inputrc_name is None:
1576 1576 home_dir = get_home_dir()
1577 1577 if home_dir is not None:
1578 1578 inputrc_name = '.inputrc'
1579 1579 if readline.uses_libedit:
1580 1580 inputrc_name = '.editrc'
1581 1581 inputrc_name = os.path.join(home_dir, inputrc_name)
1582 1582 if os.path.isfile(inputrc_name):
1583 1583 try:
1584 1584 readline.read_init_file(inputrc_name)
1585 1585 except:
1586 1586 warn('Problems reading readline initialization file <%s>'
1587 1587 % inputrc_name)
1588 1588
1589 1589 # Configure readline according to user's prefs
1590 1590 # This is only done if GNU readline is being used. If libedit
1591 1591 # is being used (as on Leopard) the readline config is
1592 1592 # not run as the syntax for libedit is different.
1593 1593 if not readline.uses_libedit:
1594 1594 for rlcommand in self.readline_parse_and_bind:
1595 1595 #print "loading rl:",rlcommand # dbg
1596 1596 readline.parse_and_bind(rlcommand)
1597 1597
1598 1598 # Remove some chars from the delimiters list. If we encounter
1599 1599 # unicode chars, discard them.
1600 1600 delims = readline.get_completer_delims().encode("ascii", "ignore")
1601 1601 delims = delims.translate(string._idmap,
1602 1602 self.readline_remove_delims)
1603 1603 delims = delims.replace(ESC_MAGIC, '')
1604 1604 readline.set_completer_delims(delims)
1605 1605 # otherwise we end up with a monster history after a while:
1606 1606 readline.set_history_length(1000)
1607 1607 try:
1608 1608 #print '*** Reading readline history' # dbg
1609 1609 readline.read_history_file(self.histfile)
1610 1610 except IOError:
1611 1611 pass # It doesn't exist yet.
1612 1612
1613 1613 # If we have readline, we want our history saved upon ipython
1614 1614 # exiting.
1615 1615 atexit.register(self.savehist)
1616 1616
1617 1617 # Configure auto-indent for all platforms
1618 1618 self.set_autoindent(self.autoindent)
1619 1619
1620 1620 def set_next_input(self, s):
1621 1621 """ Sets the 'default' input string for the next command line.
1622 1622
1623 1623 Requires readline.
1624 1624
1625 1625 Example:
1626 1626
1627 1627 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1628 1628 [D:\ipython]|2> Hello Word_ # cursor is here
1629 1629 """
1630 1630
1631 1631 self.rl_next_input = s
1632 1632
1633 1633 # Maybe move this to the terminal subclass?
1634 1634 def pre_readline(self):
1635 1635 """readline hook to be used at the start of each line.
1636 1636
1637 1637 Currently it handles auto-indent only."""
1638 1638
1639 1639 if self.rl_do_indent:
1640 1640 self.readline.insert_text(self._indent_current_str())
1641 1641 if self.rl_next_input is not None:
1642 1642 self.readline.insert_text(self.rl_next_input)
1643 1643 self.rl_next_input = None
1644 1644
1645 1645 def _indent_current_str(self):
1646 1646 """return the current level of indentation as a string"""
1647 1647 return self.indent_current_nsp * ' '
1648 1648
1649 1649 #-------------------------------------------------------------------------
1650 1650 # Things related to text completion
1651 1651 #-------------------------------------------------------------------------
1652 1652
1653 1653 def init_completer(self):
1654 1654 """Initialize the completion machinery.
1655 1655
1656 1656 This creates completion machinery that can be used by client code,
1657 1657 either interactively in-process (typically triggered by the readline
1658 1658 library), programatically (such as in test suites) or out-of-prcess
1659 1659 (typically over the network by remote frontends).
1660 1660 """
1661 1661 from IPython.core.completer import IPCompleter
1662 1662 from IPython.core.completerlib import (module_completer,
1663 1663 magic_run_completer, cd_completer)
1664 1664
1665 1665 self.Completer = IPCompleter(self,
1666 1666 self.user_ns,
1667 1667 self.user_global_ns,
1668 1668 self.readline_omit__names,
1669 1669 self.alias_manager.alias_table,
1670 1670 self.has_readline)
1671 1671
1672 1672 # Add custom completers to the basic ones built into IPCompleter
1673 1673 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1674 1674 self.strdispatchers['complete_command'] = sdisp
1675 1675 self.Completer.custom_completers = sdisp
1676 1676
1677 1677 self.set_hook('complete_command', module_completer, str_key = 'import')
1678 1678 self.set_hook('complete_command', module_completer, str_key = 'from')
1679 1679 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1680 1680 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1681 1681
1682 1682 # Only configure readline if we truly are using readline. IPython can
1683 1683 # do tab-completion over the network, in GUIs, etc, where readline
1684 1684 # itself may be absent
1685 1685 if self.has_readline:
1686 1686 self.set_readline_completer()
1687 1687
1688 1688 def complete(self, text, line=None, cursor_pos=None):
1689 1689 """Return the completed text and a list of completions.
1690 1690
1691 1691 Parameters
1692 1692 ----------
1693 1693
1694 1694 text : string
1695 1695 A string of text to be completed on. It can be given as empty and
1696 1696 instead a line/position pair are given. In this case, the
1697 1697 completer itself will split the line like readline does.
1698 1698
1699 1699 line : string, optional
1700 1700 The complete line that text is part of.
1701 1701
1702 1702 cursor_pos : int, optional
1703 1703 The position of the cursor on the input line.
1704 1704
1705 1705 Returns
1706 1706 -------
1707 1707 text : string
1708 1708 The actual text that was completed.
1709 1709
1710 1710 matches : list
1711 1711 A sorted list with all possible completions.
1712 1712
1713 1713 The optional arguments allow the completion to take more context into
1714 1714 account, and are part of the low-level completion API.
1715 1715
1716 1716 This is a wrapper around the completion mechanism, similar to what
1717 1717 readline does at the command line when the TAB key is hit. By
1718 1718 exposing it as a method, it can be used by other non-readline
1719 1719 environments (such as GUIs) for text completion.
1720 1720
1721 1721 Simple usage example:
1722 1722
1723 1723 In [1]: x = 'hello'
1724 1724
1725 1725 In [2]: _ip.complete('x.l')
1726 1726 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1727 1727 """
1728 1728
1729 1729 # Inject names into __builtin__ so we can complete on the added names.
1730 1730 with self.builtin_trap:
1731 1731 return self.Completer.complete(text, line, cursor_pos)
1732 1732
1733 1733 def set_custom_completer(self, completer, pos=0):
1734 1734 """Adds a new custom completer function.
1735 1735
1736 1736 The position argument (defaults to 0) is the index in the completers
1737 1737 list where you want the completer to be inserted."""
1738 1738
1739 1739 newcomp = new.instancemethod(completer,self.Completer,
1740 1740 self.Completer.__class__)
1741 1741 self.Completer.matchers.insert(pos,newcomp)
1742 1742
1743 1743 def set_readline_completer(self):
1744 1744 """Reset readline's completer to be our own."""
1745 1745 self.readline.set_completer(self.Completer.rlcomplete)
1746 1746
1747 1747 def set_completer_frame(self, frame=None):
1748 1748 """Set the frame of the completer."""
1749 1749 if frame:
1750 1750 self.Completer.namespace = frame.f_locals
1751 1751 self.Completer.global_namespace = frame.f_globals
1752 1752 else:
1753 1753 self.Completer.namespace = self.user_ns
1754 1754 self.Completer.global_namespace = self.user_global_ns
1755 1755
1756 1756 #-------------------------------------------------------------------------
1757 1757 # Things related to magics
1758 1758 #-------------------------------------------------------------------------
1759 1759
1760 1760 def init_magics(self):
1761 1761 # FIXME: Move the color initialization to the DisplayHook, which
1762 1762 # should be split into a prompt manager and displayhook. We probably
1763 1763 # even need a centralize colors management object.
1764 1764 self.magic_colors(self.colors)
1765 1765 # History was moved to a separate module
1766 1766 from . import history
1767 1767 history.init_ipython(self)
1768 1768
1769 1769 def magic(self,arg_s):
1770 1770 """Call a magic function by name.
1771 1771
1772 1772 Input: a string containing the name of the magic function to call and
1773 1773 any additional arguments to be passed to the magic.
1774 1774
1775 1775 magic('name -opt foo bar') is equivalent to typing at the ipython
1776 1776 prompt:
1777 1777
1778 1778 In[1]: %name -opt foo bar
1779 1779
1780 1780 To call a magic without arguments, simply use magic('name').
1781 1781
1782 1782 This provides a proper Python function to call IPython's magics in any
1783 1783 valid Python code you can type at the interpreter, including loops and
1784 1784 compound statements.
1785 1785 """
1786 1786 args = arg_s.split(' ',1)
1787 1787 magic_name = args[0]
1788 1788 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1789 1789
1790 1790 try:
1791 1791 magic_args = args[1]
1792 1792 except IndexError:
1793 1793 magic_args = ''
1794 1794 fn = getattr(self,'magic_'+magic_name,None)
1795 1795 if fn is None:
1796 1796 error("Magic function `%s` not found." % magic_name)
1797 1797 else:
1798 1798 magic_args = self.var_expand(magic_args,1)
1799 1799 with nested(self.builtin_trap,):
1800 1800 result = fn(magic_args)
1801 1801 return result
1802 1802
1803 1803 def define_magic(self, magicname, func):
1804 1804 """Expose own function as magic function for ipython
1805 1805
1806 1806 def foo_impl(self,parameter_s=''):
1807 1807 'My very own magic!. (Use docstrings, IPython reads them).'
1808 1808 print 'Magic function. Passed parameter is between < >:'
1809 1809 print '<%s>' % parameter_s
1810 1810 print 'The self object is:',self
1811 1811
1812 1812 self.define_magic('foo',foo_impl)
1813 1813 """
1814 1814
1815 1815 import new
1816 1816 im = new.instancemethod(func,self, self.__class__)
1817 1817 old = getattr(self, "magic_" + magicname, None)
1818 1818 setattr(self, "magic_" + magicname, im)
1819 1819 return old
1820 1820
1821 1821 #-------------------------------------------------------------------------
1822 1822 # Things related to macros
1823 1823 #-------------------------------------------------------------------------
1824 1824
1825 1825 def define_macro(self, name, themacro):
1826 1826 """Define a new macro
1827 1827
1828 1828 Parameters
1829 1829 ----------
1830 1830 name : str
1831 1831 The name of the macro.
1832 1832 themacro : str or Macro
1833 1833 The action to do upon invoking the macro. If a string, a new
1834 1834 Macro object is created by passing the string to it.
1835 1835 """
1836 1836
1837 1837 from IPython.core import macro
1838 1838
1839 1839 if isinstance(themacro, basestring):
1840 1840 themacro = macro.Macro(themacro)
1841 1841 if not isinstance(themacro, macro.Macro):
1842 1842 raise ValueError('A macro must be a string or a Macro instance.')
1843 1843 self.user_ns[name] = themacro
1844 1844
1845 1845 #-------------------------------------------------------------------------
1846 1846 # Things related to the running of system commands
1847 1847 #-------------------------------------------------------------------------
1848 1848
1849 1849 def system(self, cmd):
1850 """Call the given cmd in a subprocess."""
1850 """Call the given cmd in a subprocess.
1851
1852 Parameters
1853 ----------
1854 cmd : str
1855 Command to execute (can not end in '&', as bacground processes are
1856 not supported.
1857 """
1851 1858 # We do not support backgrounding processes because we either use
1852 1859 # pexpect or pipes to read from. Users can always just call
1853 1860 # os.system() if they really want a background process.
1854 1861 if cmd.endswith('&'):
1855 1862 raise OSError("Background processes not supported.")
1856 1863
1857 1864 return system(self.var_expand(cmd, depth=2))
1858 1865
1859 def getoutput(self, cmd):
1860 """Get output (possibly including stderr) from a subprocess."""
1866 def getoutput(self, cmd, split=True):
1867 """Get output (possibly including stderr) from a subprocess.
1868
1869 Parameters
1870 ----------
1871 cmd : str
1872 Command to execute (can not end in '&', as bacground processes are
1873 not supported.
1874 split : bool, optional
1875
1876 If True, split the output into an IPython SList. Otherwise, an
1877 IPython LSString is returned. These are objects similar to normal
1878 lists and strings, with a few convenience attributes for easier
1879 manipulation of line-based output. You can use '?' on them for
1880 details.
1881 """
1861 1882 if cmd.endswith('&'):
1862 1883 raise OSError("Background processes not supported.")
1863 return getoutput(self.var_expand(cmd, depth=2))
1884 out = getoutput(self.var_expand(cmd, depth=2))
1885 if split:
1886 out = SList(out.splitlines())
1887 else:
1888 out = LSString(out)
1889 return out
1864 1890
1865 1891 #-------------------------------------------------------------------------
1866 1892 # Things related to aliases
1867 1893 #-------------------------------------------------------------------------
1868 1894
1869 1895 def init_alias(self):
1870 1896 self.alias_manager = AliasManager(shell=self, config=self.config)
1871 1897 self.ns_table['alias'] = self.alias_manager.alias_table,
1872 1898
1873 1899 #-------------------------------------------------------------------------
1874 1900 # Things related to extensions and plugins
1875 1901 #-------------------------------------------------------------------------
1876 1902
1877 1903 def init_extension_manager(self):
1878 1904 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1879 1905
1880 1906 def init_plugin_manager(self):
1881 1907 self.plugin_manager = PluginManager(config=self.config)
1882 1908
1883 1909 #-------------------------------------------------------------------------
1884 1910 # Things related to payloads
1885 1911 #-------------------------------------------------------------------------
1886 1912
1887 1913 def init_payload(self):
1888 1914 self.payload_manager = PayloadManager(config=self.config)
1889 1915
1890 1916 #-------------------------------------------------------------------------
1891 1917 # Things related to the prefilter
1892 1918 #-------------------------------------------------------------------------
1893 1919
1894 1920 def init_prefilter(self):
1895 1921 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1896 1922 # Ultimately this will be refactored in the new interpreter code, but
1897 1923 # for now, we should expose the main prefilter method (there's legacy
1898 1924 # code out there that may rely on this).
1899 1925 self.prefilter = self.prefilter_manager.prefilter_lines
1900 1926
1901 1927
1902 1928 def auto_rewrite_input(self, cmd):
1903 1929 """Print to the screen the rewritten form of the user's command.
1904 1930
1905 1931 This shows visual feedback by rewriting input lines that cause
1906 1932 automatic calling to kick in, like::
1907 1933
1908 1934 /f x
1909 1935
1910 1936 into::
1911 1937
1912 1938 ------> f(x)
1913 1939
1914 1940 after the user's input prompt. This helps the user understand that the
1915 1941 input line was transformed automatically by IPython.
1916 1942 """
1917 1943 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1918 1944
1919 1945 try:
1920 1946 # plain ascii works better w/ pyreadline, on some machines, so
1921 1947 # we use it and only print uncolored rewrite if we have unicode
1922 1948 rw = str(rw)
1923 1949 print >> IPython.utils.io.Term.cout, rw
1924 1950 except UnicodeEncodeError:
1925 1951 print "------> " + cmd
1926 1952
1927 1953 #-------------------------------------------------------------------------
1928 1954 # Things related to extracting values/expressions from kernel and user_ns
1929 1955 #-------------------------------------------------------------------------
1930 1956
1931 1957 def _simple_error(self):
1932 1958 etype, value = sys.exc_info()[:2]
1933 1959 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1934 1960
1935 1961 def get_user_variables(self, names):
1936 1962 """Get a list of variable names from the user's namespace.
1937 1963
1938 1964 The return value is a dict with the repr() of each value.
1939 1965 """
1940 1966 out = {}
1941 1967 user_ns = self.user_ns
1942 1968 for varname in names:
1943 1969 try:
1944 1970 value = repr(user_ns[varname])
1945 1971 except:
1946 1972 value = self._simple_error()
1947 1973 out[varname] = value
1948 1974 return out
1949 1975
1950 1976 def eval_expressions(self, expressions):
1951 1977 """Evaluate a dict of expressions in the user's namespace.
1952 1978
1953 1979 The return value is a dict with the repr() of each value.
1954 1980 """
1955 1981 out = {}
1956 1982 user_ns = self.user_ns
1957 1983 global_ns = self.user_global_ns
1958 1984 for key, expr in expressions.iteritems():
1959 1985 try:
1960 1986 value = repr(eval(expr, global_ns, user_ns))
1961 1987 except:
1962 1988 value = self._simple_error()
1963 1989 out[key] = value
1964 1990 return out
1965 1991
1966 1992 #-------------------------------------------------------------------------
1967 1993 # Things related to the running of code
1968 1994 #-------------------------------------------------------------------------
1969 1995
1970 1996 def ex(self, cmd):
1971 1997 """Execute a normal python statement in user namespace."""
1972 1998 with nested(self.builtin_trap,):
1973 1999 exec cmd in self.user_global_ns, self.user_ns
1974 2000
1975 2001 def ev(self, expr):
1976 2002 """Evaluate python expression expr in user namespace.
1977 2003
1978 2004 Returns the result of evaluation
1979 2005 """
1980 2006 with nested(self.builtin_trap,):
1981 2007 return eval(expr, self.user_global_ns, self.user_ns)
1982 2008
1983 2009 def safe_execfile(self, fname, *where, **kw):
1984 2010 """A safe version of the builtin execfile().
1985 2011
1986 2012 This version will never throw an exception, but instead print
1987 2013 helpful error messages to the screen. This only works on pure
1988 2014 Python files with the .py extension.
1989 2015
1990 2016 Parameters
1991 2017 ----------
1992 2018 fname : string
1993 2019 The name of the file to be executed.
1994 2020 where : tuple
1995 2021 One or two namespaces, passed to execfile() as (globals,locals).
1996 2022 If only one is given, it is passed as both.
1997 2023 exit_ignore : bool (False)
1998 2024 If True, then silence SystemExit for non-zero status (it is always
1999 2025 silenced for zero status, as it is so common).
2000 2026 """
2001 2027 kw.setdefault('exit_ignore', False)
2002 2028
2003 2029 fname = os.path.abspath(os.path.expanduser(fname))
2004 2030
2005 2031 # Make sure we have a .py file
2006 2032 if not fname.endswith('.py'):
2007 2033 warn('File must end with .py to be run using execfile: <%s>' % fname)
2008 2034
2009 2035 # Make sure we can open the file
2010 2036 try:
2011 2037 with open(fname) as thefile:
2012 2038 pass
2013 2039 except:
2014 2040 warn('Could not open file <%s> for safe execution.' % fname)
2015 2041 return
2016 2042
2017 2043 # Find things also in current directory. This is needed to mimic the
2018 2044 # behavior of running a script from the system command line, where
2019 2045 # Python inserts the script's directory into sys.path
2020 2046 dname = os.path.dirname(fname)
2021 2047
2022 2048 with prepended_to_syspath(dname):
2023 2049 try:
2024 2050 execfile(fname,*where)
2025 2051 except SystemExit, status:
2026 2052 # If the call was made with 0 or None exit status (sys.exit(0)
2027 2053 # or sys.exit() ), don't bother showing a traceback, as both of
2028 2054 # these are considered normal by the OS:
2029 2055 # > python -c'import sys;sys.exit(0)'; echo $?
2030 2056 # 0
2031 2057 # > python -c'import sys;sys.exit()'; echo $?
2032 2058 # 0
2033 2059 # For other exit status, we show the exception unless
2034 2060 # explicitly silenced, but only in short form.
2035 2061 if status.code not in (0, None) and not kw['exit_ignore']:
2036 2062 self.showtraceback(exception_only=True)
2037 2063 except:
2038 2064 self.showtraceback()
2039 2065
2040 2066 def safe_execfile_ipy(self, fname):
2041 2067 """Like safe_execfile, but for .ipy files with IPython syntax.
2042 2068
2043 2069 Parameters
2044 2070 ----------
2045 2071 fname : str
2046 2072 The name of the file to execute. The filename must have a
2047 2073 .ipy extension.
2048 2074 """
2049 2075 fname = os.path.abspath(os.path.expanduser(fname))
2050 2076
2051 2077 # Make sure we have a .py file
2052 2078 if not fname.endswith('.ipy'):
2053 2079 warn('File must end with .py to be run using execfile: <%s>' % fname)
2054 2080
2055 2081 # Make sure we can open the file
2056 2082 try:
2057 2083 with open(fname) as thefile:
2058 2084 pass
2059 2085 except:
2060 2086 warn('Could not open file <%s> for safe execution.' % fname)
2061 2087 return
2062 2088
2063 2089 # Find things also in current directory. This is needed to mimic the
2064 2090 # behavior of running a script from the system command line, where
2065 2091 # Python inserts the script's directory into sys.path
2066 2092 dname = os.path.dirname(fname)
2067 2093
2068 2094 with prepended_to_syspath(dname):
2069 2095 try:
2070 2096 with open(fname) as thefile:
2071 2097 script = thefile.read()
2072 2098 # self.runlines currently captures all exceptions
2073 2099 # raise in user code. It would be nice if there were
2074 2100 # versions of runlines, execfile that did raise, so
2075 2101 # we could catch the errors.
2076 2102 self.runlines(script, clean=True)
2077 2103 except:
2078 2104 self.showtraceback()
2079 2105 warn('Unknown failure executing file: <%s>' % fname)
2080 2106
2081 2107 def run_cell(self, cell):
2082 2108 """Run the contents of an entire multiline 'cell' of code.
2083 2109
2084 2110 The cell is split into separate blocks which can be executed
2085 2111 individually. Then, based on how many blocks there are, they are
2086 2112 executed as follows:
2087 2113
2088 2114 - A single block: 'single' mode.
2089 2115
2090 2116 If there's more than one block, it depends:
2091 2117
2092 2118 - if the last one is a single line long, run all but the last in
2093 2119 'exec' mode and the very last one in 'single' mode. This makes it
2094 2120 easy to type simple expressions at the end to see computed values.
2095 2121 - otherwise (last one is also multiline), run all in 'exec' mode
2096 2122
2097 2123 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2098 2124 results are displayed and output prompts are computed. In 'exec' mode,
2099 2125 no results are displayed unless :func:`print` is called explicitly;
2100 2126 this mode is more akin to running a script.
2101 2127
2102 2128 Parameters
2103 2129 ----------
2104 2130 cell : str
2105 2131 A single or multiline string.
2106 2132 """
2107 2133 # We need to break up the input into executable blocks that can be run
2108 2134 # in 'single' mode, to provide comfortable user behavior.
2109 2135 blocks = self.input_splitter.split_blocks(cell)
2110 2136
2111 2137 if not blocks:
2112 2138 return
2113 2139
2114 2140 # Single-block input should behave like an interactive prompt
2115 2141 if len(blocks) == 1:
2116 2142 self.runlines(blocks[0])
2117 2143 return
2118 2144
2119 2145 # In multi-block input, if the last block is a simple (one-two lines)
2120 2146 # expression, run it in single mode so it produces output. Otherwise
2121 2147 # just feed the whole thing to runcode.
2122 2148 # This seems like a reasonable usability design.
2123 2149 last = blocks[-1]
2124 2150
2125 2151 # Note: below, whenever we call runcode, we must sync history
2126 2152 # ourselves, because runcode is NOT meant to manage history at all.
2127 2153 if len(last.splitlines()) < 2:
2128 2154 # Get the main body to run as a cell
2129 2155 body = ''.join(blocks[:-1])
2130 2156 self.input_hist.append(body)
2131 2157 self.input_hist_raw.append(body)
2132 2158 self.runcode(body, post_execute=False)
2133 2159 # And the last expression via runlines so it produces output
2134 2160 self.runlines(last)
2135 2161 else:
2136 2162 # Run the whole cell as one entity
2137 2163 self.input_hist.append(cell)
2138 2164 self.input_hist_raw.append(cell)
2139 2165 self.runcode(cell)
2140 2166
2141 2167 def runlines(self, lines, clean=False):
2142 2168 """Run a string of one or more lines of source.
2143 2169
2144 2170 This method is capable of running a string containing multiple source
2145 2171 lines, as if they had been entered at the IPython prompt. Since it
2146 2172 exposes IPython's processing machinery, the given strings can contain
2147 2173 magic calls (%magic), special shell access (!cmd), etc.
2148 2174 """
2149 2175
2150 2176 if isinstance(lines, (list, tuple)):
2151 2177 lines = '\n'.join(lines)
2152 2178
2153 2179 if clean:
2154 2180 lines = self._cleanup_ipy_script(lines)
2155 2181
2156 2182 # We must start with a clean buffer, in case this is run from an
2157 2183 # interactive IPython session (via a magic, for example).
2158 2184 self.resetbuffer()
2159 2185 lines = lines.splitlines()
2160 2186 more = 0
2161 2187 with nested(self.builtin_trap, self.display_trap):
2162 2188 for line in lines:
2163 2189 # skip blank lines so we don't mess up the prompt counter, but
2164 2190 # do NOT skip even a blank line if we are in a code block (more
2165 2191 # is true)
2166 2192
2167 2193 if line or more:
2168 2194 # push to raw history, so hist line numbers stay in sync
2169 2195 self.input_hist_raw.append(line + '\n')
2170 2196 prefiltered = self.prefilter_manager.prefilter_lines(line,
2171 2197 more)
2172 2198 more = self.push_line(prefiltered)
2173 2199 # IPython's runsource returns None if there was an error
2174 2200 # compiling the code. This allows us to stop processing
2175 2201 # right away, so the user gets the error message at the
2176 2202 # right place.
2177 2203 if more is None:
2178 2204 break
2179 2205 else:
2180 2206 self.input_hist_raw.append("\n")
2181 2207 # final newline in case the input didn't have it, so that the code
2182 2208 # actually does get executed
2183 2209 if more:
2184 2210 self.push_line('\n')
2185 2211
2186 2212 def runsource(self, source, filename='<input>', symbol='single'):
2187 2213 """Compile and run some source in the interpreter.
2188 2214
2189 2215 Arguments are as for compile_command().
2190 2216
2191 2217 One several things can happen:
2192 2218
2193 2219 1) The input is incorrect; compile_command() raised an
2194 2220 exception (SyntaxError or OverflowError). A syntax traceback
2195 2221 will be printed by calling the showsyntaxerror() method.
2196 2222
2197 2223 2) The input is incomplete, and more input is required;
2198 2224 compile_command() returned None. Nothing happens.
2199 2225
2200 2226 3) The input is complete; compile_command() returned a code
2201 2227 object. The code is executed by calling self.runcode() (which
2202 2228 also handles run-time exceptions, except for SystemExit).
2203 2229
2204 2230 The return value is:
2205 2231
2206 2232 - True in case 2
2207 2233
2208 2234 - False in the other cases, unless an exception is raised, where
2209 2235 None is returned instead. This can be used by external callers to
2210 2236 know whether to continue feeding input or not.
2211 2237
2212 2238 The return value can be used to decide whether to use sys.ps1 or
2213 2239 sys.ps2 to prompt the next line."""
2214 2240
2215 2241 # if the source code has leading blanks, add 'if 1:\n' to it
2216 2242 # this allows execution of indented pasted code. It is tempting
2217 2243 # to add '\n' at the end of source to run commands like ' a=1'
2218 2244 # directly, but this fails for more complicated scenarios
2219 2245 source=source.encode(self.stdin_encoding)
2220 2246 if source[:1] in [' ', '\t']:
2221 2247 source = 'if 1:\n%s' % source
2222 2248
2223 2249 try:
2224 2250 code = self.compile(source,filename,symbol)
2225 2251 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2226 2252 # Case 1
2227 2253 self.showsyntaxerror(filename)
2228 2254 return None
2229 2255
2230 2256 if code is None:
2231 2257 # Case 2
2232 2258 return True
2233 2259
2234 2260 # Case 3
2235 2261 # We store the code object so that threaded shells and
2236 2262 # custom exception handlers can access all this info if needed.
2237 2263 # The source corresponding to this can be obtained from the
2238 2264 # buffer attribute as '\n'.join(self.buffer).
2239 2265 self.code_to_run = code
2240 2266 # now actually execute the code object
2241 2267 if self.runcode(code) == 0:
2242 2268 return False
2243 2269 else:
2244 2270 return None
2245 2271
2246 2272 def runcode(self, code_obj, post_execute=True):
2247 2273 """Execute a code object.
2248 2274
2249 2275 When an exception occurs, self.showtraceback() is called to display a
2250 2276 traceback.
2251 2277
2252 2278 Return value: a flag indicating whether the code to be run completed
2253 2279 successfully:
2254 2280
2255 2281 - 0: successful execution.
2256 2282 - 1: an error occurred.
2257 2283 """
2258 2284
2259 2285 # Set our own excepthook in case the user code tries to call it
2260 2286 # directly, so that the IPython crash handler doesn't get triggered
2261 2287 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2262 2288
2263 2289 # we save the original sys.excepthook in the instance, in case config
2264 2290 # code (such as magics) needs access to it.
2265 2291 self.sys_excepthook = old_excepthook
2266 2292 outflag = 1 # happens in more places, so it's easier as default
2267 2293 try:
2268 2294 try:
2269 2295 self.hooks.pre_runcode_hook()
2270 2296 #rprint('Running code') # dbg
2271 2297 exec code_obj in self.user_global_ns, self.user_ns
2272 2298 finally:
2273 2299 # Reset our crash handler in place
2274 2300 sys.excepthook = old_excepthook
2275 2301 except SystemExit:
2276 2302 self.resetbuffer()
2277 2303 self.showtraceback(exception_only=True)
2278 2304 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2279 2305 except self.custom_exceptions:
2280 2306 etype,value,tb = sys.exc_info()
2281 2307 self.CustomTB(etype,value,tb)
2282 2308 except:
2283 2309 self.showtraceback()
2284 2310 else:
2285 2311 outflag = 0
2286 2312 if softspace(sys.stdout, 0):
2287 2313 print
2288 2314
2289 2315 # Execute any registered post-execution functions. Here, any errors
2290 2316 # are reported only minimally and just on the terminal, because the
2291 2317 # main exception channel may be occupied with a user traceback.
2292 2318 # FIXME: we need to think this mechanism a little more carefully.
2293 2319 if post_execute:
2294 2320 for func in self._post_execute:
2295 2321 try:
2296 2322 func()
2297 2323 except:
2298 2324 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2299 2325 func
2300 2326 print >> io.Term.cout, head
2301 2327 print >> io.Term.cout, self._simple_error()
2302 2328 print >> io.Term.cout, 'Removing from post_execute'
2303 2329 self._post_execute.remove(func)
2304 2330
2305 2331 # Flush out code object which has been run (and source)
2306 2332 self.code_to_run = None
2307 2333 return outflag
2308 2334
2309 2335 def push_line(self, line):
2310 2336 """Push a line to the interpreter.
2311 2337
2312 2338 The line should not have a trailing newline; it may have
2313 2339 internal newlines. The line is appended to a buffer and the
2314 2340 interpreter's runsource() method is called with the
2315 2341 concatenated contents of the buffer as source. If this
2316 2342 indicates that the command was executed or invalid, the buffer
2317 2343 is reset; otherwise, the command is incomplete, and the buffer
2318 2344 is left as it was after the line was appended. The return
2319 2345 value is 1 if more input is required, 0 if the line was dealt
2320 2346 with in some way (this is the same as runsource()).
2321 2347 """
2322 2348
2323 2349 # autoindent management should be done here, and not in the
2324 2350 # interactive loop, since that one is only seen by keyboard input. We
2325 2351 # need this done correctly even for code run via runlines (which uses
2326 2352 # push).
2327 2353
2328 2354 #print 'push line: <%s>' % line # dbg
2329 2355 for subline in line.splitlines():
2330 2356 self._autoindent_update(subline)
2331 2357 self.buffer.append(line)
2332 2358 more = self.runsource('\n'.join(self.buffer), self.filename)
2333 2359 if not more:
2334 2360 self.resetbuffer()
2335 2361 return more
2336 2362
2337 2363 def resetbuffer(self):
2338 2364 """Reset the input buffer."""
2339 2365 self.buffer[:] = []
2340 2366
2341 2367 def _is_secondary_block_start(self, s):
2342 2368 if not s.endswith(':'):
2343 2369 return False
2344 2370 if (s.startswith('elif') or
2345 2371 s.startswith('else') or
2346 2372 s.startswith('except') or
2347 2373 s.startswith('finally')):
2348 2374 return True
2349 2375
2350 2376 def _cleanup_ipy_script(self, script):
2351 2377 """Make a script safe for self.runlines()
2352 2378
2353 2379 Currently, IPython is lines based, with blocks being detected by
2354 2380 empty lines. This is a problem for block based scripts that may
2355 2381 not have empty lines after blocks. This script adds those empty
2356 2382 lines to make scripts safe for running in the current line based
2357 2383 IPython.
2358 2384 """
2359 2385 res = []
2360 2386 lines = script.splitlines()
2361 2387 level = 0
2362 2388
2363 2389 for l in lines:
2364 2390 lstripped = l.lstrip()
2365 2391 stripped = l.strip()
2366 2392 if not stripped:
2367 2393 continue
2368 2394 newlevel = len(l) - len(lstripped)
2369 2395 if level > 0 and newlevel == 0 and \
2370 2396 not self._is_secondary_block_start(stripped):
2371 2397 # add empty line
2372 2398 res.append('')
2373 2399 res.append(l)
2374 2400 level = newlevel
2375 2401
2376 2402 return '\n'.join(res) + '\n'
2377 2403
2378 2404 def _autoindent_update(self,line):
2379 2405 """Keep track of the indent level."""
2380 2406
2381 2407 #debugx('line')
2382 2408 #debugx('self.indent_current_nsp')
2383 2409 if self.autoindent:
2384 2410 if line:
2385 2411 inisp = num_ini_spaces(line)
2386 2412 if inisp < self.indent_current_nsp:
2387 2413 self.indent_current_nsp = inisp
2388 2414
2389 2415 if line[-1] == ':':
2390 2416 self.indent_current_nsp += 4
2391 2417 elif dedent_re.match(line):
2392 2418 self.indent_current_nsp -= 4
2393 2419 else:
2394 2420 self.indent_current_nsp = 0
2395 2421
2396 2422 #-------------------------------------------------------------------------
2397 2423 # Things related to GUI support and pylab
2398 2424 #-------------------------------------------------------------------------
2399 2425
2400 2426 def enable_pylab(self, gui=None):
2401 2427 raise NotImplementedError('Implement enable_pylab in a subclass')
2402 2428
2403 2429 #-------------------------------------------------------------------------
2404 2430 # Utilities
2405 2431 #-------------------------------------------------------------------------
2406 2432
2407 2433 def var_expand(self,cmd,depth=0):
2408 2434 """Expand python variables in a string.
2409 2435
2410 2436 The depth argument indicates how many frames above the caller should
2411 2437 be walked to look for the local namespace where to expand variables.
2412 2438
2413 2439 The global namespace for expansion is always the user's interactive
2414 2440 namespace.
2415 2441 """
2416 2442
2417 2443 return str(ItplNS(cmd,
2418 2444 self.user_ns, # globals
2419 2445 # Skip our own frame in searching for locals:
2420 2446 sys._getframe(depth+1).f_locals # locals
2421 2447 ))
2422 2448
2423 2449 def mktempfile(self,data=None):
2424 2450 """Make a new tempfile and return its filename.
2425 2451
2426 2452 This makes a call to tempfile.mktemp, but it registers the created
2427 2453 filename internally so ipython cleans it up at exit time.
2428 2454
2429 2455 Optional inputs:
2430 2456
2431 2457 - data(None): if data is given, it gets written out to the temp file
2432 2458 immediately, and the file is closed again."""
2433 2459
2434 2460 filename = tempfile.mktemp('.py','ipython_edit_')
2435 2461 self.tempfiles.append(filename)
2436 2462
2437 2463 if data:
2438 2464 tmp_file = open(filename,'w')
2439 2465 tmp_file.write(data)
2440 2466 tmp_file.close()
2441 2467 return filename
2442 2468
2443 2469 # TODO: This should be removed when Term is refactored.
2444 2470 def write(self,data):
2445 2471 """Write a string to the default output"""
2446 2472 io.Term.cout.write(data)
2447 2473
2448 2474 # TODO: This should be removed when Term is refactored.
2449 2475 def write_err(self,data):
2450 2476 """Write a string to the default error output"""
2451 2477 io.Term.cerr.write(data)
2452 2478
2453 2479 def ask_yes_no(self,prompt,default=True):
2454 2480 if self.quiet:
2455 2481 return True
2456 2482 return ask_yes_no(prompt,default)
2457 2483
2458 2484 def show_usage(self):
2459 2485 """Show a usage message"""
2460 2486 page.page(IPython.core.usage.interactive_usage)
2461 2487
2462 2488 #-------------------------------------------------------------------------
2463 2489 # Things related to IPython exiting
2464 2490 #-------------------------------------------------------------------------
2465 2491 def atexit_operations(self):
2466 2492 """This will be executed at the time of exit.
2467 2493
2468 2494 Cleanup operations and saving of persistent data that is done
2469 2495 unconditionally by IPython should be performed here.
2470 2496
2471 2497 For things that may depend on startup flags or platform specifics (such
2472 2498 as having readline or not), register a separate atexit function in the
2473 2499 code that has the appropriate information, rather than trying to
2474 2500 clutter
2475 2501 """
2476 2502 # Cleanup all tempfiles left around
2477 2503 for tfile in self.tempfiles:
2478 2504 try:
2479 2505 os.unlink(tfile)
2480 2506 except OSError:
2481 2507 pass
2482 2508
2483 2509 # Clear all user namespaces to release all references cleanly.
2484 2510 self.reset()
2485 2511
2486 2512 # Run user hooks
2487 2513 self.hooks.shutdown_hook()
2488 2514
2489 2515 def cleanup(self):
2490 2516 self.restore_sys_module_state()
2491 2517
2492 2518
2493 2519 class InteractiveShellABC(object):
2494 2520 """An abstract base class for InteractiveShell."""
2495 2521 __metaclass__ = abc.ABCMeta
2496 2522
2497 2523 InteractiveShellABC.register(InteractiveShell)
@@ -1,3377 +1,3377 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import os
23 23 import sys
24 24 import shutil
25 25 import re
26 26 import time
27 27 import textwrap
28 28 import types
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 45 # 2.5 compatibility
46 46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48 48
49 49 import IPython
50 50 from IPython.core import debugger, oinspect
51 51 from IPython.core.error import TryNext
52 52 from IPython.core.error import UsageError
53 53 from IPython.core.fakemodule import FakeModule
54 54 from IPython.core.macro import Macro
55 55 from IPython.core import page
56 56 from IPython.core.prefilter import ESC_MAGIC
57 57 from IPython.lib.pylabtools import mpl_runner
58 58 from IPython.external.Itpl import itpl, printpl
59 59 from IPython.testing import decorators as testdec
60 60 from IPython.utils.io import file_read, nlprint
61 61 import IPython.utils.io
62 62 from IPython.utils.path import get_py_filename
63 63 from IPython.utils.process import arg_split, abbrev_cwd
64 64 from IPython.utils.terminal import set_term_title
65 65 from IPython.utils.text import LSString, SList, StringTypes, format_screen
66 66 from IPython.utils.timing import clock, clock2
67 67 from IPython.utils.warn import warn, error
68 68 from IPython.utils.ipstruct import Struct
69 69 import IPython.utils.generics
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Utility functions
73 73 #-----------------------------------------------------------------------------
74 74
75 75 def on_off(tag):
76 76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 77 return ['OFF','ON'][tag]
78 78
79 79 class Bunch: pass
80 80
81 81 def compress_dhist(dh):
82 82 head, tail = dh[:-10], dh[-10:]
83 83
84 84 newhead = []
85 85 done = set()
86 86 for h in head:
87 87 if h in done:
88 88 continue
89 89 newhead.append(h)
90 90 done.add(h)
91 91
92 92 return newhead + tail
93 93
94 94
95 95 #***************************************************************************
96 96 # Main class implementing Magic functionality
97 97
98 98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 99 # on construction of the main InteractiveShell object. Something odd is going
100 100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 101 # eventually this needs to be clarified.
102 102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 104 # make Magic a configurable that InteractiveShell does not subclass.
105 105
106 106 class Magic:
107 107 """Magic functions for InteractiveShell.
108 108
109 109 Shell functions which can be reached as %function_name. All magic
110 110 functions should accept a string, which they can parse for their own
111 111 needs. This can make some functions easier to type, eg `%cd ../`
112 112 vs. `%cd("../")`
113 113
114 114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 115 at the command line, but it is is needed in the definition. """
116 116
117 117 # class globals
118 118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 119 'Automagic is ON, % prefix NOT needed for magic functions.']
120 120
121 121 #......................................................................
122 122 # some utility functions
123 123
124 124 def __init__(self,shell):
125 125
126 126 self.options_table = {}
127 127 if profile is None:
128 128 self.magic_prun = self.profile_missing_notice
129 129 self.shell = shell
130 130
131 131 # namespace for holding state we may need
132 132 self._magic_state = Bunch()
133 133
134 134 def profile_missing_notice(self, *args, **kwargs):
135 135 error("""\
136 136 The profile module could not be found. It has been removed from the standard
137 137 python packages because of its non-free license. To use profiling, install the
138 138 python-profiler package from non-free.""")
139 139
140 140 def default_option(self,fn,optstr):
141 141 """Make an entry in the options_table for fn, with value optstr"""
142 142
143 143 if fn not in self.lsmagic():
144 144 error("%s is not a magic function" % fn)
145 145 self.options_table[fn] = optstr
146 146
147 147 def lsmagic(self):
148 148 """Return a list of currently available magic functions.
149 149
150 150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 151 ['magic_ls','magic_cd',...]"""
152 152
153 153 # FIXME. This needs a cleanup, in the way the magics list is built.
154 154
155 155 # magics in class definition
156 156 class_magic = lambda fn: fn.startswith('magic_') and \
157 157 callable(Magic.__dict__[fn])
158 158 # in instance namespace (run-time user additions)
159 159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 160 callable(self.__dict__[fn])
161 161 # and bound magics by user (so they can access self):
162 162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 163 callable(self.__class__.__dict__[fn])
164 164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 165 filter(inst_magic,self.__dict__.keys()) + \
166 166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 167 out = []
168 168 for fn in set(magics):
169 169 out.append(fn.replace('magic_','',1))
170 170 out.sort()
171 171 return out
172 172
173 173 def extract_input_slices(self,slices,raw=False):
174 174 """Return as a string a set of input history slices.
175 175
176 176 Inputs:
177 177
178 178 - slices: the set of slices is given as a list of strings (like
179 179 ['1','4:8','9'], since this function is for use by magic functions
180 180 which get their arguments as strings.
181 181
182 182 Optional inputs:
183 183
184 184 - raw(False): by default, the processed input is used. If this is
185 185 true, the raw input history is used instead.
186 186
187 187 Note that slices can be called with two notations:
188 188
189 189 N:M -> standard python form, means including items N...(M-1).
190 190
191 191 N-M -> include items N..M (closed endpoint)."""
192 192
193 193 if raw:
194 194 hist = self.shell.input_hist_raw
195 195 else:
196 196 hist = self.shell.input_hist
197 197
198 198 cmds = []
199 199 for chunk in slices:
200 200 if ':' in chunk:
201 201 ini,fin = map(int,chunk.split(':'))
202 202 elif '-' in chunk:
203 203 ini,fin = map(int,chunk.split('-'))
204 204 fin += 1
205 205 else:
206 206 ini = int(chunk)
207 207 fin = ini+1
208 208 cmds.append(hist[ini:fin])
209 209 return cmds
210 210
211 211 def arg_err(self,func):
212 212 """Print docstring if incorrect arguments were passed"""
213 213 print 'Error in arguments:'
214 214 print oinspect.getdoc(func)
215 215
216 216 def format_latex(self,strng):
217 217 """Format a string for latex inclusion."""
218 218
219 219 # Characters that need to be escaped for latex:
220 220 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
221 221 # Magic command names as headers:
222 222 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
223 223 re.MULTILINE)
224 224 # Magic commands
225 225 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
226 226 re.MULTILINE)
227 227 # Paragraph continue
228 228 par_re = re.compile(r'\\$',re.MULTILINE)
229 229
230 230 # The "\n" symbol
231 231 newline_re = re.compile(r'\\n')
232 232
233 233 # Now build the string for output:
234 234 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
235 235 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
236 236 strng)
237 237 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
238 238 strng = par_re.sub(r'\\\\',strng)
239 239 strng = escape_re.sub(r'\\\1',strng)
240 240 strng = newline_re.sub(r'\\textbackslash{}n',strng)
241 241 return strng
242 242
243 243 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
244 244 """Parse options passed to an argument string.
245 245
246 246 The interface is similar to that of getopt(), but it returns back a
247 247 Struct with the options as keys and the stripped argument string still
248 248 as a string.
249 249
250 250 arg_str is quoted as a true sys.argv vector by using shlex.split.
251 251 This allows us to easily expand variables, glob files, quote
252 252 arguments, etc.
253 253
254 254 Options:
255 255 -mode: default 'string'. If given as 'list', the argument string is
256 256 returned as a list (split on whitespace) instead of a string.
257 257
258 258 -list_all: put all option values in lists. Normally only options
259 259 appearing more than once are put in a list.
260 260
261 261 -posix (True): whether to split the input line in POSIX mode or not,
262 262 as per the conventions outlined in the shlex module from the
263 263 standard library."""
264 264
265 265 # inject default options at the beginning of the input line
266 266 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
267 267 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
268 268
269 269 mode = kw.get('mode','string')
270 270 if mode not in ['string','list']:
271 271 raise ValueError,'incorrect mode given: %s' % mode
272 272 # Get options
273 273 list_all = kw.get('list_all',0)
274 274 posix = kw.get('posix', os.name == 'posix')
275 275
276 276 # Check if we have more than one argument to warrant extra processing:
277 277 odict = {} # Dictionary with options
278 278 args = arg_str.split()
279 279 if len(args) >= 1:
280 280 # If the list of inputs only has 0 or 1 thing in it, there's no
281 281 # need to look for options
282 282 argv = arg_split(arg_str,posix)
283 283 # Do regular option processing
284 284 try:
285 285 opts,args = getopt(argv,opt_str,*long_opts)
286 286 except GetoptError,e:
287 287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
288 288 " ".join(long_opts)))
289 289 for o,a in opts:
290 290 if o.startswith('--'):
291 291 o = o[2:]
292 292 else:
293 293 o = o[1:]
294 294 try:
295 295 odict[o].append(a)
296 296 except AttributeError:
297 297 odict[o] = [odict[o],a]
298 298 except KeyError:
299 299 if list_all:
300 300 odict[o] = [a]
301 301 else:
302 302 odict[o] = a
303 303
304 304 # Prepare opts,args for return
305 305 opts = Struct(odict)
306 306 if mode == 'string':
307 307 args = ' '.join(args)
308 308
309 309 return opts,args
310 310
311 311 #......................................................................
312 312 # And now the actual magic functions
313 313
314 314 # Functions for IPython shell work (vars,funcs, config, etc)
315 315 def magic_lsmagic(self, parameter_s = ''):
316 316 """List currently available magic functions."""
317 317 mesc = ESC_MAGIC
318 318 print 'Available magic functions:\n'+mesc+\
319 319 (' '+mesc).join(self.lsmagic())
320 320 print '\n' + Magic.auto_status[self.shell.automagic]
321 321 return None
322 322
323 323 def magic_magic(self, parameter_s = ''):
324 324 """Print information about the magic function system.
325 325
326 326 Supported formats: -latex, -brief, -rest
327 327 """
328 328
329 329 mode = ''
330 330 try:
331 331 if parameter_s.split()[0] == '-latex':
332 332 mode = 'latex'
333 333 if parameter_s.split()[0] == '-brief':
334 334 mode = 'brief'
335 335 if parameter_s.split()[0] == '-rest':
336 336 mode = 'rest'
337 337 rest_docs = []
338 338 except:
339 339 pass
340 340
341 341 magic_docs = []
342 342 for fname in self.lsmagic():
343 343 mname = 'magic_' + fname
344 344 for space in (Magic,self,self.__class__):
345 345 try:
346 346 fn = space.__dict__[mname]
347 347 except KeyError:
348 348 pass
349 349 else:
350 350 break
351 351 if mode == 'brief':
352 352 # only first line
353 353 if fn.__doc__:
354 354 fndoc = fn.__doc__.split('\n',1)[0]
355 355 else:
356 356 fndoc = 'No documentation'
357 357 else:
358 358 if fn.__doc__:
359 359 fndoc = fn.__doc__.rstrip()
360 360 else:
361 361 fndoc = 'No documentation'
362 362
363 363
364 364 if mode == 'rest':
365 365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
366 366 fname,fndoc))
367 367
368 368 else:
369 369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
370 370 fname,fndoc))
371 371
372 372 magic_docs = ''.join(magic_docs)
373 373
374 374 if mode == 'rest':
375 375 return "".join(rest_docs)
376 376
377 377 if mode == 'latex':
378 378 print self.format_latex(magic_docs)
379 379 return
380 380 else:
381 381 magic_docs = format_screen(magic_docs)
382 382 if mode == 'brief':
383 383 return magic_docs
384 384
385 385 outmsg = """
386 386 IPython's 'magic' functions
387 387 ===========================
388 388
389 389 The magic function system provides a series of functions which allow you to
390 390 control the behavior of IPython itself, plus a lot of system-type
391 391 features. All these functions are prefixed with a % character, but parameters
392 392 are given without parentheses or quotes.
393 393
394 394 NOTE: If you have 'automagic' enabled (via the command line option or with the
395 395 %automagic function), you don't need to type in the % explicitly. By default,
396 396 IPython ships with automagic on, so you should only rarely need the % escape.
397 397
398 398 Example: typing '%cd mydir' (without the quotes) changes you working directory
399 399 to 'mydir', if it exists.
400 400
401 401 You can define your own magic functions to extend the system. See the supplied
402 402 ipythonrc and example-magic.py files for details (in your ipython
403 403 configuration directory, typically $HOME/.ipython/).
404 404
405 405 You can also define your own aliased names for magic functions. In your
406 406 ipythonrc file, placing a line like:
407 407
408 408 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
409 409
410 410 will define %pf as a new name for %profile.
411 411
412 412 You can also call magics in code using the magic() function, which IPython
413 413 automatically adds to the builtin namespace. Type 'magic?' for details.
414 414
415 415 For a list of the available magic functions, use %lsmagic. For a description
416 416 of any of them, type %magic_name?, e.g. '%cd?'.
417 417
418 418 Currently the magic system has the following functions:\n"""
419 419
420 420 mesc = ESC_MAGIC
421 421 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
422 422 "\n\n%s%s\n\n%s" % (outmsg,
423 423 magic_docs,mesc,mesc,
424 424 (' '+mesc).join(self.lsmagic()),
425 425 Magic.auto_status[self.shell.automagic] ) )
426 426 page.page(outmsg)
427 427
428 428 def magic_automagic(self, parameter_s = ''):
429 429 """Make magic functions callable without having to type the initial %.
430 430
431 431 Without argumentsl toggles on/off (when off, you must call it as
432 432 %automagic, of course). With arguments it sets the value, and you can
433 433 use any of (case insensitive):
434 434
435 435 - on,1,True: to activate
436 436
437 437 - off,0,False: to deactivate.
438 438
439 439 Note that magic functions have lowest priority, so if there's a
440 440 variable whose name collides with that of a magic fn, automagic won't
441 441 work for that function (you get the variable instead). However, if you
442 442 delete the variable (del var), the previously shadowed magic function
443 443 becomes visible to automagic again."""
444 444
445 445 arg = parameter_s.lower()
446 446 if parameter_s in ('on','1','true'):
447 447 self.shell.automagic = True
448 448 elif parameter_s in ('off','0','false'):
449 449 self.shell.automagic = False
450 450 else:
451 451 self.shell.automagic = not self.shell.automagic
452 452 print '\n' + Magic.auto_status[self.shell.automagic]
453 453
454 454 @testdec.skip_doctest
455 455 def magic_autocall(self, parameter_s = ''):
456 456 """Make functions callable without having to type parentheses.
457 457
458 458 Usage:
459 459
460 460 %autocall [mode]
461 461
462 462 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
463 463 value is toggled on and off (remembering the previous state).
464 464
465 465 In more detail, these values mean:
466 466
467 467 0 -> fully disabled
468 468
469 469 1 -> active, but do not apply if there are no arguments on the line.
470 470
471 471 In this mode, you get:
472 472
473 473 In [1]: callable
474 474 Out[1]: <built-in function callable>
475 475
476 476 In [2]: callable 'hello'
477 477 ------> callable('hello')
478 478 Out[2]: False
479 479
480 480 2 -> Active always. Even if no arguments are present, the callable
481 481 object is called:
482 482
483 483 In [2]: float
484 484 ------> float()
485 485 Out[2]: 0.0
486 486
487 487 Note that even with autocall off, you can still use '/' at the start of
488 488 a line to treat the first argument on the command line as a function
489 489 and add parentheses to it:
490 490
491 491 In [8]: /str 43
492 492 ------> str(43)
493 493 Out[8]: '43'
494 494
495 495 # all-random (note for auto-testing)
496 496 """
497 497
498 498 if parameter_s:
499 499 arg = int(parameter_s)
500 500 else:
501 501 arg = 'toggle'
502 502
503 503 if not arg in (0,1,2,'toggle'):
504 504 error('Valid modes: (0->Off, 1->Smart, 2->Full')
505 505 return
506 506
507 507 if arg in (0,1,2):
508 508 self.shell.autocall = arg
509 509 else: # toggle
510 510 if self.shell.autocall:
511 511 self._magic_state.autocall_save = self.shell.autocall
512 512 self.shell.autocall = 0
513 513 else:
514 514 try:
515 515 self.shell.autocall = self._magic_state.autocall_save
516 516 except AttributeError:
517 517 self.shell.autocall = self._magic_state.autocall_save = 1
518 518
519 519 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
520 520
521 521
522 522 def magic_page(self, parameter_s=''):
523 523 """Pretty print the object and display it through a pager.
524 524
525 525 %page [options] OBJECT
526 526
527 527 If no object is given, use _ (last output).
528 528
529 529 Options:
530 530
531 531 -r: page str(object), don't pretty-print it."""
532 532
533 533 # After a function contributed by Olivier Aubert, slightly modified.
534 534
535 535 # Process options/args
536 536 opts,args = self.parse_options(parameter_s,'r')
537 537 raw = 'r' in opts
538 538
539 539 oname = args and args or '_'
540 540 info = self._ofind(oname)
541 541 if info['found']:
542 542 txt = (raw and str or pformat)( info['obj'] )
543 543 page.page(txt)
544 544 else:
545 545 print 'Object `%s` not found' % oname
546 546
547 547 def magic_profile(self, parameter_s=''):
548 548 """Print your currently active IPython profile."""
549 549 if self.shell.profile:
550 550 printpl('Current IPython profile: $self.shell.profile.')
551 551 else:
552 552 print 'No profile active.'
553 553
554 554 def magic_pinfo(self, parameter_s='', namespaces=None):
555 555 """Provide detailed information about an object.
556 556
557 557 '%pinfo object' is just a synonym for object? or ?object."""
558 558
559 559 #print 'pinfo par: <%s>' % parameter_s # dbg
560 560
561 561
562 562 # detail_level: 0 -> obj? , 1 -> obj??
563 563 detail_level = 0
564 564 # We need to detect if we got called as 'pinfo pinfo foo', which can
565 565 # happen if the user types 'pinfo foo?' at the cmd line.
566 566 pinfo,qmark1,oname,qmark2 = \
567 567 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
568 568 if pinfo or qmark1 or qmark2:
569 569 detail_level = 1
570 570 if "*" in oname:
571 571 self.magic_psearch(oname)
572 572 else:
573 573 self.shell._inspect('pinfo', oname, detail_level=detail_level,
574 574 namespaces=namespaces)
575 575
576 576 def magic_pinfo2(self, parameter_s='', namespaces=None):
577 577 """Provide extra detailed information about an object.
578 578
579 579 '%pinfo2 object' is just a synonym for object?? or ??object."""
580 580 print 'pinfo2 par: <%s>' % parameter_s # dbg
581 581 self.shell._inspect('pinfo', parameter_s, detail_level=1,
582 582 namespaces=namespaces)
583 583
584 584 def magic_pdef(self, parameter_s='', namespaces=None):
585 585 """Print the definition header for any callable object.
586 586
587 587 If the object is a class, print the constructor information."""
588 588 self._inspect('pdef',parameter_s, namespaces)
589 589
590 590 def magic_pdoc(self, parameter_s='', namespaces=None):
591 591 """Print the docstring for an object.
592 592
593 593 If the given object is a class, it will print both the class and the
594 594 constructor docstrings."""
595 595 self._inspect('pdoc',parameter_s, namespaces)
596 596
597 597 def magic_psource(self, parameter_s='', namespaces=None):
598 598 """Print (or run through pager) the source code for an object."""
599 599 self._inspect('psource',parameter_s, namespaces)
600 600
601 601 def magic_pfile(self, parameter_s=''):
602 602 """Print (or run through pager) the file where an object is defined.
603 603
604 604 The file opens at the line where the object definition begins. IPython
605 605 will honor the environment variable PAGER if set, and otherwise will
606 606 do its best to print the file in a convenient form.
607 607
608 608 If the given argument is not an object currently defined, IPython will
609 609 try to interpret it as a filename (automatically adding a .py extension
610 610 if needed). You can thus use %pfile as a syntax highlighting code
611 611 viewer."""
612 612
613 613 # first interpret argument as an object name
614 614 out = self._inspect('pfile',parameter_s)
615 615 # if not, try the input as a filename
616 616 if out == 'not found':
617 617 try:
618 618 filename = get_py_filename(parameter_s)
619 619 except IOError,msg:
620 620 print msg
621 621 return
622 622 page.page(self.shell.inspector.format(file(filename).read()))
623 623
624 624 def magic_psearch(self, parameter_s=''):
625 625 """Search for object in namespaces by wildcard.
626 626
627 627 %psearch [options] PATTERN [OBJECT TYPE]
628 628
629 629 Note: ? can be used as a synonym for %psearch, at the beginning or at
630 630 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
631 631 rest of the command line must be unchanged (options come first), so
632 632 for example the following forms are equivalent
633 633
634 634 %psearch -i a* function
635 635 -i a* function?
636 636 ?-i a* function
637 637
638 638 Arguments:
639 639
640 640 PATTERN
641 641
642 642 where PATTERN is a string containing * as a wildcard similar to its
643 643 use in a shell. The pattern is matched in all namespaces on the
644 644 search path. By default objects starting with a single _ are not
645 645 matched, many IPython generated objects have a single
646 646 underscore. The default is case insensitive matching. Matching is
647 647 also done on the attributes of objects and not only on the objects
648 648 in a module.
649 649
650 650 [OBJECT TYPE]
651 651
652 652 Is the name of a python type from the types module. The name is
653 653 given in lowercase without the ending type, ex. StringType is
654 654 written string. By adding a type here only objects matching the
655 655 given type are matched. Using all here makes the pattern match all
656 656 types (this is the default).
657 657
658 658 Options:
659 659
660 660 -a: makes the pattern match even objects whose names start with a
661 661 single underscore. These names are normally ommitted from the
662 662 search.
663 663
664 664 -i/-c: make the pattern case insensitive/sensitive. If neither of
665 665 these options is given, the default is read from your ipythonrc
666 666 file. The option name which sets this value is
667 667 'wildcards_case_sensitive'. If this option is not specified in your
668 668 ipythonrc file, IPython's internal default is to do a case sensitive
669 669 search.
670 670
671 671 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
672 672 specifiy can be searched in any of the following namespaces:
673 673 'builtin', 'user', 'user_global','internal', 'alias', where
674 674 'builtin' and 'user' are the search defaults. Note that you should
675 675 not use quotes when specifying namespaces.
676 676
677 677 'Builtin' contains the python module builtin, 'user' contains all
678 678 user data, 'alias' only contain the shell aliases and no python
679 679 objects, 'internal' contains objects used by IPython. The
680 680 'user_global' namespace is only used by embedded IPython instances,
681 681 and it contains module-level globals. You can add namespaces to the
682 682 search with -s or exclude them with -e (these options can be given
683 683 more than once).
684 684
685 685 Examples:
686 686
687 687 %psearch a* -> objects beginning with an a
688 688 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
689 689 %psearch a* function -> all functions beginning with an a
690 690 %psearch re.e* -> objects beginning with an e in module re
691 691 %psearch r*.e* -> objects that start with e in modules starting in r
692 692 %psearch r*.* string -> all strings in modules beginning with r
693 693
694 694 Case sensitve search:
695 695
696 696 %psearch -c a* list all object beginning with lower case a
697 697
698 698 Show objects beginning with a single _:
699 699
700 700 %psearch -a _* list objects beginning with a single underscore"""
701 701 try:
702 702 parameter_s = parameter_s.encode('ascii')
703 703 except UnicodeEncodeError:
704 704 print 'Python identifiers can only contain ascii characters.'
705 705 return
706 706
707 707 # default namespaces to be searched
708 708 def_search = ['user','builtin']
709 709
710 710 # Process options/args
711 711 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
712 712 opt = opts.get
713 713 shell = self.shell
714 714 psearch = shell.inspector.psearch
715 715
716 716 # select case options
717 717 if opts.has_key('i'):
718 718 ignore_case = True
719 719 elif opts.has_key('c'):
720 720 ignore_case = False
721 721 else:
722 722 ignore_case = not shell.wildcards_case_sensitive
723 723
724 724 # Build list of namespaces to search from user options
725 725 def_search.extend(opt('s',[]))
726 726 ns_exclude = ns_exclude=opt('e',[])
727 727 ns_search = [nm for nm in def_search if nm not in ns_exclude]
728 728
729 729 # Call the actual search
730 730 try:
731 731 psearch(args,shell.ns_table,ns_search,
732 732 show_all=opt('a'),ignore_case=ignore_case)
733 733 except:
734 734 shell.showtraceback()
735 735
736 736 def magic_who_ls(self, parameter_s=''):
737 737 """Return a sorted list of all interactive variables.
738 738
739 739 If arguments are given, only variables of types matching these
740 740 arguments are returned."""
741 741
742 742 user_ns = self.shell.user_ns
743 743 internal_ns = self.shell.internal_ns
744 744 user_ns_hidden = self.shell.user_ns_hidden
745 745 out = [ i for i in user_ns
746 746 if not i.startswith('_') \
747 747 and not (i in internal_ns or i in user_ns_hidden) ]
748 748
749 749 typelist = parameter_s.split()
750 750 if typelist:
751 751 typeset = set(typelist)
752 752 out = [i for i in out if type(i).__name__ in typeset]
753 753
754 754 out.sort()
755 755 return out
756 756
757 757 def magic_who(self, parameter_s=''):
758 758 """Print all interactive variables, with some minimal formatting.
759 759
760 760 If any arguments are given, only variables whose type matches one of
761 761 these are printed. For example:
762 762
763 763 %who function str
764 764
765 765 will only list functions and strings, excluding all other types of
766 766 variables. To find the proper type names, simply use type(var) at a
767 767 command line to see how python prints type names. For example:
768 768
769 769 In [1]: type('hello')\\
770 770 Out[1]: <type 'str'>
771 771
772 772 indicates that the type name for strings is 'str'.
773 773
774 774 %who always excludes executed names loaded through your configuration
775 775 file and things which are internal to IPython.
776 776
777 777 This is deliberate, as typically you may load many modules and the
778 778 purpose of %who is to show you only what you've manually defined."""
779 779
780 780 varlist = self.magic_who_ls(parameter_s)
781 781 if not varlist:
782 782 if parameter_s:
783 783 print 'No variables match your requested type.'
784 784 else:
785 785 print 'Interactive namespace is empty.'
786 786 return
787 787
788 788 # if we have variables, move on...
789 789 count = 0
790 790 for i in varlist:
791 791 print i+'\t',
792 792 count += 1
793 793 if count > 8:
794 794 count = 0
795 795 print
796 796 print
797 797
798 798 def magic_whos(self, parameter_s=''):
799 799 """Like %who, but gives some extra information about each variable.
800 800
801 801 The same type filtering of %who can be applied here.
802 802
803 803 For all variables, the type is printed. Additionally it prints:
804 804
805 805 - For {},[],(): their length.
806 806
807 807 - For numpy and Numeric arrays, a summary with shape, number of
808 808 elements, typecode and size in memory.
809 809
810 810 - Everything else: a string representation, snipping their middle if
811 811 too long."""
812 812
813 813 varnames = self.magic_who_ls(parameter_s)
814 814 if not varnames:
815 815 if parameter_s:
816 816 print 'No variables match your requested type.'
817 817 else:
818 818 print 'Interactive namespace is empty.'
819 819 return
820 820
821 821 # if we have variables, move on...
822 822
823 823 # for these types, show len() instead of data:
824 824 seq_types = [types.DictType,types.ListType,types.TupleType]
825 825
826 826 # for numpy/Numeric arrays, display summary info
827 827 try:
828 828 import numpy
829 829 except ImportError:
830 830 ndarray_type = None
831 831 else:
832 832 ndarray_type = numpy.ndarray.__name__
833 833 try:
834 834 import Numeric
835 835 except ImportError:
836 836 array_type = None
837 837 else:
838 838 array_type = Numeric.ArrayType.__name__
839 839
840 840 # Find all variable names and types so we can figure out column sizes
841 841 def get_vars(i):
842 842 return self.shell.user_ns[i]
843 843
844 844 # some types are well known and can be shorter
845 845 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
846 846 def type_name(v):
847 847 tn = type(v).__name__
848 848 return abbrevs.get(tn,tn)
849 849
850 850 varlist = map(get_vars,varnames)
851 851
852 852 typelist = []
853 853 for vv in varlist:
854 854 tt = type_name(vv)
855 855
856 856 if tt=='instance':
857 857 typelist.append( abbrevs.get(str(vv.__class__),
858 858 str(vv.__class__)))
859 859 else:
860 860 typelist.append(tt)
861 861
862 862 # column labels and # of spaces as separator
863 863 varlabel = 'Variable'
864 864 typelabel = 'Type'
865 865 datalabel = 'Data/Info'
866 866 colsep = 3
867 867 # variable format strings
868 868 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
869 869 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
870 870 aformat = "%s: %s elems, type `%s`, %s bytes"
871 871 # find the size of the columns to format the output nicely
872 872 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
873 873 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
874 874 # table header
875 875 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
876 876 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
877 877 # and the table itself
878 878 kb = 1024
879 879 Mb = 1048576 # kb**2
880 880 for vname,var,vtype in zip(varnames,varlist,typelist):
881 881 print itpl(vformat),
882 882 if vtype in seq_types:
883 883 print len(var)
884 884 elif vtype in [array_type,ndarray_type]:
885 885 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
886 886 if vtype==ndarray_type:
887 887 # numpy
888 888 vsize = var.size
889 889 vbytes = vsize*var.itemsize
890 890 vdtype = var.dtype
891 891 else:
892 892 # Numeric
893 893 vsize = Numeric.size(var)
894 894 vbytes = vsize*var.itemsize()
895 895 vdtype = var.typecode()
896 896
897 897 if vbytes < 100000:
898 898 print aformat % (vshape,vsize,vdtype,vbytes)
899 899 else:
900 900 print aformat % (vshape,vsize,vdtype,vbytes),
901 901 if vbytes < Mb:
902 902 print '(%s kb)' % (vbytes/kb,)
903 903 else:
904 904 print '(%s Mb)' % (vbytes/Mb,)
905 905 else:
906 906 try:
907 907 vstr = str(var)
908 908 except UnicodeEncodeError:
909 909 vstr = unicode(var).encode(sys.getdefaultencoding(),
910 910 'backslashreplace')
911 911 vstr = vstr.replace('\n','\\n')
912 912 if len(vstr) < 50:
913 913 print vstr
914 914 else:
915 915 printpl(vfmt_short)
916 916
917 917 def magic_reset(self, parameter_s=''):
918 918 """Resets the namespace by removing all names defined by the user.
919 919
920 920 Input/Output history are left around in case you need them.
921 921
922 922 Parameters
923 923 ----------
924 924 -y : force reset without asking for confirmation.
925 925
926 926 Examples
927 927 --------
928 928 In [6]: a = 1
929 929
930 930 In [7]: a
931 931 Out[7]: 1
932 932
933 933 In [8]: 'a' in _ip.user_ns
934 934 Out[8]: True
935 935
936 936 In [9]: %reset -f
937 937
938 938 In [10]: 'a' in _ip.user_ns
939 939 Out[10]: False
940 940 """
941 941
942 942 if parameter_s == '-f':
943 943 ans = True
944 944 else:
945 945 ans = self.shell.ask_yes_no(
946 946 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
947 947 if not ans:
948 948 print 'Nothing done.'
949 949 return
950 950 user_ns = self.shell.user_ns
951 951 for i in self.magic_who_ls():
952 952 del(user_ns[i])
953 953
954 954 # Also flush the private list of module references kept for script
955 955 # execution protection
956 956 self.shell.clear_main_mod_cache()
957 957
958 958 def magic_reset_selective(self, parameter_s=''):
959 959 """Resets the namespace by removing names defined by the user.
960 960
961 961 Input/Output history are left around in case you need them.
962 962
963 963 %reset_selective [-f] regex
964 964
965 965 No action is taken if regex is not included
966 966
967 967 Options
968 968 -f : force reset without asking for confirmation.
969 969
970 970 Examples
971 971 --------
972 972
973 973 We first fully reset the namespace so your output looks identical to
974 974 this example for pedagogical reasons; in practice you do not need a
975 975 full reset.
976 976
977 977 In [1]: %reset -f
978 978
979 979 Now, with a clean namespace we can make a few variables and use
980 980 %reset_selective to only delete names that match our regexp:
981 981
982 982 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
983 983
984 984 In [3]: who_ls
985 985 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
986 986
987 987 In [4]: %reset_selective -f b[2-3]m
988 988
989 989 In [5]: who_ls
990 990 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
991 991
992 992 In [6]: %reset_selective -f d
993 993
994 994 In [7]: who_ls
995 995 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
996 996
997 997 In [8]: %reset_selective -f c
998 998
999 999 In [9]: who_ls
1000 1000 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1001 1001
1002 1002 In [10]: %reset_selective -f b
1003 1003
1004 1004 In [11]: who_ls
1005 1005 Out[11]: ['a']
1006 1006 """
1007 1007
1008 1008 opts, regex = self.parse_options(parameter_s,'f')
1009 1009
1010 1010 if opts.has_key('f'):
1011 1011 ans = True
1012 1012 else:
1013 1013 ans = self.shell.ask_yes_no(
1014 1014 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1015 1015 if not ans:
1016 1016 print 'Nothing done.'
1017 1017 return
1018 1018 user_ns = self.shell.user_ns
1019 1019 if not regex:
1020 1020 print 'No regex pattern specified. Nothing done.'
1021 1021 return
1022 1022 else:
1023 1023 try:
1024 1024 m = re.compile(regex)
1025 1025 except TypeError:
1026 1026 raise TypeError('regex must be a string or compiled pattern')
1027 1027 for i in self.magic_who_ls():
1028 1028 if m.search(i):
1029 1029 del(user_ns[i])
1030 1030
1031 1031 def magic_logstart(self,parameter_s=''):
1032 1032 """Start logging anywhere in a session.
1033 1033
1034 1034 %logstart [-o|-r|-t] [log_name [log_mode]]
1035 1035
1036 1036 If no name is given, it defaults to a file named 'ipython_log.py' in your
1037 1037 current directory, in 'rotate' mode (see below).
1038 1038
1039 1039 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1040 1040 history up to that point and then continues logging.
1041 1041
1042 1042 %logstart takes a second optional parameter: logging mode. This can be one
1043 1043 of (note that the modes are given unquoted):\\
1044 1044 append: well, that says it.\\
1045 1045 backup: rename (if exists) to name~ and start name.\\
1046 1046 global: single logfile in your home dir, appended to.\\
1047 1047 over : overwrite existing log.\\
1048 1048 rotate: create rotating logs name.1~, name.2~, etc.
1049 1049
1050 1050 Options:
1051 1051
1052 1052 -o: log also IPython's output. In this mode, all commands which
1053 1053 generate an Out[NN] prompt are recorded to the logfile, right after
1054 1054 their corresponding input line. The output lines are always
1055 1055 prepended with a '#[Out]# ' marker, so that the log remains valid
1056 1056 Python code.
1057 1057
1058 1058 Since this marker is always the same, filtering only the output from
1059 1059 a log is very easy, using for example a simple awk call:
1060 1060
1061 1061 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1062 1062
1063 1063 -r: log 'raw' input. Normally, IPython's logs contain the processed
1064 1064 input, so that user lines are logged in their final form, converted
1065 1065 into valid Python. For example, %Exit is logged as
1066 1066 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1067 1067 exactly as typed, with no transformations applied.
1068 1068
1069 1069 -t: put timestamps before each input line logged (these are put in
1070 1070 comments)."""
1071 1071
1072 1072 opts,par = self.parse_options(parameter_s,'ort')
1073 1073 log_output = 'o' in opts
1074 1074 log_raw_input = 'r' in opts
1075 1075 timestamp = 't' in opts
1076 1076
1077 1077 logger = self.shell.logger
1078 1078
1079 1079 # if no args are given, the defaults set in the logger constructor by
1080 1080 # ipytohn remain valid
1081 1081 if par:
1082 1082 try:
1083 1083 logfname,logmode = par.split()
1084 1084 except:
1085 1085 logfname = par
1086 1086 logmode = 'backup'
1087 1087 else:
1088 1088 logfname = logger.logfname
1089 1089 logmode = logger.logmode
1090 1090 # put logfname into rc struct as if it had been called on the command
1091 1091 # line, so it ends up saved in the log header Save it in case we need
1092 1092 # to restore it...
1093 1093 old_logfile = self.shell.logfile
1094 1094 if logfname:
1095 1095 logfname = os.path.expanduser(logfname)
1096 1096 self.shell.logfile = logfname
1097 1097
1098 1098 loghead = '# IPython log file\n\n'
1099 1099 try:
1100 1100 started = logger.logstart(logfname,loghead,logmode,
1101 1101 log_output,timestamp,log_raw_input)
1102 1102 except:
1103 1103 self.shell.logfile = old_logfile
1104 1104 warn("Couldn't start log: %s" % sys.exc_info()[1])
1105 1105 else:
1106 1106 # log input history up to this point, optionally interleaving
1107 1107 # output if requested
1108 1108
1109 1109 if timestamp:
1110 1110 # disable timestamping for the previous history, since we've
1111 1111 # lost those already (no time machine here).
1112 1112 logger.timestamp = False
1113 1113
1114 1114 if log_raw_input:
1115 1115 input_hist = self.shell.input_hist_raw
1116 1116 else:
1117 1117 input_hist = self.shell.input_hist
1118 1118
1119 1119 if log_output:
1120 1120 log_write = logger.log_write
1121 1121 output_hist = self.shell.output_hist
1122 1122 for n in range(1,len(input_hist)-1):
1123 1123 log_write(input_hist[n].rstrip())
1124 1124 if n in output_hist:
1125 1125 log_write(repr(output_hist[n]),'output')
1126 1126 else:
1127 1127 logger.log_write(input_hist[1:])
1128 1128 if timestamp:
1129 1129 # re-enable timestamping
1130 1130 logger.timestamp = True
1131 1131
1132 1132 print ('Activating auto-logging. '
1133 1133 'Current session state plus future input saved.')
1134 1134 logger.logstate()
1135 1135
1136 1136 def magic_logstop(self,parameter_s=''):
1137 1137 """Fully stop logging and close log file.
1138 1138
1139 1139 In order to start logging again, a new %logstart call needs to be made,
1140 1140 possibly (though not necessarily) with a new filename, mode and other
1141 1141 options."""
1142 1142 self.logger.logstop()
1143 1143
1144 1144 def magic_logoff(self,parameter_s=''):
1145 1145 """Temporarily stop logging.
1146 1146
1147 1147 You must have previously started logging."""
1148 1148 self.shell.logger.switch_log(0)
1149 1149
1150 1150 def magic_logon(self,parameter_s=''):
1151 1151 """Restart logging.
1152 1152
1153 1153 This function is for restarting logging which you've temporarily
1154 1154 stopped with %logoff. For starting logging for the first time, you
1155 1155 must use the %logstart function, which allows you to specify an
1156 1156 optional log filename."""
1157 1157
1158 1158 self.shell.logger.switch_log(1)
1159 1159
1160 1160 def magic_logstate(self,parameter_s=''):
1161 1161 """Print the status of the logging system."""
1162 1162
1163 1163 self.shell.logger.logstate()
1164 1164
1165 1165 def magic_pdb(self, parameter_s=''):
1166 1166 """Control the automatic calling of the pdb interactive debugger.
1167 1167
1168 1168 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1169 1169 argument it works as a toggle.
1170 1170
1171 1171 When an exception is triggered, IPython can optionally call the
1172 1172 interactive pdb debugger after the traceback printout. %pdb toggles
1173 1173 this feature on and off.
1174 1174
1175 1175 The initial state of this feature is set in your ipythonrc
1176 1176 configuration file (the variable is called 'pdb').
1177 1177
1178 1178 If you want to just activate the debugger AFTER an exception has fired,
1179 1179 without having to type '%pdb on' and rerunning your code, you can use
1180 1180 the %debug magic."""
1181 1181
1182 1182 par = parameter_s.strip().lower()
1183 1183
1184 1184 if par:
1185 1185 try:
1186 1186 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1187 1187 except KeyError:
1188 1188 print ('Incorrect argument. Use on/1, off/0, '
1189 1189 'or nothing for a toggle.')
1190 1190 return
1191 1191 else:
1192 1192 # toggle
1193 1193 new_pdb = not self.shell.call_pdb
1194 1194
1195 1195 # set on the shell
1196 1196 self.shell.call_pdb = new_pdb
1197 1197 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1198 1198
1199 1199 def magic_debug(self, parameter_s=''):
1200 1200 """Activate the interactive debugger in post-mortem mode.
1201 1201
1202 1202 If an exception has just occurred, this lets you inspect its stack
1203 1203 frames interactively. Note that this will always work only on the last
1204 1204 traceback that occurred, so you must call this quickly after an
1205 1205 exception that you wish to inspect has fired, because if another one
1206 1206 occurs, it clobbers the previous one.
1207 1207
1208 1208 If you want IPython to automatically do this on every exception, see
1209 1209 the %pdb magic for more details.
1210 1210 """
1211 1211 self.shell.debugger(force=True)
1212 1212
1213 1213 @testdec.skip_doctest
1214 1214 def magic_prun(self, parameter_s ='',user_mode=1,
1215 1215 opts=None,arg_lst=None,prog_ns=None):
1216 1216
1217 1217 """Run a statement through the python code profiler.
1218 1218
1219 1219 Usage:
1220 1220 %prun [options] statement
1221 1221
1222 1222 The given statement (which doesn't require quote marks) is run via the
1223 1223 python profiler in a manner similar to the profile.run() function.
1224 1224 Namespaces are internally managed to work correctly; profile.run
1225 1225 cannot be used in IPython because it makes certain assumptions about
1226 1226 namespaces which do not hold under IPython.
1227 1227
1228 1228 Options:
1229 1229
1230 1230 -l <limit>: you can place restrictions on what or how much of the
1231 1231 profile gets printed. The limit value can be:
1232 1232
1233 1233 * A string: only information for function names containing this string
1234 1234 is printed.
1235 1235
1236 1236 * An integer: only these many lines are printed.
1237 1237
1238 1238 * A float (between 0 and 1): this fraction of the report is printed
1239 1239 (for example, use a limit of 0.4 to see the topmost 40% only).
1240 1240
1241 1241 You can combine several limits with repeated use of the option. For
1242 1242 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1243 1243 information about class constructors.
1244 1244
1245 1245 -r: return the pstats.Stats object generated by the profiling. This
1246 1246 object has all the information about the profile in it, and you can
1247 1247 later use it for further analysis or in other functions.
1248 1248
1249 1249 -s <key>: sort profile by given key. You can provide more than one key
1250 1250 by using the option several times: '-s key1 -s key2 -s key3...'. The
1251 1251 default sorting key is 'time'.
1252 1252
1253 1253 The following is copied verbatim from the profile documentation
1254 1254 referenced below:
1255 1255
1256 1256 When more than one key is provided, additional keys are used as
1257 1257 secondary criteria when the there is equality in all keys selected
1258 1258 before them.
1259 1259
1260 1260 Abbreviations can be used for any key names, as long as the
1261 1261 abbreviation is unambiguous. The following are the keys currently
1262 1262 defined:
1263 1263
1264 1264 Valid Arg Meaning
1265 1265 "calls" call count
1266 1266 "cumulative" cumulative time
1267 1267 "file" file name
1268 1268 "module" file name
1269 1269 "pcalls" primitive call count
1270 1270 "line" line number
1271 1271 "name" function name
1272 1272 "nfl" name/file/line
1273 1273 "stdname" standard name
1274 1274 "time" internal time
1275 1275
1276 1276 Note that all sorts on statistics are in descending order (placing
1277 1277 most time consuming items first), where as name, file, and line number
1278 1278 searches are in ascending order (i.e., alphabetical). The subtle
1279 1279 distinction between "nfl" and "stdname" is that the standard name is a
1280 1280 sort of the name as printed, which means that the embedded line
1281 1281 numbers get compared in an odd way. For example, lines 3, 20, and 40
1282 1282 would (if the file names were the same) appear in the string order
1283 1283 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1284 1284 line numbers. In fact, sort_stats("nfl") is the same as
1285 1285 sort_stats("name", "file", "line").
1286 1286
1287 1287 -T <filename>: save profile results as shown on screen to a text
1288 1288 file. The profile is still shown on screen.
1289 1289
1290 1290 -D <filename>: save (via dump_stats) profile statistics to given
1291 1291 filename. This data is in a format understod by the pstats module, and
1292 1292 is generated by a call to the dump_stats() method of profile
1293 1293 objects. The profile is still shown on screen.
1294 1294
1295 1295 If you want to run complete programs under the profiler's control, use
1296 1296 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1297 1297 contains profiler specific options as described here.
1298 1298
1299 1299 You can read the complete documentation for the profile module with::
1300 1300
1301 1301 In [1]: import profile; profile.help()
1302 1302 """
1303 1303
1304 1304 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1305 1305 # protect user quote marks
1306 1306 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1307 1307
1308 1308 if user_mode: # regular user call
1309 1309 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1310 1310 list_all=1)
1311 1311 namespace = self.shell.user_ns
1312 1312 else: # called to run a program by %run -p
1313 1313 try:
1314 1314 filename = get_py_filename(arg_lst[0])
1315 1315 except IOError,msg:
1316 1316 error(msg)
1317 1317 return
1318 1318
1319 1319 arg_str = 'execfile(filename,prog_ns)'
1320 1320 namespace = locals()
1321 1321
1322 1322 opts.merge(opts_def)
1323 1323
1324 1324 prof = profile.Profile()
1325 1325 try:
1326 1326 prof = prof.runctx(arg_str,namespace,namespace)
1327 1327 sys_exit = ''
1328 1328 except SystemExit:
1329 1329 sys_exit = """*** SystemExit exception caught in code being profiled."""
1330 1330
1331 1331 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1332 1332
1333 1333 lims = opts.l
1334 1334 if lims:
1335 1335 lims = [] # rebuild lims with ints/floats/strings
1336 1336 for lim in opts.l:
1337 1337 try:
1338 1338 lims.append(int(lim))
1339 1339 except ValueError:
1340 1340 try:
1341 1341 lims.append(float(lim))
1342 1342 except ValueError:
1343 1343 lims.append(lim)
1344 1344
1345 1345 # Trap output.
1346 1346 stdout_trap = StringIO()
1347 1347
1348 1348 if hasattr(stats,'stream'):
1349 1349 # In newer versions of python, the stats object has a 'stream'
1350 1350 # attribute to write into.
1351 1351 stats.stream = stdout_trap
1352 1352 stats.print_stats(*lims)
1353 1353 else:
1354 1354 # For older versions, we manually redirect stdout during printing
1355 1355 sys_stdout = sys.stdout
1356 1356 try:
1357 1357 sys.stdout = stdout_trap
1358 1358 stats.print_stats(*lims)
1359 1359 finally:
1360 1360 sys.stdout = sys_stdout
1361 1361
1362 1362 output = stdout_trap.getvalue()
1363 1363 output = output.rstrip()
1364 1364
1365 1365 page.page(output)
1366 1366 print sys_exit,
1367 1367
1368 1368 dump_file = opts.D[0]
1369 1369 text_file = opts.T[0]
1370 1370 if dump_file:
1371 1371 prof.dump_stats(dump_file)
1372 1372 print '\n*** Profile stats marshalled to file',\
1373 1373 `dump_file`+'.',sys_exit
1374 1374 if text_file:
1375 1375 pfile = file(text_file,'w')
1376 1376 pfile.write(output)
1377 1377 pfile.close()
1378 1378 print '\n*** Profile printout saved to text file',\
1379 1379 `text_file`+'.',sys_exit
1380 1380
1381 1381 if opts.has_key('r'):
1382 1382 return stats
1383 1383 else:
1384 1384 return None
1385 1385
1386 1386 @testdec.skip_doctest
1387 1387 def magic_run(self, parameter_s ='',runner=None,
1388 1388 file_finder=get_py_filename):
1389 1389 """Run the named file inside IPython as a program.
1390 1390
1391 1391 Usage:\\
1392 1392 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1393 1393
1394 1394 Parameters after the filename are passed as command-line arguments to
1395 1395 the program (put in sys.argv). Then, control returns to IPython's
1396 1396 prompt.
1397 1397
1398 1398 This is similar to running at a system prompt:\\
1399 1399 $ python file args\\
1400 1400 but with the advantage of giving you IPython's tracebacks, and of
1401 1401 loading all variables into your interactive namespace for further use
1402 1402 (unless -p is used, see below).
1403 1403
1404 1404 The file is executed in a namespace initially consisting only of
1405 1405 __name__=='__main__' and sys.argv constructed as indicated. It thus
1406 1406 sees its environment as if it were being run as a stand-alone program
1407 1407 (except for sharing global objects such as previously imported
1408 1408 modules). But after execution, the IPython interactive namespace gets
1409 1409 updated with all variables defined in the program (except for __name__
1410 1410 and sys.argv). This allows for very convenient loading of code for
1411 1411 interactive work, while giving each program a 'clean sheet' to run in.
1412 1412
1413 1413 Options:
1414 1414
1415 1415 -n: __name__ is NOT set to '__main__', but to the running file's name
1416 1416 without extension (as python does under import). This allows running
1417 1417 scripts and reloading the definitions in them without calling code
1418 1418 protected by an ' if __name__ == "__main__" ' clause.
1419 1419
1420 1420 -i: run the file in IPython's namespace instead of an empty one. This
1421 1421 is useful if you are experimenting with code written in a text editor
1422 1422 which depends on variables defined interactively.
1423 1423
1424 1424 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1425 1425 being run. This is particularly useful if IPython is being used to
1426 1426 run unittests, which always exit with a sys.exit() call. In such
1427 1427 cases you are interested in the output of the test results, not in
1428 1428 seeing a traceback of the unittest module.
1429 1429
1430 1430 -t: print timing information at the end of the run. IPython will give
1431 1431 you an estimated CPU time consumption for your script, which under
1432 1432 Unix uses the resource module to avoid the wraparound problems of
1433 1433 time.clock(). Under Unix, an estimate of time spent on system tasks
1434 1434 is also given (for Windows platforms this is reported as 0.0).
1435 1435
1436 1436 If -t is given, an additional -N<N> option can be given, where <N>
1437 1437 must be an integer indicating how many times you want the script to
1438 1438 run. The final timing report will include total and per run results.
1439 1439
1440 1440 For example (testing the script uniq_stable.py):
1441 1441
1442 1442 In [1]: run -t uniq_stable
1443 1443
1444 1444 IPython CPU timings (estimated):\\
1445 1445 User : 0.19597 s.\\
1446 1446 System: 0.0 s.\\
1447 1447
1448 1448 In [2]: run -t -N5 uniq_stable
1449 1449
1450 1450 IPython CPU timings (estimated):\\
1451 1451 Total runs performed: 5\\
1452 1452 Times : Total Per run\\
1453 1453 User : 0.910862 s, 0.1821724 s.\\
1454 1454 System: 0.0 s, 0.0 s.
1455 1455
1456 1456 -d: run your program under the control of pdb, the Python debugger.
1457 1457 This allows you to execute your program step by step, watch variables,
1458 1458 etc. Internally, what IPython does is similar to calling:
1459 1459
1460 1460 pdb.run('execfile("YOURFILENAME")')
1461 1461
1462 1462 with a breakpoint set on line 1 of your file. You can change the line
1463 1463 number for this automatic breakpoint to be <N> by using the -bN option
1464 1464 (where N must be an integer). For example:
1465 1465
1466 1466 %run -d -b40 myscript
1467 1467
1468 1468 will set the first breakpoint at line 40 in myscript.py. Note that
1469 1469 the first breakpoint must be set on a line which actually does
1470 1470 something (not a comment or docstring) for it to stop execution.
1471 1471
1472 1472 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1473 1473 first enter 'c' (without qoutes) to start execution up to the first
1474 1474 breakpoint.
1475 1475
1476 1476 Entering 'help' gives information about the use of the debugger. You
1477 1477 can easily see pdb's full documentation with "import pdb;pdb.help()"
1478 1478 at a prompt.
1479 1479
1480 1480 -p: run program under the control of the Python profiler module (which
1481 1481 prints a detailed report of execution times, function calls, etc).
1482 1482
1483 1483 You can pass other options after -p which affect the behavior of the
1484 1484 profiler itself. See the docs for %prun for details.
1485 1485
1486 1486 In this mode, the program's variables do NOT propagate back to the
1487 1487 IPython interactive namespace (because they remain in the namespace
1488 1488 where the profiler executes them).
1489 1489
1490 1490 Internally this triggers a call to %prun, see its documentation for
1491 1491 details on the options available specifically for profiling.
1492 1492
1493 1493 There is one special usage for which the text above doesn't apply:
1494 1494 if the filename ends with .ipy, the file is run as ipython script,
1495 1495 just as if the commands were written on IPython prompt.
1496 1496 """
1497 1497
1498 1498 # get arguments and set sys.argv for program to be run.
1499 1499 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1500 1500 mode='list',list_all=1)
1501 1501
1502 1502 try:
1503 1503 filename = file_finder(arg_lst[0])
1504 1504 except IndexError:
1505 1505 warn('you must provide at least a filename.')
1506 1506 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1507 1507 return
1508 1508 except IOError,msg:
1509 1509 error(msg)
1510 1510 return
1511 1511
1512 1512 if filename.lower().endswith('.ipy'):
1513 1513 self.shell.safe_execfile_ipy(filename)
1514 1514 return
1515 1515
1516 1516 # Control the response to exit() calls made by the script being run
1517 1517 exit_ignore = opts.has_key('e')
1518 1518
1519 1519 # Make sure that the running script gets a proper sys.argv as if it
1520 1520 # were run from a system shell.
1521 1521 save_argv = sys.argv # save it for later restoring
1522 1522 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1523 1523
1524 1524 if opts.has_key('i'):
1525 1525 # Run in user's interactive namespace
1526 1526 prog_ns = self.shell.user_ns
1527 1527 __name__save = self.shell.user_ns['__name__']
1528 1528 prog_ns['__name__'] = '__main__'
1529 1529 main_mod = self.shell.new_main_mod(prog_ns)
1530 1530 else:
1531 1531 # Run in a fresh, empty namespace
1532 1532 if opts.has_key('n'):
1533 1533 name = os.path.splitext(os.path.basename(filename))[0]
1534 1534 else:
1535 1535 name = '__main__'
1536 1536
1537 1537 main_mod = self.shell.new_main_mod()
1538 1538 prog_ns = main_mod.__dict__
1539 1539 prog_ns['__name__'] = name
1540 1540
1541 1541 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1542 1542 # set the __file__ global in the script's namespace
1543 1543 prog_ns['__file__'] = filename
1544 1544
1545 1545 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1546 1546 # that, if we overwrite __main__, we replace it at the end
1547 1547 main_mod_name = prog_ns['__name__']
1548 1548
1549 1549 if main_mod_name == '__main__':
1550 1550 restore_main = sys.modules['__main__']
1551 1551 else:
1552 1552 restore_main = False
1553 1553
1554 1554 # This needs to be undone at the end to prevent holding references to
1555 1555 # every single object ever created.
1556 1556 sys.modules[main_mod_name] = main_mod
1557 1557
1558 1558 stats = None
1559 1559 try:
1560 1560 self.shell.savehist()
1561 1561
1562 1562 if opts.has_key('p'):
1563 1563 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1564 1564 else:
1565 1565 if opts.has_key('d'):
1566 1566 deb = debugger.Pdb(self.shell.colors)
1567 1567 # reset Breakpoint state, which is moronically kept
1568 1568 # in a class
1569 1569 bdb.Breakpoint.next = 1
1570 1570 bdb.Breakpoint.bplist = {}
1571 1571 bdb.Breakpoint.bpbynumber = [None]
1572 1572 # Set an initial breakpoint to stop execution
1573 1573 maxtries = 10
1574 1574 bp = int(opts.get('b',[1])[0])
1575 1575 checkline = deb.checkline(filename,bp)
1576 1576 if not checkline:
1577 1577 for bp in range(bp+1,bp+maxtries+1):
1578 1578 if deb.checkline(filename,bp):
1579 1579 break
1580 1580 else:
1581 1581 msg = ("\nI failed to find a valid line to set "
1582 1582 "a breakpoint\n"
1583 1583 "after trying up to line: %s.\n"
1584 1584 "Please set a valid breakpoint manually "
1585 1585 "with the -b option." % bp)
1586 1586 error(msg)
1587 1587 return
1588 1588 # if we find a good linenumber, set the breakpoint
1589 1589 deb.do_break('%s:%s' % (filename,bp))
1590 1590 # Start file run
1591 1591 print "NOTE: Enter 'c' at the",
1592 1592 print "%s prompt to start your script." % deb.prompt
1593 1593 try:
1594 1594 deb.run('execfile("%s")' % filename,prog_ns)
1595 1595
1596 1596 except:
1597 1597 etype, value, tb = sys.exc_info()
1598 1598 # Skip three frames in the traceback: the %run one,
1599 1599 # one inside bdb.py, and the command-line typed by the
1600 1600 # user (run by exec in pdb itself).
1601 1601 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1602 1602 else:
1603 1603 if runner is None:
1604 1604 runner = self.shell.safe_execfile
1605 1605 if opts.has_key('t'):
1606 1606 # timed execution
1607 1607 try:
1608 1608 nruns = int(opts['N'][0])
1609 1609 if nruns < 1:
1610 1610 error('Number of runs must be >=1')
1611 1611 return
1612 1612 except (KeyError):
1613 1613 nruns = 1
1614 1614 if nruns == 1:
1615 1615 t0 = clock2()
1616 1616 runner(filename,prog_ns,prog_ns,
1617 1617 exit_ignore=exit_ignore)
1618 1618 t1 = clock2()
1619 1619 t_usr = t1[0]-t0[0]
1620 1620 t_sys = t1[1]-t0[1]
1621 1621 print "\nIPython CPU timings (estimated):"
1622 1622 print " User : %10s s." % t_usr
1623 1623 print " System: %10s s." % t_sys
1624 1624 else:
1625 1625 runs = range(nruns)
1626 1626 t0 = clock2()
1627 1627 for nr in runs:
1628 1628 runner(filename,prog_ns,prog_ns,
1629 1629 exit_ignore=exit_ignore)
1630 1630 t1 = clock2()
1631 1631 t_usr = t1[0]-t0[0]
1632 1632 t_sys = t1[1]-t0[1]
1633 1633 print "\nIPython CPU timings (estimated):"
1634 1634 print "Total runs performed:",nruns
1635 1635 print " Times : %10s %10s" % ('Total','Per run')
1636 1636 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1637 1637 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1638 1638
1639 1639 else:
1640 1640 # regular execution
1641 1641 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1642 1642
1643 1643 if opts.has_key('i'):
1644 1644 self.shell.user_ns['__name__'] = __name__save
1645 1645 else:
1646 1646 # The shell MUST hold a reference to prog_ns so after %run
1647 1647 # exits, the python deletion mechanism doesn't zero it out
1648 1648 # (leaving dangling references).
1649 1649 self.shell.cache_main_mod(prog_ns,filename)
1650 1650 # update IPython interactive namespace
1651 1651
1652 1652 # Some forms of read errors on the file may mean the
1653 1653 # __name__ key was never set; using pop we don't have to
1654 1654 # worry about a possible KeyError.
1655 1655 prog_ns.pop('__name__', None)
1656 1656
1657 1657 self.shell.user_ns.update(prog_ns)
1658 1658 finally:
1659 1659 # It's a bit of a mystery why, but __builtins__ can change from
1660 1660 # being a module to becoming a dict missing some key data after
1661 1661 # %run. As best I can see, this is NOT something IPython is doing
1662 1662 # at all, and similar problems have been reported before:
1663 1663 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1664 1664 # Since this seems to be done by the interpreter itself, the best
1665 1665 # we can do is to at least restore __builtins__ for the user on
1666 1666 # exit.
1667 1667 self.shell.user_ns['__builtins__'] = __builtin__
1668 1668
1669 1669 # Ensure key global structures are restored
1670 1670 sys.argv = save_argv
1671 1671 if restore_main:
1672 1672 sys.modules['__main__'] = restore_main
1673 1673 else:
1674 1674 # Remove from sys.modules the reference to main_mod we'd
1675 1675 # added. Otherwise it will trap references to objects
1676 1676 # contained therein.
1677 1677 del sys.modules[main_mod_name]
1678 1678
1679 1679 self.shell.reloadhist()
1680 1680
1681 1681 return stats
1682 1682
1683 1683 @testdec.skip_doctest
1684 1684 def magic_timeit(self, parameter_s =''):
1685 1685 """Time execution of a Python statement or expression
1686 1686
1687 1687 Usage:\\
1688 1688 %timeit [-n<N> -r<R> [-t|-c]] statement
1689 1689
1690 1690 Time execution of a Python statement or expression using the timeit
1691 1691 module.
1692 1692
1693 1693 Options:
1694 1694 -n<N>: execute the given statement <N> times in a loop. If this value
1695 1695 is not given, a fitting value is chosen.
1696 1696
1697 1697 -r<R>: repeat the loop iteration <R> times and take the best result.
1698 1698 Default: 3
1699 1699
1700 1700 -t: use time.time to measure the time, which is the default on Unix.
1701 1701 This function measures wall time.
1702 1702
1703 1703 -c: use time.clock to measure the time, which is the default on
1704 1704 Windows and measures wall time. On Unix, resource.getrusage is used
1705 1705 instead and returns the CPU user time.
1706 1706
1707 1707 -p<P>: use a precision of <P> digits to display the timing result.
1708 1708 Default: 3
1709 1709
1710 1710
1711 1711 Examples:
1712 1712
1713 1713 In [1]: %timeit pass
1714 1714 10000000 loops, best of 3: 53.3 ns per loop
1715 1715
1716 1716 In [2]: u = None
1717 1717
1718 1718 In [3]: %timeit u is None
1719 1719 10000000 loops, best of 3: 184 ns per loop
1720 1720
1721 1721 In [4]: %timeit -r 4 u == None
1722 1722 1000000 loops, best of 4: 242 ns per loop
1723 1723
1724 1724 In [5]: import time
1725 1725
1726 1726 In [6]: %timeit -n1 time.sleep(2)
1727 1727 1 loops, best of 3: 2 s per loop
1728 1728
1729 1729
1730 1730 The times reported by %timeit will be slightly higher than those
1731 1731 reported by the timeit.py script when variables are accessed. This is
1732 1732 due to the fact that %timeit executes the statement in the namespace
1733 1733 of the shell, compared with timeit.py, which uses a single setup
1734 1734 statement to import function or create variables. Generally, the bias
1735 1735 does not matter as long as results from timeit.py are not mixed with
1736 1736 those from %timeit."""
1737 1737
1738 1738 import timeit
1739 1739 import math
1740 1740
1741 1741 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1742 1742 # certain terminals. Until we figure out a robust way of
1743 1743 # auto-detecting if the terminal can deal with it, use plain 'us' for
1744 1744 # microseconds. I am really NOT happy about disabling the proper
1745 1745 # 'micro' prefix, but crashing is worse... If anyone knows what the
1746 1746 # right solution for this is, I'm all ears...
1747 1747 #
1748 1748 # Note: using
1749 1749 #
1750 1750 # s = u'\xb5'
1751 1751 # s.encode(sys.getdefaultencoding())
1752 1752 #
1753 1753 # is not sufficient, as I've seen terminals where that fails but
1754 1754 # print s
1755 1755 #
1756 1756 # succeeds
1757 1757 #
1758 1758 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1759 1759
1760 1760 #units = [u"s", u"ms",u'\xb5',"ns"]
1761 1761 units = [u"s", u"ms",u'us',"ns"]
1762 1762
1763 1763 scaling = [1, 1e3, 1e6, 1e9]
1764 1764
1765 1765 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1766 1766 posix=False)
1767 1767 if stmt == "":
1768 1768 return
1769 1769 timefunc = timeit.default_timer
1770 1770 number = int(getattr(opts, "n", 0))
1771 1771 repeat = int(getattr(opts, "r", timeit.default_repeat))
1772 1772 precision = int(getattr(opts, "p", 3))
1773 1773 if hasattr(opts, "t"):
1774 1774 timefunc = time.time
1775 1775 if hasattr(opts, "c"):
1776 1776 timefunc = clock
1777 1777
1778 1778 timer = timeit.Timer(timer=timefunc)
1779 1779 # this code has tight coupling to the inner workings of timeit.Timer,
1780 1780 # but is there a better way to achieve that the code stmt has access
1781 1781 # to the shell namespace?
1782 1782
1783 1783 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1784 1784 'setup': "pass"}
1785 1785 # Track compilation time so it can be reported if too long
1786 1786 # Minimum time above which compilation time will be reported
1787 1787 tc_min = 0.1
1788 1788
1789 1789 t0 = clock()
1790 1790 code = compile(src, "<magic-timeit>", "exec")
1791 1791 tc = clock()-t0
1792 1792
1793 1793 ns = {}
1794 1794 exec code in self.shell.user_ns, ns
1795 1795 timer.inner = ns["inner"]
1796 1796
1797 1797 if number == 0:
1798 1798 # determine number so that 0.2 <= total time < 2.0
1799 1799 number = 1
1800 1800 for i in range(1, 10):
1801 1801 if timer.timeit(number) >= 0.2:
1802 1802 break
1803 1803 number *= 10
1804 1804
1805 1805 best = min(timer.repeat(repeat, number)) / number
1806 1806
1807 1807 if best > 0.0 and best < 1000.0:
1808 1808 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1809 1809 elif best >= 1000.0:
1810 1810 order = 0
1811 1811 else:
1812 1812 order = 3
1813 1813 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1814 1814 precision,
1815 1815 best * scaling[order],
1816 1816 units[order])
1817 1817 if tc > tc_min:
1818 1818 print "Compiler time: %.2f s" % tc
1819 1819
1820 1820 @testdec.skip_doctest
1821 1821 def magic_time(self,parameter_s = ''):
1822 1822 """Time execution of a Python statement or expression.
1823 1823
1824 1824 The CPU and wall clock times are printed, and the value of the
1825 1825 expression (if any) is returned. Note that under Win32, system time
1826 1826 is always reported as 0, since it can not be measured.
1827 1827
1828 1828 This function provides very basic timing functionality. In Python
1829 1829 2.3, the timeit module offers more control and sophistication, so this
1830 1830 could be rewritten to use it (patches welcome).
1831 1831
1832 1832 Some examples:
1833 1833
1834 1834 In [1]: time 2**128
1835 1835 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1836 1836 Wall time: 0.00
1837 1837 Out[1]: 340282366920938463463374607431768211456L
1838 1838
1839 1839 In [2]: n = 1000000
1840 1840
1841 1841 In [3]: time sum(range(n))
1842 1842 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1843 1843 Wall time: 1.37
1844 1844 Out[3]: 499999500000L
1845 1845
1846 1846 In [4]: time print 'hello world'
1847 1847 hello world
1848 1848 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1849 1849 Wall time: 0.00
1850 1850
1851 1851 Note that the time needed by Python to compile the given expression
1852 1852 will be reported if it is more than 0.1s. In this example, the
1853 1853 actual exponentiation is done by Python at compilation time, so while
1854 1854 the expression can take a noticeable amount of time to compute, that
1855 1855 time is purely due to the compilation:
1856 1856
1857 1857 In [5]: time 3**9999;
1858 1858 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1859 1859 Wall time: 0.00 s
1860 1860
1861 1861 In [6]: time 3**999999;
1862 1862 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1863 1863 Wall time: 0.00 s
1864 1864 Compiler : 0.78 s
1865 1865 """
1866 1866
1867 1867 # fail immediately if the given expression can't be compiled
1868 1868
1869 1869 expr = self.shell.prefilter(parameter_s,False)
1870 1870
1871 1871 # Minimum time above which compilation time will be reported
1872 1872 tc_min = 0.1
1873 1873
1874 1874 try:
1875 1875 mode = 'eval'
1876 1876 t0 = clock()
1877 1877 code = compile(expr,'<timed eval>',mode)
1878 1878 tc = clock()-t0
1879 1879 except SyntaxError:
1880 1880 mode = 'exec'
1881 1881 t0 = clock()
1882 1882 code = compile(expr,'<timed exec>',mode)
1883 1883 tc = clock()-t0
1884 1884 # skew measurement as little as possible
1885 1885 glob = self.shell.user_ns
1886 1886 clk = clock2
1887 1887 wtime = time.time
1888 1888 # time execution
1889 1889 wall_st = wtime()
1890 1890 if mode=='eval':
1891 1891 st = clk()
1892 1892 out = eval(code,glob)
1893 1893 end = clk()
1894 1894 else:
1895 1895 st = clk()
1896 1896 exec code in glob
1897 1897 end = clk()
1898 1898 out = None
1899 1899 wall_end = wtime()
1900 1900 # Compute actual times and report
1901 1901 wall_time = wall_end-wall_st
1902 1902 cpu_user = end[0]-st[0]
1903 1903 cpu_sys = end[1]-st[1]
1904 1904 cpu_tot = cpu_user+cpu_sys
1905 1905 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1906 1906 (cpu_user,cpu_sys,cpu_tot)
1907 1907 print "Wall time: %.2f s" % wall_time
1908 1908 if tc > tc_min:
1909 1909 print "Compiler : %.2f s" % tc
1910 1910 return out
1911 1911
1912 1912 @testdec.skip_doctest
1913 1913 def magic_macro(self,parameter_s = ''):
1914 1914 """Define a set of input lines as a macro for future re-execution.
1915 1915
1916 1916 Usage:\\
1917 1917 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1918 1918
1919 1919 Options:
1920 1920
1921 1921 -r: use 'raw' input. By default, the 'processed' history is used,
1922 1922 so that magics are loaded in their transformed version to valid
1923 1923 Python. If this option is given, the raw input as typed as the
1924 1924 command line is used instead.
1925 1925
1926 1926 This will define a global variable called `name` which is a string
1927 1927 made of joining the slices and lines you specify (n1,n2,... numbers
1928 1928 above) from your input history into a single string. This variable
1929 1929 acts like an automatic function which re-executes those lines as if
1930 1930 you had typed them. You just type 'name' at the prompt and the code
1931 1931 executes.
1932 1932
1933 1933 The notation for indicating number ranges is: n1-n2 means 'use line
1934 1934 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1935 1935 using the lines numbered 5,6 and 7.
1936 1936
1937 1937 Note: as a 'hidden' feature, you can also use traditional python slice
1938 1938 notation, where N:M means numbers N through M-1.
1939 1939
1940 1940 For example, if your history contains (%hist prints it):
1941 1941
1942 1942 44: x=1
1943 1943 45: y=3
1944 1944 46: z=x+y
1945 1945 47: print x
1946 1946 48: a=5
1947 1947 49: print 'x',x,'y',y
1948 1948
1949 1949 you can create a macro with lines 44 through 47 (included) and line 49
1950 1950 called my_macro with:
1951 1951
1952 1952 In [55]: %macro my_macro 44-47 49
1953 1953
1954 1954 Now, typing `my_macro` (without quotes) will re-execute all this code
1955 1955 in one pass.
1956 1956
1957 1957 You don't need to give the line-numbers in order, and any given line
1958 1958 number can appear multiple times. You can assemble macros with any
1959 1959 lines from your input history in any order.
1960 1960
1961 1961 The macro is a simple object which holds its value in an attribute,
1962 1962 but IPython's display system checks for macros and executes them as
1963 1963 code instead of printing them when you type their name.
1964 1964
1965 1965 You can view a macro's contents by explicitly printing it with:
1966 1966
1967 1967 'print macro_name'.
1968 1968
1969 1969 For one-off cases which DON'T contain magic function calls in them you
1970 1970 can obtain similar results by explicitly executing slices from your
1971 1971 input history with:
1972 1972
1973 1973 In [60]: exec In[44:48]+In[49]"""
1974 1974
1975 1975 opts,args = self.parse_options(parameter_s,'r',mode='list')
1976 1976 if not args:
1977 1977 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1978 1978 macs.sort()
1979 1979 return macs
1980 1980 if len(args) == 1:
1981 1981 raise UsageError(
1982 1982 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1983 1983 name,ranges = args[0], args[1:]
1984 1984
1985 1985 #print 'rng',ranges # dbg
1986 1986 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1987 1987 macro = Macro(lines)
1988 1988 self.shell.define_macro(name, macro)
1989 1989 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1990 1990 print 'Macro contents:'
1991 1991 print macro,
1992 1992
1993 1993 def magic_save(self,parameter_s = ''):
1994 1994 """Save a set of lines to a given filename.
1995 1995
1996 1996 Usage:\\
1997 1997 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1998 1998
1999 1999 Options:
2000 2000
2001 2001 -r: use 'raw' input. By default, the 'processed' history is used,
2002 2002 so that magics are loaded in their transformed version to valid
2003 2003 Python. If this option is given, the raw input as typed as the
2004 2004 command line is used instead.
2005 2005
2006 2006 This function uses the same syntax as %macro for line extraction, but
2007 2007 instead of creating a macro it saves the resulting string to the
2008 2008 filename you specify.
2009 2009
2010 2010 It adds a '.py' extension to the file if you don't do so yourself, and
2011 2011 it asks for confirmation before overwriting existing files."""
2012 2012
2013 2013 opts,args = self.parse_options(parameter_s,'r',mode='list')
2014 2014 fname,ranges = args[0], args[1:]
2015 2015 if not fname.endswith('.py'):
2016 2016 fname += '.py'
2017 2017 if os.path.isfile(fname):
2018 2018 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2019 2019 if ans.lower() not in ['y','yes']:
2020 2020 print 'Operation cancelled.'
2021 2021 return
2022 2022 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2023 2023 f = file(fname,'w')
2024 2024 f.write(cmds)
2025 2025 f.close()
2026 2026 print 'The following commands were written to file `%s`:' % fname
2027 2027 print cmds
2028 2028
2029 2029 def _edit_macro(self,mname,macro):
2030 2030 """open an editor with the macro data in a file"""
2031 2031 filename = self.shell.mktempfile(macro.value)
2032 2032 self.shell.hooks.editor(filename)
2033 2033
2034 2034 # and make a new macro object, to replace the old one
2035 2035 mfile = open(filename)
2036 2036 mvalue = mfile.read()
2037 2037 mfile.close()
2038 2038 self.shell.user_ns[mname] = Macro(mvalue)
2039 2039
2040 2040 def magic_ed(self,parameter_s=''):
2041 2041 """Alias to %edit."""
2042 2042 return self.magic_edit(parameter_s)
2043 2043
2044 2044 @testdec.skip_doctest
2045 2045 def magic_edit(self,parameter_s='',last_call=['','']):
2046 2046 """Bring up an editor and execute the resulting code.
2047 2047
2048 2048 Usage:
2049 2049 %edit [options] [args]
2050 2050
2051 2051 %edit runs IPython's editor hook. The default version of this hook is
2052 2052 set to call the __IPYTHON__.rc.editor command. This is read from your
2053 2053 environment variable $EDITOR. If this isn't found, it will default to
2054 2054 vi under Linux/Unix and to notepad under Windows. See the end of this
2055 2055 docstring for how to change the editor hook.
2056 2056
2057 2057 You can also set the value of this editor via the command line option
2058 2058 '-editor' or in your ipythonrc file. This is useful if you wish to use
2059 2059 specifically for IPython an editor different from your typical default
2060 2060 (and for Windows users who typically don't set environment variables).
2061 2061
2062 2062 This command allows you to conveniently edit multi-line code right in
2063 2063 your IPython session.
2064 2064
2065 2065 If called without arguments, %edit opens up an empty editor with a
2066 2066 temporary file and will execute the contents of this file when you
2067 2067 close it (don't forget to save it!).
2068 2068
2069 2069
2070 2070 Options:
2071 2071
2072 2072 -n <number>: open the editor at a specified line number. By default,
2073 2073 the IPython editor hook uses the unix syntax 'editor +N filename', but
2074 2074 you can configure this by providing your own modified hook if your
2075 2075 favorite editor supports line-number specifications with a different
2076 2076 syntax.
2077 2077
2078 2078 -p: this will call the editor with the same data as the previous time
2079 2079 it was used, regardless of how long ago (in your current session) it
2080 2080 was.
2081 2081
2082 2082 -r: use 'raw' input. This option only applies to input taken from the
2083 2083 user's history. By default, the 'processed' history is used, so that
2084 2084 magics are loaded in their transformed version to valid Python. If
2085 2085 this option is given, the raw input as typed as the command line is
2086 2086 used instead. When you exit the editor, it will be executed by
2087 2087 IPython's own processor.
2088 2088
2089 2089 -x: do not execute the edited code immediately upon exit. This is
2090 2090 mainly useful if you are editing programs which need to be called with
2091 2091 command line arguments, which you can then do using %run.
2092 2092
2093 2093
2094 2094 Arguments:
2095 2095
2096 2096 If arguments are given, the following possibilites exist:
2097 2097
2098 2098 - The arguments are numbers or pairs of colon-separated numbers (like
2099 2099 1 4:8 9). These are interpreted as lines of previous input to be
2100 2100 loaded into the editor. The syntax is the same of the %macro command.
2101 2101
2102 2102 - If the argument doesn't start with a number, it is evaluated as a
2103 2103 variable and its contents loaded into the editor. You can thus edit
2104 2104 any string which contains python code (including the result of
2105 2105 previous edits).
2106 2106
2107 2107 - If the argument is the name of an object (other than a string),
2108 2108 IPython will try to locate the file where it was defined and open the
2109 2109 editor at the point where it is defined. You can use `%edit function`
2110 2110 to load an editor exactly at the point where 'function' is defined,
2111 2111 edit it and have the file be executed automatically.
2112 2112
2113 2113 If the object is a macro (see %macro for details), this opens up your
2114 2114 specified editor with a temporary file containing the macro's data.
2115 2115 Upon exit, the macro is reloaded with the contents of the file.
2116 2116
2117 2117 Note: opening at an exact line is only supported under Unix, and some
2118 2118 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2119 2119 '+NUMBER' parameter necessary for this feature. Good editors like
2120 2120 (X)Emacs, vi, jed, pico and joe all do.
2121 2121
2122 2122 - If the argument is not found as a variable, IPython will look for a
2123 2123 file with that name (adding .py if necessary) and load it into the
2124 2124 editor. It will execute its contents with execfile() when you exit,
2125 2125 loading any code in the file into your interactive namespace.
2126 2126
2127 2127 After executing your code, %edit will return as output the code you
2128 2128 typed in the editor (except when it was an existing file). This way
2129 2129 you can reload the code in further invocations of %edit as a variable,
2130 2130 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2131 2131 the output.
2132 2132
2133 2133 Note that %edit is also available through the alias %ed.
2134 2134
2135 2135 This is an example of creating a simple function inside the editor and
2136 2136 then modifying it. First, start up the editor:
2137 2137
2138 2138 In [1]: ed
2139 2139 Editing... done. Executing edited code...
2140 2140 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2141 2141
2142 2142 We can then call the function foo():
2143 2143
2144 2144 In [2]: foo()
2145 2145 foo() was defined in an editing session
2146 2146
2147 2147 Now we edit foo. IPython automatically loads the editor with the
2148 2148 (temporary) file where foo() was previously defined:
2149 2149
2150 2150 In [3]: ed foo
2151 2151 Editing... done. Executing edited code...
2152 2152
2153 2153 And if we call foo() again we get the modified version:
2154 2154
2155 2155 In [4]: foo()
2156 2156 foo() has now been changed!
2157 2157
2158 2158 Here is an example of how to edit a code snippet successive
2159 2159 times. First we call the editor:
2160 2160
2161 2161 In [5]: ed
2162 2162 Editing... done. Executing edited code...
2163 2163 hello
2164 2164 Out[5]: "print 'hello'n"
2165 2165
2166 2166 Now we call it again with the previous output (stored in _):
2167 2167
2168 2168 In [6]: ed _
2169 2169 Editing... done. Executing edited code...
2170 2170 hello world
2171 2171 Out[6]: "print 'hello world'n"
2172 2172
2173 2173 Now we call it with the output #8 (stored in _8, also as Out[8]):
2174 2174
2175 2175 In [7]: ed _8
2176 2176 Editing... done. Executing edited code...
2177 2177 hello again
2178 2178 Out[7]: "print 'hello again'n"
2179 2179
2180 2180
2181 2181 Changing the default editor hook:
2182 2182
2183 2183 If you wish to write your own editor hook, you can put it in a
2184 2184 configuration file which you load at startup time. The default hook
2185 2185 is defined in the IPython.core.hooks module, and you can use that as a
2186 2186 starting example for further modifications. That file also has
2187 2187 general instructions on how to set a new hook for use once you've
2188 2188 defined it."""
2189 2189
2190 2190 # FIXME: This function has become a convoluted mess. It needs a
2191 2191 # ground-up rewrite with clean, simple logic.
2192 2192
2193 2193 def make_filename(arg):
2194 2194 "Make a filename from the given args"
2195 2195 try:
2196 2196 filename = get_py_filename(arg)
2197 2197 except IOError:
2198 2198 if args.endswith('.py'):
2199 2199 filename = arg
2200 2200 else:
2201 2201 filename = None
2202 2202 return filename
2203 2203
2204 2204 # custom exceptions
2205 2205 class DataIsObject(Exception): pass
2206 2206
2207 2207 opts,args = self.parse_options(parameter_s,'prxn:')
2208 2208 # Set a few locals from the options for convenience:
2209 2209 opts_p = opts.has_key('p')
2210 2210 opts_r = opts.has_key('r')
2211 2211
2212 2212 # Default line number value
2213 2213 lineno = opts.get('n',None)
2214 2214
2215 2215 if opts_p:
2216 2216 args = '_%s' % last_call[0]
2217 2217 if not self.shell.user_ns.has_key(args):
2218 2218 args = last_call[1]
2219 2219
2220 2220 # use last_call to remember the state of the previous call, but don't
2221 2221 # let it be clobbered by successive '-p' calls.
2222 2222 try:
2223 2223 last_call[0] = self.shell.displayhook.prompt_count
2224 2224 if not opts_p:
2225 2225 last_call[1] = parameter_s
2226 2226 except:
2227 2227 pass
2228 2228
2229 2229 # by default this is done with temp files, except when the given
2230 2230 # arg is a filename
2231 2231 use_temp = 1
2232 2232
2233 2233 if re.match(r'\d',args):
2234 2234 # Mode where user specifies ranges of lines, like in %macro.
2235 2235 # This means that you can't edit files whose names begin with
2236 2236 # numbers this way. Tough.
2237 2237 ranges = args.split()
2238 2238 data = ''.join(self.extract_input_slices(ranges,opts_r))
2239 2239 elif args.endswith('.py'):
2240 2240 filename = make_filename(args)
2241 2241 data = ''
2242 2242 use_temp = 0
2243 2243 elif args:
2244 2244 try:
2245 2245 # Load the parameter given as a variable. If not a string,
2246 2246 # process it as an object instead (below)
2247 2247
2248 2248 #print '*** args',args,'type',type(args) # dbg
2249 2249 data = eval(args,self.shell.user_ns)
2250 2250 if not type(data) in StringTypes:
2251 2251 raise DataIsObject
2252 2252
2253 2253 except (NameError,SyntaxError):
2254 2254 # given argument is not a variable, try as a filename
2255 2255 filename = make_filename(args)
2256 2256 if filename is None:
2257 2257 warn("Argument given (%s) can't be found as a variable "
2258 2258 "or as a filename." % args)
2259 2259 return
2260 2260
2261 2261 data = ''
2262 2262 use_temp = 0
2263 2263 except DataIsObject:
2264 2264
2265 2265 # macros have a special edit function
2266 2266 if isinstance(data,Macro):
2267 2267 self._edit_macro(args,data)
2268 2268 return
2269 2269
2270 2270 # For objects, try to edit the file where they are defined
2271 2271 try:
2272 2272 filename = inspect.getabsfile(data)
2273 2273 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2274 2274 # class created by %edit? Try to find source
2275 2275 # by looking for method definitions instead, the
2276 2276 # __module__ in those classes is FakeModule.
2277 2277 attrs = [getattr(data, aname) for aname in dir(data)]
2278 2278 for attr in attrs:
2279 2279 if not inspect.ismethod(attr):
2280 2280 continue
2281 2281 filename = inspect.getabsfile(attr)
2282 2282 if filename and 'fakemodule' not in filename.lower():
2283 2283 # change the attribute to be the edit target instead
2284 2284 data = attr
2285 2285 break
2286 2286
2287 2287 datafile = 1
2288 2288 except TypeError:
2289 2289 filename = make_filename(args)
2290 2290 datafile = 1
2291 2291 warn('Could not find file where `%s` is defined.\n'
2292 2292 'Opening a file named `%s`' % (args,filename))
2293 2293 # Now, make sure we can actually read the source (if it was in
2294 2294 # a temp file it's gone by now).
2295 2295 if datafile:
2296 2296 try:
2297 2297 if lineno is None:
2298 2298 lineno = inspect.getsourcelines(data)[1]
2299 2299 except IOError:
2300 2300 filename = make_filename(args)
2301 2301 if filename is None:
2302 2302 warn('The file `%s` where `%s` was defined cannot '
2303 2303 'be read.' % (filename,data))
2304 2304 return
2305 2305 use_temp = 0
2306 2306 else:
2307 2307 data = ''
2308 2308
2309 2309 if use_temp:
2310 2310 filename = self.shell.mktempfile(data)
2311 2311 print 'IPython will make a temporary file named:',filename
2312 2312
2313 2313 # do actual editing here
2314 2314 print 'Editing...',
2315 2315 sys.stdout.flush()
2316 2316 try:
2317 2317 # Quote filenames that may have spaces in them
2318 2318 if ' ' in filename:
2319 2319 filename = "%s" % filename
2320 2320 self.shell.hooks.editor(filename,lineno)
2321 2321 except TryNext:
2322 2322 warn('Could not open editor')
2323 2323 return
2324 2324
2325 2325 # XXX TODO: should this be generalized for all string vars?
2326 2326 # For now, this is special-cased to blocks created by cpaste
2327 2327 if args.strip() == 'pasted_block':
2328 2328 self.shell.user_ns['pasted_block'] = file_read(filename)
2329 2329
2330 2330 if opts.has_key('x'): # -x prevents actual execution
2331 2331 print
2332 2332 else:
2333 2333 print 'done. Executing edited code...'
2334 2334 if opts_r:
2335 2335 self.shell.runlines(file_read(filename))
2336 2336 else:
2337 2337 self.shell.safe_execfile(filename,self.shell.user_ns,
2338 2338 self.shell.user_ns)
2339 2339
2340 2340
2341 2341 if use_temp:
2342 2342 try:
2343 2343 return open(filename).read()
2344 2344 except IOError,msg:
2345 2345 if msg.filename == filename:
2346 2346 warn('File not found. Did you forget to save?')
2347 2347 return
2348 2348 else:
2349 2349 self.shell.showtraceback()
2350 2350
2351 2351 def magic_xmode(self,parameter_s = ''):
2352 2352 """Switch modes for the exception handlers.
2353 2353
2354 2354 Valid modes: Plain, Context and Verbose.
2355 2355
2356 2356 If called without arguments, acts as a toggle."""
2357 2357
2358 2358 def xmode_switch_err(name):
2359 2359 warn('Error changing %s exception modes.\n%s' %
2360 2360 (name,sys.exc_info()[1]))
2361 2361
2362 2362 shell = self.shell
2363 2363 new_mode = parameter_s.strip().capitalize()
2364 2364 try:
2365 2365 shell.InteractiveTB.set_mode(mode=new_mode)
2366 2366 print 'Exception reporting mode:',shell.InteractiveTB.mode
2367 2367 except:
2368 2368 xmode_switch_err('user')
2369 2369
2370 2370 def magic_colors(self,parameter_s = ''):
2371 2371 """Switch color scheme for prompts, info system and exception handlers.
2372 2372
2373 2373 Currently implemented schemes: NoColor, Linux, LightBG.
2374 2374
2375 2375 Color scheme names are not case-sensitive."""
2376 2376
2377 2377 def color_switch_err(name):
2378 2378 warn('Error changing %s color schemes.\n%s' %
2379 2379 (name,sys.exc_info()[1]))
2380 2380
2381 2381
2382 2382 new_scheme = parameter_s.strip()
2383 2383 if not new_scheme:
2384 2384 raise UsageError(
2385 2385 "%colors: you must specify a color scheme. See '%colors?'")
2386 2386 return
2387 2387 # local shortcut
2388 2388 shell = self.shell
2389 2389
2390 2390 import IPython.utils.rlineimpl as readline
2391 2391
2392 2392 if not readline.have_readline and sys.platform == "win32":
2393 2393 msg = """\
2394 2394 Proper color support under MS Windows requires the pyreadline library.
2395 2395 You can find it at:
2396 2396 http://ipython.scipy.org/moin/PyReadline/Intro
2397 2397 Gary's readline needs the ctypes module, from:
2398 2398 http://starship.python.net/crew/theller/ctypes
2399 2399 (Note that ctypes is already part of Python versions 2.5 and newer).
2400 2400
2401 2401 Defaulting color scheme to 'NoColor'"""
2402 2402 new_scheme = 'NoColor'
2403 2403 warn(msg)
2404 2404
2405 2405 # readline option is 0
2406 2406 if not shell.has_readline:
2407 2407 new_scheme = 'NoColor'
2408 2408
2409 2409 # Set prompt colors
2410 2410 try:
2411 2411 shell.displayhook.set_colors(new_scheme)
2412 2412 except:
2413 2413 color_switch_err('prompt')
2414 2414 else:
2415 2415 shell.colors = \
2416 2416 shell.displayhook.color_table.active_scheme_name
2417 2417 # Set exception colors
2418 2418 try:
2419 2419 shell.InteractiveTB.set_colors(scheme = new_scheme)
2420 2420 shell.SyntaxTB.set_colors(scheme = new_scheme)
2421 2421 except:
2422 2422 color_switch_err('exception')
2423 2423
2424 2424 # Set info (for 'object?') colors
2425 2425 if shell.color_info:
2426 2426 try:
2427 2427 shell.inspector.set_active_scheme(new_scheme)
2428 2428 except:
2429 2429 color_switch_err('object inspector')
2430 2430 else:
2431 2431 shell.inspector.set_active_scheme('NoColor')
2432 2432
2433 2433 def magic_Pprint(self, parameter_s=''):
2434 2434 """Toggle pretty printing on/off."""
2435 2435
2436 2436 self.shell.pprint = 1 - self.shell.pprint
2437 2437 print 'Pretty printing has been turned', \
2438 2438 ['OFF','ON'][self.shell.pprint]
2439 2439
2440 2440 def magic_Exit(self, parameter_s=''):
2441 2441 """Exit IPython."""
2442 2442
2443 2443 self.shell.ask_exit()
2444 2444
2445 2445 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2446 2446 magic_exit = magic_quit = magic_Quit = magic_Exit
2447 2447
2448 2448 #......................................................................
2449 2449 # Functions to implement unix shell-type things
2450 2450
2451 2451 @testdec.skip_doctest
2452 2452 def magic_alias(self, parameter_s = ''):
2453 2453 """Define an alias for a system command.
2454 2454
2455 2455 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2456 2456
2457 2457 Then, typing 'alias_name params' will execute the system command 'cmd
2458 2458 params' (from your underlying operating system).
2459 2459
2460 2460 Aliases have lower precedence than magic functions and Python normal
2461 2461 variables, so if 'foo' is both a Python variable and an alias, the
2462 2462 alias can not be executed until 'del foo' removes the Python variable.
2463 2463
2464 2464 You can use the %l specifier in an alias definition to represent the
2465 2465 whole line when the alias is called. For example:
2466 2466
2467 2467 In [2]: alias bracket echo "Input in brackets: <%l>"
2468 2468 In [3]: bracket hello world
2469 2469 Input in brackets: <hello world>
2470 2470
2471 2471 You can also define aliases with parameters using %s specifiers (one
2472 2472 per parameter):
2473 2473
2474 2474 In [1]: alias parts echo first %s second %s
2475 2475 In [2]: %parts A B
2476 2476 first A second B
2477 2477 In [3]: %parts A
2478 2478 Incorrect number of arguments: 2 expected.
2479 2479 parts is an alias to: 'echo first %s second %s'
2480 2480
2481 2481 Note that %l and %s are mutually exclusive. You can only use one or
2482 2482 the other in your aliases.
2483 2483
2484 2484 Aliases expand Python variables just like system calls using ! or !!
2485 2485 do: all expressions prefixed with '$' get expanded. For details of
2486 2486 the semantic rules, see PEP-215:
2487 2487 http://www.python.org/peps/pep-0215.html. This is the library used by
2488 2488 IPython for variable expansion. If you want to access a true shell
2489 2489 variable, an extra $ is necessary to prevent its expansion by IPython:
2490 2490
2491 2491 In [6]: alias show echo
2492 2492 In [7]: PATH='A Python string'
2493 2493 In [8]: show $PATH
2494 2494 A Python string
2495 2495 In [9]: show $$PATH
2496 2496 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2497 2497
2498 2498 You can use the alias facility to acess all of $PATH. See the %rehash
2499 2499 and %rehashx functions, which automatically create aliases for the
2500 2500 contents of your $PATH.
2501 2501
2502 2502 If called with no parameters, %alias prints the current alias table."""
2503 2503
2504 2504 par = parameter_s.strip()
2505 2505 if not par:
2506 2506 stored = self.db.get('stored_aliases', {} )
2507 2507 aliases = sorted(self.shell.alias_manager.aliases)
2508 2508 # for k, v in stored:
2509 2509 # atab.append(k, v[0])
2510 2510
2511 2511 print "Total number of aliases:", len(aliases)
2512 2512 return aliases
2513 2513
2514 2514 # Now try to define a new one
2515 2515 try:
2516 2516 alias,cmd = par.split(None, 1)
2517 2517 except:
2518 2518 print oinspect.getdoc(self.magic_alias)
2519 2519 else:
2520 2520 self.shell.alias_manager.soft_define_alias(alias, cmd)
2521 2521 # end magic_alias
2522 2522
2523 2523 def magic_unalias(self, parameter_s = ''):
2524 2524 """Remove an alias"""
2525 2525
2526 2526 aname = parameter_s.strip()
2527 2527 self.shell.alias_manager.undefine_alias(aname)
2528 2528 stored = self.db.get('stored_aliases', {} )
2529 2529 if aname in stored:
2530 2530 print "Removing %stored alias",aname
2531 2531 del stored[aname]
2532 2532 self.db['stored_aliases'] = stored
2533 2533
2534 2534 def magic_rehashx(self, parameter_s = ''):
2535 2535 """Update the alias table with all executable files in $PATH.
2536 2536
2537 2537 This version explicitly checks that every entry in $PATH is a file
2538 2538 with execute access (os.X_OK), so it is much slower than %rehash.
2539 2539
2540 2540 Under Windows, it checks executability as a match agains a
2541 2541 '|'-separated string of extensions, stored in the IPython config
2542 2542 variable win_exec_ext. This defaults to 'exe|com|bat'.
2543 2543
2544 2544 This function also resets the root module cache of module completer,
2545 2545 used on slow filesystems.
2546 2546 """
2547 2547 from IPython.core.alias import InvalidAliasError
2548 2548
2549 2549 # for the benefit of module completer in ipy_completers.py
2550 2550 del self.db['rootmodules']
2551 2551
2552 2552 path = [os.path.abspath(os.path.expanduser(p)) for p in
2553 2553 os.environ.get('PATH','').split(os.pathsep)]
2554 2554 path = filter(os.path.isdir,path)
2555 2555
2556 2556 syscmdlist = []
2557 2557 # Now define isexec in a cross platform manner.
2558 2558 if os.name == 'posix':
2559 2559 isexec = lambda fname:os.path.isfile(fname) and \
2560 2560 os.access(fname,os.X_OK)
2561 2561 else:
2562 2562 try:
2563 2563 winext = os.environ['pathext'].replace(';','|').replace('.','')
2564 2564 except KeyError:
2565 2565 winext = 'exe|com|bat|py'
2566 2566 if 'py' not in winext:
2567 2567 winext += '|py'
2568 2568 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2569 2569 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2570 2570 savedir = os.getcwd()
2571 2571
2572 2572 # Now walk the paths looking for executables to alias.
2573 2573 try:
2574 2574 # write the whole loop for posix/Windows so we don't have an if in
2575 2575 # the innermost part
2576 2576 if os.name == 'posix':
2577 2577 for pdir in path:
2578 2578 os.chdir(pdir)
2579 2579 for ff in os.listdir(pdir):
2580 2580 if isexec(ff):
2581 2581 try:
2582 2582 # Removes dots from the name since ipython
2583 2583 # will assume names with dots to be python.
2584 2584 self.shell.alias_manager.define_alias(
2585 2585 ff.replace('.',''), ff)
2586 2586 except InvalidAliasError:
2587 2587 pass
2588 2588 else:
2589 2589 syscmdlist.append(ff)
2590 2590 else:
2591 2591 no_alias = self.shell.alias_manager.no_alias
2592 2592 for pdir in path:
2593 2593 os.chdir(pdir)
2594 2594 for ff in os.listdir(pdir):
2595 2595 base, ext = os.path.splitext(ff)
2596 2596 if isexec(ff) and base.lower() not in no_alias:
2597 2597 if ext.lower() == '.exe':
2598 2598 ff = base
2599 2599 try:
2600 2600 # Removes dots from the name since ipython
2601 2601 # will assume names with dots to be python.
2602 2602 self.shell.alias_manager.define_alias(
2603 2603 base.lower().replace('.',''), ff)
2604 2604 except InvalidAliasError:
2605 2605 pass
2606 2606 syscmdlist.append(ff)
2607 2607 db = self.db
2608 2608 db['syscmdlist'] = syscmdlist
2609 2609 finally:
2610 2610 os.chdir(savedir)
2611 2611
2612 2612 def magic_pwd(self, parameter_s = ''):
2613 2613 """Return the current working directory path."""
2614 2614 return os.getcwd()
2615 2615
2616 2616 def magic_cd(self, parameter_s=''):
2617 2617 """Change the current working directory.
2618 2618
2619 2619 This command automatically maintains an internal list of directories
2620 2620 you visit during your IPython session, in the variable _dh. The
2621 2621 command %dhist shows this history nicely formatted. You can also
2622 2622 do 'cd -<tab>' to see directory history conveniently.
2623 2623
2624 2624 Usage:
2625 2625
2626 2626 cd 'dir': changes to directory 'dir'.
2627 2627
2628 2628 cd -: changes to the last visited directory.
2629 2629
2630 2630 cd -<n>: changes to the n-th directory in the directory history.
2631 2631
2632 2632 cd --foo: change to directory that matches 'foo' in history
2633 2633
2634 2634 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2635 2635 (note: cd <bookmark_name> is enough if there is no
2636 2636 directory <bookmark_name>, but a bookmark with the name exists.)
2637 2637 'cd -b <tab>' allows you to tab-complete bookmark names.
2638 2638
2639 2639 Options:
2640 2640
2641 2641 -q: quiet. Do not print the working directory after the cd command is
2642 2642 executed. By default IPython's cd command does print this directory,
2643 2643 since the default prompts do not display path information.
2644 2644
2645 2645 Note that !cd doesn't work for this purpose because the shell where
2646 2646 !command runs is immediately discarded after executing 'command'."""
2647 2647
2648 2648 parameter_s = parameter_s.strip()
2649 2649 #bkms = self.shell.persist.get("bookmarks",{})
2650 2650
2651 2651 oldcwd = os.getcwd()
2652 2652 numcd = re.match(r'(-)(\d+)$',parameter_s)
2653 2653 # jump in directory history by number
2654 2654 if numcd:
2655 2655 nn = int(numcd.group(2))
2656 2656 try:
2657 2657 ps = self.shell.user_ns['_dh'][nn]
2658 2658 except IndexError:
2659 2659 print 'The requested directory does not exist in history.'
2660 2660 return
2661 2661 else:
2662 2662 opts = {}
2663 2663 elif parameter_s.startswith('--'):
2664 2664 ps = None
2665 2665 fallback = None
2666 2666 pat = parameter_s[2:]
2667 2667 dh = self.shell.user_ns['_dh']
2668 2668 # first search only by basename (last component)
2669 2669 for ent in reversed(dh):
2670 2670 if pat in os.path.basename(ent) and os.path.isdir(ent):
2671 2671 ps = ent
2672 2672 break
2673 2673
2674 2674 if fallback is None and pat in ent and os.path.isdir(ent):
2675 2675 fallback = ent
2676 2676
2677 2677 # if we have no last part match, pick the first full path match
2678 2678 if ps is None:
2679 2679 ps = fallback
2680 2680
2681 2681 if ps is None:
2682 2682 print "No matching entry in directory history"
2683 2683 return
2684 2684 else:
2685 2685 opts = {}
2686 2686
2687 2687
2688 2688 else:
2689 2689 #turn all non-space-escaping backslashes to slashes,
2690 2690 # for c:\windows\directory\names\
2691 2691 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2692 2692 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2693 2693 # jump to previous
2694 2694 if ps == '-':
2695 2695 try:
2696 2696 ps = self.shell.user_ns['_dh'][-2]
2697 2697 except IndexError:
2698 2698 raise UsageError('%cd -: No previous directory to change to.')
2699 2699 # jump to bookmark if needed
2700 2700 else:
2701 2701 if not os.path.isdir(ps) or opts.has_key('b'):
2702 2702 bkms = self.db.get('bookmarks', {})
2703 2703
2704 2704 if bkms.has_key(ps):
2705 2705 target = bkms[ps]
2706 2706 print '(bookmark:%s) -> %s' % (ps,target)
2707 2707 ps = target
2708 2708 else:
2709 2709 if opts.has_key('b'):
2710 2710 raise UsageError("Bookmark '%s' not found. "
2711 2711 "Use '%%bookmark -l' to see your bookmarks." % ps)
2712 2712
2713 2713 # at this point ps should point to the target dir
2714 2714 if ps:
2715 2715 try:
2716 2716 os.chdir(os.path.expanduser(ps))
2717 2717 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2718 2718 set_term_title('IPython: ' + abbrev_cwd())
2719 2719 except OSError:
2720 2720 print sys.exc_info()[1]
2721 2721 else:
2722 2722 cwd = os.getcwd()
2723 2723 dhist = self.shell.user_ns['_dh']
2724 2724 if oldcwd != cwd:
2725 2725 dhist.append(cwd)
2726 2726 self.db['dhist'] = compress_dhist(dhist)[-100:]
2727 2727
2728 2728 else:
2729 2729 os.chdir(self.shell.home_dir)
2730 2730 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2731 2731 set_term_title('IPython: ' + '~')
2732 2732 cwd = os.getcwd()
2733 2733 dhist = self.shell.user_ns['_dh']
2734 2734
2735 2735 if oldcwd != cwd:
2736 2736 dhist.append(cwd)
2737 2737 self.db['dhist'] = compress_dhist(dhist)[-100:]
2738 2738 if not 'q' in opts and self.shell.user_ns['_dh']:
2739 2739 print self.shell.user_ns['_dh'][-1]
2740 2740
2741 2741
2742 2742 def magic_env(self, parameter_s=''):
2743 2743 """List environment variables."""
2744 2744
2745 2745 return os.environ.data
2746 2746
2747 2747 def magic_pushd(self, parameter_s=''):
2748 2748 """Place the current dir on stack and change directory.
2749 2749
2750 2750 Usage:\\
2751 2751 %pushd ['dirname']
2752 2752 """
2753 2753
2754 2754 dir_s = self.shell.dir_stack
2755 2755 tgt = os.path.expanduser(parameter_s)
2756 2756 cwd = os.getcwd().replace(self.home_dir,'~')
2757 2757 if tgt:
2758 2758 self.magic_cd(parameter_s)
2759 2759 dir_s.insert(0,cwd)
2760 2760 return self.magic_dirs()
2761 2761
2762 2762 def magic_popd(self, parameter_s=''):
2763 2763 """Change to directory popped off the top of the stack.
2764 2764 """
2765 2765 if not self.shell.dir_stack:
2766 2766 raise UsageError("%popd on empty stack")
2767 2767 top = self.shell.dir_stack.pop(0)
2768 2768 self.magic_cd(top)
2769 2769 print "popd ->",top
2770 2770
2771 2771 def magic_dirs(self, parameter_s=''):
2772 2772 """Return the current directory stack."""
2773 2773
2774 2774 return self.shell.dir_stack
2775 2775
2776 2776 def magic_dhist(self, parameter_s=''):
2777 2777 """Print your history of visited directories.
2778 2778
2779 2779 %dhist -> print full history\\
2780 2780 %dhist n -> print last n entries only\\
2781 2781 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2782 2782
2783 2783 This history is automatically maintained by the %cd command, and
2784 2784 always available as the global list variable _dh. You can use %cd -<n>
2785 2785 to go to directory number <n>.
2786 2786
2787 2787 Note that most of time, you should view directory history by entering
2788 2788 cd -<TAB>.
2789 2789
2790 2790 """
2791 2791
2792 2792 dh = self.shell.user_ns['_dh']
2793 2793 if parameter_s:
2794 2794 try:
2795 2795 args = map(int,parameter_s.split())
2796 2796 except:
2797 2797 self.arg_err(Magic.magic_dhist)
2798 2798 return
2799 2799 if len(args) == 1:
2800 2800 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2801 2801 elif len(args) == 2:
2802 2802 ini,fin = args
2803 2803 else:
2804 2804 self.arg_err(Magic.magic_dhist)
2805 2805 return
2806 2806 else:
2807 2807 ini,fin = 0,len(dh)
2808 2808 nlprint(dh,
2809 2809 header = 'Directory history (kept in _dh)',
2810 2810 start=ini,stop=fin)
2811 2811
2812 2812 @testdec.skip_doctest
2813 2813 def magic_sc(self, parameter_s=''):
2814 2814 """Shell capture - execute a shell command and capture its output.
2815 2815
2816 2816 DEPRECATED. Suboptimal, retained for backwards compatibility.
2817 2817
2818 2818 You should use the form 'var = !command' instead. Example:
2819 2819
2820 2820 "%sc -l myfiles = ls ~" should now be written as
2821 2821
2822 2822 "myfiles = !ls ~"
2823 2823
2824 2824 myfiles.s, myfiles.l and myfiles.n still apply as documented
2825 2825 below.
2826 2826
2827 2827 --
2828 2828 %sc [options] varname=command
2829 2829
2830 2830 IPython will run the given command using commands.getoutput(), and
2831 2831 will then update the user's interactive namespace with a variable
2832 2832 called varname, containing the value of the call. Your command can
2833 2833 contain shell wildcards, pipes, etc.
2834 2834
2835 2835 The '=' sign in the syntax is mandatory, and the variable name you
2836 2836 supply must follow Python's standard conventions for valid names.
2837 2837
2838 2838 (A special format without variable name exists for internal use)
2839 2839
2840 2840 Options:
2841 2841
2842 2842 -l: list output. Split the output on newlines into a list before
2843 2843 assigning it to the given variable. By default the output is stored
2844 2844 as a single string.
2845 2845
2846 2846 -v: verbose. Print the contents of the variable.
2847 2847
2848 2848 In most cases you should not need to split as a list, because the
2849 2849 returned value is a special type of string which can automatically
2850 2850 provide its contents either as a list (split on newlines) or as a
2851 2851 space-separated string. These are convenient, respectively, either
2852 2852 for sequential processing or to be passed to a shell command.
2853 2853
2854 2854 For example:
2855 2855
2856 2856 # all-random
2857 2857
2858 2858 # Capture into variable a
2859 2859 In [1]: sc a=ls *py
2860 2860
2861 2861 # a is a string with embedded newlines
2862 2862 In [2]: a
2863 2863 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2864 2864
2865 2865 # which can be seen as a list:
2866 2866 In [3]: a.l
2867 2867 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2868 2868
2869 2869 # or as a whitespace-separated string:
2870 2870 In [4]: a.s
2871 2871 Out[4]: 'setup.py win32_manual_post_install.py'
2872 2872
2873 2873 # a.s is useful to pass as a single command line:
2874 2874 In [5]: !wc -l $a.s
2875 2875 146 setup.py
2876 2876 130 win32_manual_post_install.py
2877 2877 276 total
2878 2878
2879 2879 # while the list form is useful to loop over:
2880 2880 In [6]: for f in a.l:
2881 2881 ...: !wc -l $f
2882 2882 ...:
2883 2883 146 setup.py
2884 2884 130 win32_manual_post_install.py
2885 2885
2886 2886 Similiarly, the lists returned by the -l option are also special, in
2887 2887 the sense that you can equally invoke the .s attribute on them to
2888 2888 automatically get a whitespace-separated string from their contents:
2889 2889
2890 2890 In [7]: sc -l b=ls *py
2891 2891
2892 2892 In [8]: b
2893 2893 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2894 2894
2895 2895 In [9]: b.s
2896 2896 Out[9]: 'setup.py win32_manual_post_install.py'
2897 2897
2898 2898 In summary, both the lists and strings used for ouptut capture have
2899 2899 the following special attributes:
2900 2900
2901 2901 .l (or .list) : value as list.
2902 2902 .n (or .nlstr): value as newline-separated string.
2903 2903 .s (or .spstr): value as space-separated string.
2904 2904 """
2905 2905
2906 2906 opts,args = self.parse_options(parameter_s,'lv')
2907 2907 # Try to get a variable name and command to run
2908 2908 try:
2909 2909 # the variable name must be obtained from the parse_options
2910 2910 # output, which uses shlex.split to strip options out.
2911 2911 var,_ = args.split('=',1)
2912 2912 var = var.strip()
2913 2913 # But the the command has to be extracted from the original input
2914 2914 # parameter_s, not on what parse_options returns, to avoid the
2915 2915 # quote stripping which shlex.split performs on it.
2916 2916 _,cmd = parameter_s.split('=',1)
2917 2917 except ValueError:
2918 2918 var,cmd = '',''
2919 2919 # If all looks ok, proceed
2920 2920 out = self.shell.getoutput(cmd)
2921 2921 if opts.has_key('l'):
2922 out = SList(out.split('\n'))
2922 out = SList(out.splitlines())
2923 2923 else:
2924 2924 out = LSString(out)
2925 2925 if opts.has_key('v'):
2926 2926 print '%s ==\n%s' % (var,pformat(out))
2927 2927 if var:
2928 2928 self.shell.user_ns.update({var:out})
2929 2929 else:
2930 2930 return out
2931 2931
2932 2932 def magic_sx(self, parameter_s=''):
2933 2933 """Shell execute - run a shell command and capture its output.
2934 2934
2935 2935 %sx command
2936 2936
2937 2937 IPython will run the given command using commands.getoutput(), and
2938 2938 return the result formatted as a list (split on '\\n'). Since the
2939 2939 output is _returned_, it will be stored in ipython's regular output
2940 2940 cache Out[N] and in the '_N' automatic variables.
2941 2941
2942 2942 Notes:
2943 2943
2944 2944 1) If an input line begins with '!!', then %sx is automatically
2945 2945 invoked. That is, while:
2946 2946 !ls
2947 2947 causes ipython to simply issue system('ls'), typing
2948 2948 !!ls
2949 2949 is a shorthand equivalent to:
2950 2950 %sx ls
2951 2951
2952 2952 2) %sx differs from %sc in that %sx automatically splits into a list,
2953 2953 like '%sc -l'. The reason for this is to make it as easy as possible
2954 2954 to process line-oriented shell output via further python commands.
2955 2955 %sc is meant to provide much finer control, but requires more
2956 2956 typing.
2957 2957
2958 2958 3) Just like %sc -l, this is a list with special attributes:
2959 2959
2960 2960 .l (or .list) : value as list.
2961 2961 .n (or .nlstr): value as newline-separated string.
2962 2962 .s (or .spstr): value as whitespace-separated string.
2963 2963
2964 2964 This is very useful when trying to use such lists as arguments to
2965 2965 system commands."""
2966 2966
2967 2967 if parameter_s:
2968 2968 out = self.shell.getoutput(parameter_s)
2969 2969 if out is not None:
2970 2970 return SList(out.splitlines())
2971 2971
2972 2972 def magic_r(self, parameter_s=''):
2973 2973 """Repeat previous input.
2974 2974
2975 2975 Note: Consider using the more powerfull %rep instead!
2976 2976
2977 2977 If given an argument, repeats the previous command which starts with
2978 2978 the same string, otherwise it just repeats the previous input.
2979 2979
2980 2980 Shell escaped commands (with ! as first character) are not recognized
2981 2981 by this system, only pure python code and magic commands.
2982 2982 """
2983 2983
2984 2984 start = parameter_s.strip()
2985 2985 esc_magic = ESC_MAGIC
2986 2986 # Identify magic commands even if automagic is on (which means
2987 2987 # the in-memory version is different from that typed by the user).
2988 2988 if self.shell.automagic:
2989 2989 start_magic = esc_magic+start
2990 2990 else:
2991 2991 start_magic = start
2992 2992 # Look through the input history in reverse
2993 2993 for n in range(len(self.shell.input_hist)-2,0,-1):
2994 2994 input = self.shell.input_hist[n]
2995 2995 # skip plain 'r' lines so we don't recurse to infinity
2996 2996 if input != '_ip.magic("r")\n' and \
2997 2997 (input.startswith(start) or input.startswith(start_magic)):
2998 2998 #print 'match',`input` # dbg
2999 2999 print 'Executing:',input,
3000 3000 self.shell.runlines(input)
3001 3001 return
3002 3002 print 'No previous input matching `%s` found.' % start
3003 3003
3004 3004
3005 3005 def magic_bookmark(self, parameter_s=''):
3006 3006 """Manage IPython's bookmark system.
3007 3007
3008 3008 %bookmark <name> - set bookmark to current dir
3009 3009 %bookmark <name> <dir> - set bookmark to <dir>
3010 3010 %bookmark -l - list all bookmarks
3011 3011 %bookmark -d <name> - remove bookmark
3012 3012 %bookmark -r - remove all bookmarks
3013 3013
3014 3014 You can later on access a bookmarked folder with:
3015 3015 %cd -b <name>
3016 3016 or simply '%cd <name>' if there is no directory called <name> AND
3017 3017 there is such a bookmark defined.
3018 3018
3019 3019 Your bookmarks persist through IPython sessions, but they are
3020 3020 associated with each profile."""
3021 3021
3022 3022 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3023 3023 if len(args) > 2:
3024 3024 raise UsageError("%bookmark: too many arguments")
3025 3025
3026 3026 bkms = self.db.get('bookmarks',{})
3027 3027
3028 3028 if opts.has_key('d'):
3029 3029 try:
3030 3030 todel = args[0]
3031 3031 except IndexError:
3032 3032 raise UsageError(
3033 3033 "%bookmark -d: must provide a bookmark to delete")
3034 3034 else:
3035 3035 try:
3036 3036 del bkms[todel]
3037 3037 except KeyError:
3038 3038 raise UsageError(
3039 3039 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3040 3040
3041 3041 elif opts.has_key('r'):
3042 3042 bkms = {}
3043 3043 elif opts.has_key('l'):
3044 3044 bks = bkms.keys()
3045 3045 bks.sort()
3046 3046 if bks:
3047 3047 size = max(map(len,bks))
3048 3048 else:
3049 3049 size = 0
3050 3050 fmt = '%-'+str(size)+'s -> %s'
3051 3051 print 'Current bookmarks:'
3052 3052 for bk in bks:
3053 3053 print fmt % (bk,bkms[bk])
3054 3054 else:
3055 3055 if not args:
3056 3056 raise UsageError("%bookmark: You must specify the bookmark name")
3057 3057 elif len(args)==1:
3058 3058 bkms[args[0]] = os.getcwd()
3059 3059 elif len(args)==2:
3060 3060 bkms[args[0]] = args[1]
3061 3061 self.db['bookmarks'] = bkms
3062 3062
3063 3063 def magic_pycat(self, parameter_s=''):
3064 3064 """Show a syntax-highlighted file through a pager.
3065 3065
3066 3066 This magic is similar to the cat utility, but it will assume the file
3067 3067 to be Python source and will show it with syntax highlighting. """
3068 3068
3069 3069 try:
3070 3070 filename = get_py_filename(parameter_s)
3071 3071 cont = file_read(filename)
3072 3072 except IOError:
3073 3073 try:
3074 3074 cont = eval(parameter_s,self.user_ns)
3075 3075 except NameError:
3076 3076 cont = None
3077 3077 if cont is None:
3078 3078 print "Error: no such file or variable"
3079 3079 return
3080 3080
3081 3081 page.page(self.shell.pycolorize(cont))
3082 3082
3083 3083 def _rerun_pasted(self):
3084 3084 """ Rerun a previously pasted command.
3085 3085 """
3086 3086 b = self.user_ns.get('pasted_block', None)
3087 3087 if b is None:
3088 3088 raise UsageError('No previous pasted block available')
3089 3089 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3090 3090 exec b in self.user_ns
3091 3091
3092 3092 def _get_pasted_lines(self, sentinel):
3093 3093 """ Yield pasted lines until the user enters the given sentinel value.
3094 3094 """
3095 3095 from IPython.core import interactiveshell
3096 3096 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3097 3097 while True:
3098 3098 l = interactiveshell.raw_input_original(':')
3099 3099 if l == sentinel:
3100 3100 return
3101 3101 else:
3102 3102 yield l
3103 3103
3104 3104 def _strip_pasted_lines_for_code(self, raw_lines):
3105 3105 """ Strip non-code parts of a sequence of lines to return a block of
3106 3106 code.
3107 3107 """
3108 3108 # Regular expressions that declare text we strip from the input:
3109 3109 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3110 3110 r'^\s*(\s?>)+', # Python input prompt
3111 3111 r'^\s*\.{3,}', # Continuation prompts
3112 3112 r'^\++',
3113 3113 ]
3114 3114
3115 3115 strip_from_start = map(re.compile,strip_re)
3116 3116
3117 3117 lines = []
3118 3118 for l in raw_lines:
3119 3119 for pat in strip_from_start:
3120 3120 l = pat.sub('',l)
3121 3121 lines.append(l)
3122 3122
3123 3123 block = "\n".join(lines) + '\n'
3124 3124 #print "block:\n",block
3125 3125 return block
3126 3126
3127 3127 def _execute_block(self, block, par):
3128 3128 """ Execute a block, or store it in a variable, per the user's request.
3129 3129 """
3130 3130 if not par:
3131 3131 b = textwrap.dedent(block)
3132 3132 self.user_ns['pasted_block'] = b
3133 3133 exec b in self.user_ns
3134 3134 else:
3135 3135 self.user_ns[par] = SList(block.splitlines())
3136 3136 print "Block assigned to '%s'" % par
3137 3137
3138 3138 def magic_quickref(self,arg):
3139 3139 """ Show a quick reference sheet """
3140 3140 import IPython.core.usage
3141 3141 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3142 3142
3143 3143 page.page(qr)
3144 3144
3145 3145 def magic_doctest_mode(self,parameter_s=''):
3146 3146 """Toggle doctest mode on and off.
3147 3147
3148 3148 This mode is intended to make IPython behave as much as possible like a
3149 3149 plain Python shell, from the perspective of how its prompts, exceptions
3150 3150 and output look. This makes it easy to copy and paste parts of a
3151 3151 session into doctests. It does so by:
3152 3152
3153 3153 - Changing the prompts to the classic ``>>>`` ones.
3154 3154 - Changing the exception reporting mode to 'Plain'.
3155 3155 - Disabling pretty-printing of output.
3156 3156
3157 3157 Note that IPython also supports the pasting of code snippets that have
3158 3158 leading '>>>' and '...' prompts in them. This means that you can paste
3159 3159 doctests from files or docstrings (even if they have leading
3160 3160 whitespace), and the code will execute correctly. You can then use
3161 3161 '%history -t' to see the translated history; this will give you the
3162 3162 input after removal of all the leading prompts and whitespace, which
3163 3163 can be pasted back into an editor.
3164 3164
3165 3165 With these features, you can switch into this mode easily whenever you
3166 3166 need to do testing and changes to doctests, without having to leave
3167 3167 your existing IPython session.
3168 3168 """
3169 3169
3170 3170 from IPython.utils.ipstruct import Struct
3171 3171
3172 3172 # Shorthands
3173 3173 shell = self.shell
3174 3174 oc = shell.displayhook
3175 3175 meta = shell.meta
3176 3176 # dstore is a data store kept in the instance metadata bag to track any
3177 3177 # changes we make, so we can undo them later.
3178 3178 dstore = meta.setdefault('doctest_mode',Struct())
3179 3179 save_dstore = dstore.setdefault
3180 3180
3181 3181 # save a few values we'll need to recover later
3182 3182 mode = save_dstore('mode',False)
3183 3183 save_dstore('rc_pprint',shell.pprint)
3184 3184 save_dstore('xmode',shell.InteractiveTB.mode)
3185 3185 save_dstore('rc_separate_out',shell.separate_out)
3186 3186 save_dstore('rc_separate_out2',shell.separate_out2)
3187 3187 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3188 3188 save_dstore('rc_separate_in',shell.separate_in)
3189 3189
3190 3190 if mode == False:
3191 3191 # turn on
3192 3192 oc.prompt1.p_template = '>>> '
3193 3193 oc.prompt2.p_template = '... '
3194 3194 oc.prompt_out.p_template = ''
3195 3195
3196 3196 # Prompt separators like plain python
3197 3197 oc.input_sep = oc.prompt1.sep = ''
3198 3198 oc.output_sep = ''
3199 3199 oc.output_sep2 = ''
3200 3200
3201 3201 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3202 3202 oc.prompt_out.pad_left = False
3203 3203
3204 3204 shell.pprint = False
3205 3205
3206 3206 shell.magic_xmode('Plain')
3207 3207 else:
3208 3208 # turn off
3209 3209 oc.prompt1.p_template = shell.prompt_in1
3210 3210 oc.prompt2.p_template = shell.prompt_in2
3211 3211 oc.prompt_out.p_template = shell.prompt_out
3212 3212
3213 3213 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3214 3214
3215 3215 oc.output_sep = dstore.rc_separate_out
3216 3216 oc.output_sep2 = dstore.rc_separate_out2
3217 3217
3218 3218 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3219 3219 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3220 3220
3221 3221 shell.pprint = dstore.rc_pprint
3222 3222
3223 3223 shell.magic_xmode(dstore.xmode)
3224 3224
3225 3225 # Store new mode and inform
3226 3226 dstore.mode = bool(1-int(mode))
3227 3227 mode_label = ['OFF','ON'][dstore.mode]
3228 3228 print 'Doctest mode is:', mode_label
3229 3229
3230 3230 def magic_gui(self, parameter_s=''):
3231 3231 """Enable or disable IPython GUI event loop integration.
3232 3232
3233 3233 %gui [GUINAME]
3234 3234
3235 3235 This magic replaces IPython's threaded shells that were activated
3236 3236 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3237 3237 can now be enabled, disabled and swtiched at runtime and keyboard
3238 3238 interrupts should work without any problems. The following toolkits
3239 3239 are supported: wxPython, PyQt4, PyGTK, and Tk::
3240 3240
3241 3241 %gui wx # enable wxPython event loop integration
3242 3242 %gui qt4|qt # enable PyQt4 event loop integration
3243 3243 %gui gtk # enable PyGTK event loop integration
3244 3244 %gui tk # enable Tk event loop integration
3245 3245 %gui # disable all event loop integration
3246 3246
3247 3247 WARNING: after any of these has been called you can simply create
3248 3248 an application object, but DO NOT start the event loop yourself, as
3249 3249 we have already handled that.
3250 3250 """
3251 3251 from IPython.lib.inputhook import enable_gui
3252 3252 opts, arg = self.parse_options(parameter_s='')
3253 3253 if arg=='': arg = None
3254 3254 return enable_gui(arg)
3255 3255
3256 3256 def magic_load_ext(self, module_str):
3257 3257 """Load an IPython extension by its module name."""
3258 3258 return self.extension_manager.load_extension(module_str)
3259 3259
3260 3260 def magic_unload_ext(self, module_str):
3261 3261 """Unload an IPython extension by its module name."""
3262 3262 self.extension_manager.unload_extension(module_str)
3263 3263
3264 3264 def magic_reload_ext(self, module_str):
3265 3265 """Reload an IPython extension by its module name."""
3266 3266 self.extension_manager.reload_extension(module_str)
3267 3267
3268 3268 @testdec.skip_doctest
3269 3269 def magic_install_profiles(self, s):
3270 3270 """Install the default IPython profiles into the .ipython dir.
3271 3271
3272 3272 If the default profiles have already been installed, they will not
3273 3273 be overwritten. You can force overwriting them by using the ``-o``
3274 3274 option::
3275 3275
3276 3276 In [1]: %install_profiles -o
3277 3277 """
3278 3278 if '-o' in s:
3279 3279 overwrite = True
3280 3280 else:
3281 3281 overwrite = False
3282 3282 from IPython.config import profile
3283 3283 profile_dir = os.path.split(profile.__file__)[0]
3284 3284 ipython_dir = self.ipython_dir
3285 3285 files = os.listdir(profile_dir)
3286 3286
3287 3287 to_install = []
3288 3288 for f in files:
3289 3289 if f.startswith('ipython_config'):
3290 3290 src = os.path.join(profile_dir, f)
3291 3291 dst = os.path.join(ipython_dir, f)
3292 3292 if (not os.path.isfile(dst)) or overwrite:
3293 3293 to_install.append((f, src, dst))
3294 3294 if len(to_install)>0:
3295 3295 print "Installing profiles to: ", ipython_dir
3296 3296 for (f, src, dst) in to_install:
3297 3297 shutil.copy(src, dst)
3298 3298 print " %s" % f
3299 3299
3300 3300 def magic_install_default_config(self, s):
3301 3301 """Install IPython's default config file into the .ipython dir.
3302 3302
3303 3303 If the default config file (:file:`ipython_config.py`) is already
3304 3304 installed, it will not be overwritten. You can force overwriting
3305 3305 by using the ``-o`` option::
3306 3306
3307 3307 In [1]: %install_default_config
3308 3308 """
3309 3309 if '-o' in s:
3310 3310 overwrite = True
3311 3311 else:
3312 3312 overwrite = False
3313 3313 from IPython.config import default
3314 3314 config_dir = os.path.split(default.__file__)[0]
3315 3315 ipython_dir = self.ipython_dir
3316 3316 default_config_file_name = 'ipython_config.py'
3317 3317 src = os.path.join(config_dir, default_config_file_name)
3318 3318 dst = os.path.join(ipython_dir, default_config_file_name)
3319 3319 if (not os.path.isfile(dst)) or overwrite:
3320 3320 shutil.copy(src, dst)
3321 3321 print "Installing default config file: %s" % dst
3322 3322
3323 3323 # Pylab support: simple wrappers that activate pylab, load gui input
3324 3324 # handling and modify slightly %run
3325 3325
3326 3326 @testdec.skip_doctest
3327 3327 def _pylab_magic_run(self, parameter_s=''):
3328 3328 Magic.magic_run(self, parameter_s,
3329 3329 runner=mpl_runner(self.shell.safe_execfile))
3330 3330
3331 3331 _pylab_magic_run.__doc__ = magic_run.__doc__
3332 3332
3333 3333 @testdec.skip_doctest
3334 3334 def magic_pylab(self, s):
3335 3335 """Load numpy and matplotlib to work interactively.
3336 3336
3337 3337 %pylab [GUINAME]
3338 3338
3339 3339 This function lets you activate pylab (matplotlib, numpy and
3340 3340 interactive support) at any point during an IPython session.
3341 3341
3342 3342 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3343 3343 pylab and mlab, as well as all names from numpy and pylab.
3344 3344
3345 3345 Parameters
3346 3346 ----------
3347 3347 guiname : optional
3348 3348 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3349 3349 'tk'). If given, the corresponding Matplotlib backend is used,
3350 3350 otherwise matplotlib's default (which you can override in your
3351 3351 matplotlib config file) is used.
3352 3352
3353 3353 Examples
3354 3354 --------
3355 3355 In this case, where the MPL default is TkAgg:
3356 3356 In [2]: %pylab
3357 3357
3358 3358 Welcome to pylab, a matplotlib-based Python environment.
3359 3359 Backend in use: TkAgg
3360 3360 For more information, type 'help(pylab)'.
3361 3361
3362 3362 But you can explicitly request a different backend:
3363 3363 In [3]: %pylab qt
3364 3364
3365 3365 Welcome to pylab, a matplotlib-based Python environment.
3366 3366 Backend in use: Qt4Agg
3367 3367 For more information, type 'help(pylab)'.
3368 3368 """
3369 3369 self.shell.enable_pylab(s)
3370 3370
3371 3371 def magic_tb(self, s):
3372 3372 """Print the last traceback with the currently active exception mode.
3373 3373
3374 3374 See %xmode for changing exception reporting modes."""
3375 3375 self.shell.showtraceback()
3376 3376
3377 3377 # end Magic
@@ -1,1014 +1,1014 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Prefiltering components.
5 5
6 6 Prefilters transform user input before it is exec'd by Python. These
7 7 transforms are used to implement additional syntax such as !ls and %magic.
8 8
9 9 Authors:
10 10
11 11 * Brian Granger
12 12 * Fernando Perez
13 13 * Dan Milstein
14 14 * Ville Vainio
15 15 """
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Copyright (C) 2008-2009 The IPython Development Team
19 19 #
20 20 # Distributed under the terms of the BSD License. The full license is in
21 21 # the file COPYING, distributed as part of this software.
22 22 #-----------------------------------------------------------------------------
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Imports
26 26 #-----------------------------------------------------------------------------
27 27
28 28 import __builtin__
29 29 import codeop
30 30 import re
31 31
32 32 from IPython.core.alias import AliasManager
33 33 from IPython.core.autocall import IPyAutocall
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core.splitinput import split_user_input
36 36 from IPython.core import page
37 37
38 38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 39 import IPython.utils.io
40 40 from IPython.utils.text import make_quoted_expr
41 41 from IPython.utils.autoattr import auto_attr
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Global utilities, errors and constants
45 45 #-----------------------------------------------------------------------------
46 46
47 47 # Warning, these cannot be changed unless various regular expressions
48 48 # are updated in a number of places. Not great, but at least we told you.
49 49 ESC_SHELL = '!'
50 50 ESC_SH_CAP = '!!'
51 51 ESC_HELP = '?'
52 52 ESC_MAGIC = '%'
53 53 ESC_QUOTE = ','
54 54 ESC_QUOTE2 = ';'
55 55 ESC_PAREN = '/'
56 56
57 57
58 58 class PrefilterError(Exception):
59 59 pass
60 60
61 61
62 62 # RegExp to identify potential function names
63 63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64 64
65 65 # RegExp to exclude strings with this start from autocalling. In
66 66 # particular, all binary operators should be excluded, so that if foo is
67 67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 69 # routine explicitely does so, to catch direct calls and rebindings of
70 70 # existing names.
71 71
72 72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 73 # it affects the rest of the group in square brackets.
74 74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 75 r'|^is |^not |^in |^and |^or ')
76 76
77 77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 78 # (experimental). For this to work, the line_split regexp would need
79 79 # to be modified so it wouldn't break things at '['. That line is
80 80 # nasty enough that I shouldn't change it until I can test it _well_.
81 81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82 82
83 83
84 84 # Handler Check Utilities
85 85 def is_shadowed(identifier, ip):
86 86 """Is the given identifier defined in one of the namespaces which shadow
87 87 the alias and magic namespaces? Note that an identifier is different
88 88 than ifun, because it can not contain a '.' character."""
89 89 # This is much safer than calling ofind, which can change state
90 90 return (identifier in ip.user_ns \
91 91 or identifier in ip.internal_ns \
92 92 or identifier in ip.ns_table['builtin'])
93 93
94 94
95 95 #-----------------------------------------------------------------------------
96 96 # The LineInfo class used throughout
97 97 #-----------------------------------------------------------------------------
98 98
99 99
100 100 class LineInfo(object):
101 101 """A single line of input and associated info.
102 102
103 103 Includes the following as properties:
104 104
105 105 line
106 106 The original, raw line
107 107
108 108 continue_prompt
109 109 Is this line a continuation in a sequence of multiline input?
110 110
111 111 pre
112 112 The initial esc character or whitespace.
113 113
114 114 pre_char
115 115 The escape character(s) in pre or the empty string if there isn't one.
116 116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 117 always be a single character.
118 118
119 119 pre_whitespace
120 120 The leading whitespace from pre if it exists. If there is a pre_char,
121 121 this is just ''.
122 122
123 123 ifun
124 124 The 'function part', which is basically the maximal initial sequence
125 125 of valid python identifiers and the '.' character. This is what is
126 126 checked for alias and magic transformations, used for auto-calling,
127 127 etc.
128 128
129 129 the_rest
130 130 Everything else on the line.
131 131 """
132 132 def __init__(self, line, continue_prompt):
133 133 self.line = line
134 134 self.continue_prompt = continue_prompt
135 135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136 136
137 137 self.pre_char = self.pre.strip()
138 138 if self.pre_char:
139 139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 140 else:
141 141 self.pre_whitespace = self.pre
142 142
143 143 self._oinfo = None
144 144
145 145 def ofind(self, ip):
146 146 """Do a full, attribute-walking lookup of the ifun in the various
147 147 namespaces for the given IPython InteractiveShell instance.
148 148
149 149 Return a dict with keys: found,obj,ospace,ismagic
150 150
151 151 Note: can cause state changes because of calling getattr, but should
152 152 only be run if autocall is on and if the line hasn't matched any
153 153 other, less dangerous handlers.
154 154
155 155 Does cache the results of the call, so can be called multiple times
156 156 without worrying about *further* damaging state.
157 157 """
158 158 if not self._oinfo:
159 159 # ip.shell._ofind is actually on the Magic class!
160 160 self._oinfo = ip.shell._ofind(self.ifun)
161 161 return self._oinfo
162 162
163 163 def __str__(self):
164 164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165 165
166 166
167 167 #-----------------------------------------------------------------------------
168 168 # Main Prefilter manager
169 169 #-----------------------------------------------------------------------------
170 170
171 171
172 172 class PrefilterManager(Configurable):
173 173 """Main prefilter component.
174 174
175 175 The IPython prefilter is run on all user input before it is run. The
176 176 prefilter consumes lines of input and produces transformed lines of
177 177 input.
178 178
179 179 The iplementation consists of two phases:
180 180
181 181 1. Transformers
182 182 2. Checkers and handlers
183 183
184 184 Over time, we plan on deprecating the checkers and handlers and doing
185 185 everything in the transformers.
186 186
187 187 The transformers are instances of :class:`PrefilterTransformer` and have
188 188 a single method :meth:`transform` that takes a line and returns a
189 189 transformed line. The transformation can be accomplished using any
190 190 tool, but our current ones use regular expressions for speed. We also
191 191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192 192
193 193 After all the transformers have been run, the line is fed to the checkers,
194 194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 195 the :meth:`check` method, which either returns `None` or a
196 196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 198 the line is passed to the :meth:`handle` method of the returned
199 199 handler and no further checkers are tried.
200 200
201 201 Both transformers and checkers have a `priority` attribute, that determines
202 202 the order in which they are called. Smaller priorities are tried first.
203 203
204 204 Both transformers and checkers also have `enabled` attribute, which is
205 205 a boolean that determines if the instance is used.
206 206
207 207 Users or developers can change the priority or enabled attribute of
208 208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 209 or :meth:`sort_transformers` method after changing the priority.
210 210 """
211 211
212 212 multi_line_specials = CBool(True, config=True)
213 213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
214 214
215 215 def __init__(self, shell=None, config=None):
216 216 super(PrefilterManager, self).__init__(shell=shell, config=config)
217 217 self.shell = shell
218 218 self.init_transformers()
219 219 self.init_handlers()
220 220 self.init_checkers()
221 221
222 222 #-------------------------------------------------------------------------
223 223 # API for managing transformers
224 224 #-------------------------------------------------------------------------
225 225
226 226 def init_transformers(self):
227 227 """Create the default transformers."""
228 228 self._transformers = []
229 229 for transformer_cls in _default_transformers:
230 230 transformer_cls(
231 231 shell=self.shell, prefilter_manager=self, config=self.config
232 232 )
233 233
234 234 def sort_transformers(self):
235 235 """Sort the transformers by priority.
236 236
237 237 This must be called after the priority of a transformer is changed.
238 238 The :meth:`register_transformer` method calls this automatically.
239 239 """
240 240 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
241 241
242 242 @property
243 243 def transformers(self):
244 244 """Return a list of checkers, sorted by priority."""
245 245 return self._transformers
246 246
247 247 def register_transformer(self, transformer):
248 248 """Register a transformer instance."""
249 249 if transformer not in self._transformers:
250 250 self._transformers.append(transformer)
251 251 self.sort_transformers()
252 252
253 253 def unregister_transformer(self, transformer):
254 254 """Unregister a transformer instance."""
255 255 if transformer in self._transformers:
256 256 self._transformers.remove(transformer)
257 257
258 258 #-------------------------------------------------------------------------
259 259 # API for managing checkers
260 260 #-------------------------------------------------------------------------
261 261
262 262 def init_checkers(self):
263 263 """Create the default checkers."""
264 264 self._checkers = []
265 265 for checker in _default_checkers:
266 266 checker(
267 267 shell=self.shell, prefilter_manager=self, config=self.config
268 268 )
269 269
270 270 def sort_checkers(self):
271 271 """Sort the checkers by priority.
272 272
273 273 This must be called after the priority of a checker is changed.
274 274 The :meth:`register_checker` method calls this automatically.
275 275 """
276 276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277 277
278 278 @property
279 279 def checkers(self):
280 280 """Return a list of checkers, sorted by priority."""
281 281 return self._checkers
282 282
283 283 def register_checker(self, checker):
284 284 """Register a checker instance."""
285 285 if checker not in self._checkers:
286 286 self._checkers.append(checker)
287 287 self.sort_checkers()
288 288
289 289 def unregister_checker(self, checker):
290 290 """Unregister a checker instance."""
291 291 if checker in self._checkers:
292 292 self._checkers.remove(checker)
293 293
294 294 #-------------------------------------------------------------------------
295 295 # API for managing checkers
296 296 #-------------------------------------------------------------------------
297 297
298 298 def init_handlers(self):
299 299 """Create the default handlers."""
300 300 self._handlers = {}
301 301 self._esc_handlers = {}
302 302 for handler in _default_handlers:
303 303 handler(
304 304 shell=self.shell, prefilter_manager=self, config=self.config
305 305 )
306 306
307 307 @property
308 308 def handlers(self):
309 309 """Return a dict of all the handlers."""
310 310 return self._handlers
311 311
312 312 def register_handler(self, name, handler, esc_strings):
313 313 """Register a handler instance by name with esc_strings."""
314 314 self._handlers[name] = handler
315 315 for esc_str in esc_strings:
316 316 self._esc_handlers[esc_str] = handler
317 317
318 318 def unregister_handler(self, name, handler, esc_strings):
319 319 """Unregister a handler instance by name with esc_strings."""
320 320 try:
321 321 del self._handlers[name]
322 322 except KeyError:
323 323 pass
324 324 for esc_str in esc_strings:
325 325 h = self._esc_handlers.get(esc_str)
326 326 if h is handler:
327 327 del self._esc_handlers[esc_str]
328 328
329 329 def get_handler_by_name(self, name):
330 330 """Get a handler by its name."""
331 331 return self._handlers.get(name)
332 332
333 333 def get_handler_by_esc(self, esc_str):
334 334 """Get a handler by its escape string."""
335 335 return self._esc_handlers.get(esc_str)
336 336
337 337 #-------------------------------------------------------------------------
338 338 # Main prefiltering API
339 339 #-------------------------------------------------------------------------
340 340
341 341 def prefilter_line_info(self, line_info):
342 342 """Prefilter a line that has been converted to a LineInfo object.
343 343
344 344 This implements the checker/handler part of the prefilter pipe.
345 345 """
346 346 # print "prefilter_line_info: ", line_info
347 347 handler = self.find_handler(line_info)
348 348 return handler.handle(line_info)
349 349
350 350 def find_handler(self, line_info):
351 351 """Find a handler for the line_info by trying checkers."""
352 352 for checker in self.checkers:
353 353 if checker.enabled:
354 354 handler = checker.check(line_info)
355 355 if handler:
356 356 return handler
357 357 return self.get_handler_by_name('normal')
358 358
359 359 def transform_line(self, line, continue_prompt):
360 360 """Calls the enabled transformers in order of increasing priority."""
361 361 for transformer in self.transformers:
362 362 if transformer.enabled:
363 363 line = transformer.transform(line, continue_prompt)
364 364 return line
365 365
366 366 def prefilter_line(self, line, continue_prompt=False):
367 367 """Prefilter a single input line as text.
368 368
369 369 This method prefilters a single line of text by calling the
370 370 transformers and then the checkers/handlers.
371 371 """
372 372
373 373 # print "prefilter_line: ", line, continue_prompt
374 374 # All handlers *must* return a value, even if it's blank ('').
375 375
376 376 # Lines are NOT logged here. Handlers should process the line as
377 377 # needed, update the cache AND log it (so that the input cache array
378 378 # stays synced).
379 379
380 380 # save the line away in case we crash, so the post-mortem handler can
381 381 # record it
382 382 self.shell._last_input_line = line
383 383
384 384 if not line:
385 385 # Return immediately on purely empty lines, so that if the user
386 386 # previously typed some whitespace that started a continuation
387 387 # prompt, he can break out of that loop with just an empty line.
388 388 # This is how the default python prompt works.
389 389
390 390 # Only return if the accumulated input buffer was just whitespace!
391 391 if ''.join(self.shell.buffer).isspace():
392 392 self.shell.buffer[:] = []
393 393 return ''
394 394
395 395 # At this point, we invoke our transformers.
396 396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
397 397 line = self.transform_line(line, continue_prompt)
398 398
399 399 # Now we compute line_info for the checkers and handlers
400 400 line_info = LineInfo(line, continue_prompt)
401 401
402 402 # the input history needs to track even empty lines
403 403 stripped = line.strip()
404 404
405 405 normal_handler = self.get_handler_by_name('normal')
406 406 if not stripped:
407 407 if not continue_prompt:
408 408 self.shell.displayhook.prompt_count -= 1
409 409
410 410 return normal_handler.handle(line_info)
411 411
412 412 # special handlers are only allowed for single line statements
413 413 if continue_prompt and not self.multi_line_specials:
414 414 return normal_handler.handle(line_info)
415 415
416 416 prefiltered = self.prefilter_line_info(line_info)
417 417 # print "prefiltered line: %r" % prefiltered
418 418 return prefiltered
419 419
420 420 def prefilter_lines(self, lines, continue_prompt=False):
421 421 """Prefilter multiple input lines of text.
422 422
423 423 This is the main entry point for prefiltering multiple lines of
424 424 input. This simply calls :meth:`prefilter_line` for each line of
425 425 input.
426 426
427 427 This covers cases where there are multiple lines in the user entry,
428 428 which is the case when the user goes back to a multiline history
429 429 entry and presses enter.
430 430 """
431 431 llines = lines.rstrip('\n').split('\n')
432 432 # We can get multiple lines in one shot, where multiline input 'blends'
433 433 # into one line, in cases like recalling from the readline history
434 434 # buffer. We need to make sure that in such cases, we correctly
435 435 # communicate downstream which line is first and which are continuation
436 436 # ones.
437 437 if len(llines) > 1:
438 438 out = '\n'.join([self.prefilter_line(line, lnum>0)
439 439 for lnum, line in enumerate(llines) ])
440 440 else:
441 441 out = self.prefilter_line(llines[0], continue_prompt)
442 442
443 443 return out
444 444
445 445 #-----------------------------------------------------------------------------
446 446 # Prefilter transformers
447 447 #-----------------------------------------------------------------------------
448 448
449 449
450 450 class PrefilterTransformer(Configurable):
451 451 """Transform a line of user input."""
452 452
453 453 priority = Int(100, config=True)
454 454 # Transformers don't currently use shell or prefilter_manager, but as we
455 455 # move away from checkers and handlers, they will need them.
456 456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
457 457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
458 458 enabled = Bool(True, config=True)
459 459
460 460 def __init__(self, shell=None, prefilter_manager=None, config=None):
461 461 super(PrefilterTransformer, self).__init__(
462 462 shell=shell, prefilter_manager=prefilter_manager, config=config
463 463 )
464 464 self.prefilter_manager.register_transformer(self)
465 465
466 466 def transform(self, line, continue_prompt):
467 467 """Transform a line, returning the new one."""
468 468 return None
469 469
470 470 def __repr__(self):
471 471 return "<%s(priority=%r, enabled=%r)>" % (
472 472 self.__class__.__name__, self.priority, self.enabled)
473 473
474 474
475 475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
476 476 r'\s*=\s*!(?P<cmd>.*)')
477 477
478 478
479 479 class AssignSystemTransformer(PrefilterTransformer):
480 480 """Handle the `files = !ls` syntax."""
481 481
482 482 priority = Int(100, config=True)
483 483
484 484 def transform(self, line, continue_prompt):
485 485 m = _assign_system_re.match(line)
486 486 if m is not None:
487 487 cmd = m.group('cmd')
488 488 lhs = m.group('lhs')
489 expr = make_quoted_expr("sc -l =%s" % cmd)
489 expr = make_quoted_expr("sc =%s" % cmd)
490 490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
491 491 return new_line
492 492 return line
493 493
494 494
495 495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
496 496 r'\s*=\s*%(?P<cmd>.*)')
497 497
498 498 class AssignMagicTransformer(PrefilterTransformer):
499 499 """Handle the `a = %who` syntax."""
500 500
501 501 priority = Int(200, config=True)
502 502
503 503 def transform(self, line, continue_prompt):
504 504 m = _assign_magic_re.match(line)
505 505 if m is not None:
506 506 cmd = m.group('cmd')
507 507 lhs = m.group('lhs')
508 508 expr = make_quoted_expr(cmd)
509 509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
510 510 return new_line
511 511 return line
512 512
513 513
514 514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
515 515
516 516 class PyPromptTransformer(PrefilterTransformer):
517 517 """Handle inputs that start with '>>> ' syntax."""
518 518
519 519 priority = Int(50, config=True)
520 520
521 521 def transform(self, line, continue_prompt):
522 522
523 523 if not line or line.isspace() or line.strip() == '...':
524 524 # This allows us to recognize multiple input prompts separated by
525 525 # blank lines and pasted in a single chunk, very common when
526 526 # pasting doctests or long tutorial passages.
527 527 return ''
528 528 m = _classic_prompt_re.match(line)
529 529 if m:
530 530 return line[len(m.group(0)):]
531 531 else:
532 532 return line
533 533
534 534
535 535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
536 536
537 537 class IPyPromptTransformer(PrefilterTransformer):
538 538 """Handle inputs that start classic IPython prompt syntax."""
539 539
540 540 priority = Int(50, config=True)
541 541
542 542 def transform(self, line, continue_prompt):
543 543
544 544 if not line or line.isspace() or line.strip() == '...':
545 545 # This allows us to recognize multiple input prompts separated by
546 546 # blank lines and pasted in a single chunk, very common when
547 547 # pasting doctests or long tutorial passages.
548 548 return ''
549 549 m = _ipy_prompt_re.match(line)
550 550 if m:
551 551 return line[len(m.group(0)):]
552 552 else:
553 553 return line
554 554
555 555 #-----------------------------------------------------------------------------
556 556 # Prefilter checkers
557 557 #-----------------------------------------------------------------------------
558 558
559 559
560 560 class PrefilterChecker(Configurable):
561 561 """Inspect an input line and return a handler for that line."""
562 562
563 563 priority = Int(100, config=True)
564 564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
565 565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
566 566 enabled = Bool(True, config=True)
567 567
568 568 def __init__(self, shell=None, prefilter_manager=None, config=None):
569 569 super(PrefilterChecker, self).__init__(
570 570 shell=shell, prefilter_manager=prefilter_manager, config=config
571 571 )
572 572 self.prefilter_manager.register_checker(self)
573 573
574 574 def check(self, line_info):
575 575 """Inspect line_info and return a handler instance or None."""
576 576 return None
577 577
578 578 def __repr__(self):
579 579 return "<%s(priority=%r, enabled=%r)>" % (
580 580 self.__class__.__name__, self.priority, self.enabled)
581 581
582 582
583 583 class EmacsChecker(PrefilterChecker):
584 584
585 585 priority = Int(100, config=True)
586 586 enabled = Bool(False, config=True)
587 587
588 588 def check(self, line_info):
589 589 "Emacs ipython-mode tags certain input lines."
590 590 if line_info.line.endswith('# PYTHON-MODE'):
591 591 return self.prefilter_manager.get_handler_by_name('emacs')
592 592 else:
593 593 return None
594 594
595 595
596 596 class ShellEscapeChecker(PrefilterChecker):
597 597
598 598 priority = Int(200, config=True)
599 599
600 600 def check(self, line_info):
601 601 if line_info.line.lstrip().startswith(ESC_SHELL):
602 602 return self.prefilter_manager.get_handler_by_name('shell')
603 603
604 604
605 605 class IPyAutocallChecker(PrefilterChecker):
606 606
607 607 priority = Int(300, config=True)
608 608
609 609 def check(self, line_info):
610 610 "Instances of IPyAutocall in user_ns get autocalled immediately"
611 611 obj = self.shell.user_ns.get(line_info.ifun, None)
612 612 if isinstance(obj, IPyAutocall):
613 613 obj.set_ip(self.shell)
614 614 return self.prefilter_manager.get_handler_by_name('auto')
615 615 else:
616 616 return None
617 617
618 618
619 619 class MultiLineMagicChecker(PrefilterChecker):
620 620
621 621 priority = Int(400, config=True)
622 622
623 623 def check(self, line_info):
624 624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
625 625 # Note that this one of the only places we check the first character of
626 626 # ifun and *not* the pre_char. Also note that the below test matches
627 627 # both ! and !!.
628 628 if line_info.continue_prompt \
629 629 and self.prefilter_manager.multi_line_specials:
630 630 if line_info.ifun.startswith(ESC_MAGIC):
631 631 return self.prefilter_manager.get_handler_by_name('magic')
632 632 else:
633 633 return None
634 634
635 635
636 636 class EscCharsChecker(PrefilterChecker):
637 637
638 638 priority = Int(500, config=True)
639 639
640 640 def check(self, line_info):
641 641 """Check for escape character and return either a handler to handle it,
642 642 or None if there is no escape char."""
643 643 if line_info.line[-1] == ESC_HELP \
644 644 and line_info.pre_char != ESC_SHELL \
645 645 and line_info.pre_char != ESC_SH_CAP:
646 646 # the ? can be at the end, but *not* for either kind of shell escape,
647 647 # because a ? can be a vaild final char in a shell cmd
648 648 return self.prefilter_manager.get_handler_by_name('help')
649 649 else:
650 650 # This returns None like it should if no handler exists
651 651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
652 652
653 653
654 654 class AssignmentChecker(PrefilterChecker):
655 655
656 656 priority = Int(600, config=True)
657 657
658 658 def check(self, line_info):
659 659 """Check to see if user is assigning to a var for the first time, in
660 660 which case we want to avoid any sort of automagic / autocall games.
661 661
662 662 This allows users to assign to either alias or magic names true python
663 663 variables (the magic/alias systems always take second seat to true
664 664 python code). E.g. ls='hi', or ls,that=1,2"""
665 665 if line_info.the_rest:
666 666 if line_info.the_rest[0] in '=,':
667 667 return self.prefilter_manager.get_handler_by_name('normal')
668 668 else:
669 669 return None
670 670
671 671
672 672 class AutoMagicChecker(PrefilterChecker):
673 673
674 674 priority = Int(700, config=True)
675 675
676 676 def check(self, line_info):
677 677 """If the ifun is magic, and automagic is on, run it. Note: normal,
678 678 non-auto magic would already have been triggered via '%' in
679 679 check_esc_chars. This just checks for automagic. Also, before
680 680 triggering the magic handler, make sure that there is nothing in the
681 681 user namespace which could shadow it."""
682 682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
683 683 return None
684 684
685 685 # We have a likely magic method. Make sure we should actually call it.
686 686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
687 687 return None
688 688
689 689 head = line_info.ifun.split('.',1)[0]
690 690 if is_shadowed(head, self.shell):
691 691 return None
692 692
693 693 return self.prefilter_manager.get_handler_by_name('magic')
694 694
695 695
696 696 class AliasChecker(PrefilterChecker):
697 697
698 698 priority = Int(800, config=True)
699 699
700 700 def check(self, line_info):
701 701 "Check if the initital identifier on the line is an alias."
702 702 # Note: aliases can not contain '.'
703 703 head = line_info.ifun.split('.',1)[0]
704 704 if line_info.ifun not in self.shell.alias_manager \
705 705 or head not in self.shell.alias_manager \
706 706 or is_shadowed(head, self.shell):
707 707 return None
708 708
709 709 return self.prefilter_manager.get_handler_by_name('alias')
710 710
711 711
712 712 class PythonOpsChecker(PrefilterChecker):
713 713
714 714 priority = Int(900, config=True)
715 715
716 716 def check(self, line_info):
717 717 """If the 'rest' of the line begins with a function call or pretty much
718 718 any python operator, we should simply execute the line (regardless of
719 719 whether or not there's a possible autocall expansion). This avoids
720 720 spurious (and very confusing) geattr() accesses."""
721 721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
722 722 return self.prefilter_manager.get_handler_by_name('normal')
723 723 else:
724 724 return None
725 725
726 726
727 727 class AutocallChecker(PrefilterChecker):
728 728
729 729 priority = Int(1000, config=True)
730 730
731 731 def check(self, line_info):
732 732 "Check if the initial word/function is callable and autocall is on."
733 733 if not self.shell.autocall:
734 734 return None
735 735
736 736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
737 737 if not oinfo['found']:
738 738 return None
739 739
740 740 if callable(oinfo['obj']) \
741 741 and (not re_exclude_auto.match(line_info.the_rest)) \
742 742 and re_fun_name.match(line_info.ifun):
743 743 return self.prefilter_manager.get_handler_by_name('auto')
744 744 else:
745 745 return None
746 746
747 747
748 748 #-----------------------------------------------------------------------------
749 749 # Prefilter handlers
750 750 #-----------------------------------------------------------------------------
751 751
752 752
753 753 class PrefilterHandler(Configurable):
754 754
755 755 handler_name = Str('normal')
756 756 esc_strings = List([])
757 757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
758 758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
759 759
760 760 def __init__(self, shell=None, prefilter_manager=None, config=None):
761 761 super(PrefilterHandler, self).__init__(
762 762 shell=shell, prefilter_manager=prefilter_manager, config=config
763 763 )
764 764 self.prefilter_manager.register_handler(
765 765 self.handler_name,
766 766 self,
767 767 self.esc_strings
768 768 )
769 769
770 770 def handle(self, line_info):
771 771 # print "normal: ", line_info
772 772 """Handle normal input lines. Use as a template for handlers."""
773 773
774 774 # With autoindent on, we need some way to exit the input loop, and I
775 775 # don't want to force the user to have to backspace all the way to
776 776 # clear the line. The rule will be in this case, that either two
777 777 # lines of pure whitespace in a row, or a line of pure whitespace but
778 778 # of a size different to the indent level, will exit the input loop.
779 779 line = line_info.line
780 780 continue_prompt = line_info.continue_prompt
781 781
782 782 if (continue_prompt and
783 783 self.shell.autoindent and
784 784 line.isspace() and
785 785
786 786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
787 787 or
788 788 not self.shell.buffer
789 789 or
790 790 (self.shell.buffer[-1]).isspace()
791 791 )
792 792 ):
793 793 line = ''
794 794
795 795 self.shell.log(line, line, continue_prompt)
796 796 return line
797 797
798 798 def __str__(self):
799 799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
800 800
801 801
802 802 class AliasHandler(PrefilterHandler):
803 803
804 804 handler_name = Str('alias')
805 805
806 806 def handle(self, line_info):
807 807 """Handle alias input lines. """
808 808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
809 809 # pre is needed, because it carries the leading whitespace. Otherwise
810 810 # aliases won't work in indented sections.
811 811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
812 812 make_quoted_expr(transformed))
813 813
814 814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
815 815 return line_out
816 816
817 817
818 818 class ShellEscapeHandler(PrefilterHandler):
819 819
820 820 handler_name = Str('shell')
821 821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
822 822
823 823 def handle(self, line_info):
824 824 """Execute the line in a shell, empty return value"""
825 825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
826 826
827 827 line = line_info.line
828 828 if line.lstrip().startswith(ESC_SH_CAP):
829 829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
830 830 # call to %sx and the actual command to be executed, so
831 831 # handle_magic can work correctly. Note that this works even if
832 832 # the line is indented, so it handles multi_line_specials
833 833 # properly.
834 834 new_rest = line.lstrip()[2:]
835 835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
836 836 line_info.ifun = 'sx'
837 837 line_info.the_rest = new_rest
838 838 return magic_handler.handle(line_info)
839 839 else:
840 840 cmd = line.lstrip().lstrip(ESC_SHELL)
841 841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
842 842 make_quoted_expr(cmd))
843 843 # update cache/log and return
844 844 self.shell.log(line, line_out, line_info.continue_prompt)
845 845 return line_out
846 846
847 847
848 848 class MagicHandler(PrefilterHandler):
849 849
850 850 handler_name = Str('magic')
851 851 esc_strings = List([ESC_MAGIC])
852 852
853 853 def handle(self, line_info):
854 854 """Execute magic functions."""
855 855 ifun = line_info.ifun
856 856 the_rest = line_info.the_rest
857 857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
858 858 make_quoted_expr(ifun + " " + the_rest))
859 859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
860 860 return cmd
861 861
862 862
863 863 class AutoHandler(PrefilterHandler):
864 864
865 865 handler_name = Str('auto')
866 866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
867 867
868 868 def handle(self, line_info):
869 869 """Handle lines which can be auto-executed, quoting if requested."""
870 870 line = line_info.line
871 871 ifun = line_info.ifun
872 872 the_rest = line_info.the_rest
873 873 pre = line_info.pre
874 874 continue_prompt = line_info.continue_prompt
875 875 obj = line_info.ofind(self)['obj']
876 876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
877 877
878 878 # This should only be active for single-line input!
879 879 if continue_prompt:
880 880 self.shell.log(line,line,continue_prompt)
881 881 return line
882 882
883 883 force_auto = isinstance(obj, IPyAutocall)
884 884 auto_rewrite = True
885 885
886 886 if pre == ESC_QUOTE:
887 887 # Auto-quote splitting on whitespace
888 888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
889 889 elif pre == ESC_QUOTE2:
890 890 # Auto-quote whole string
891 891 newcmd = '%s("%s")' % (ifun,the_rest)
892 892 elif pre == ESC_PAREN:
893 893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
894 894 else:
895 895 # Auto-paren.
896 896 # We only apply it to argument-less calls if the autocall
897 897 # parameter is set to 2. We only need to check that autocall is <
898 898 # 2, since this function isn't called unless it's at least 1.
899 899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
900 900 newcmd = '%s %s' % (ifun,the_rest)
901 901 auto_rewrite = False
902 902 else:
903 903 if not force_auto and the_rest.startswith('['):
904 904 if hasattr(obj,'__getitem__'):
905 905 # Don't autocall in this case: item access for an object
906 906 # which is BOTH callable and implements __getitem__.
907 907 newcmd = '%s %s' % (ifun,the_rest)
908 908 auto_rewrite = False
909 909 else:
910 910 # if the object doesn't support [] access, go ahead and
911 911 # autocall
912 912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
913 913 elif the_rest.endswith(';'):
914 914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
915 915 else:
916 916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
917 917
918 918 if auto_rewrite:
919 919 self.shell.auto_rewrite_input(newcmd)
920 920
921 921 # log what is now valid Python, not the actual user input (without the
922 922 # final newline)
923 923 self.shell.log(line,newcmd,continue_prompt)
924 924 return newcmd
925 925
926 926
927 927 class HelpHandler(PrefilterHandler):
928 928
929 929 handler_name = Str('help')
930 930 esc_strings = List([ESC_HELP])
931 931
932 932 def handle(self, line_info):
933 933 """Try to get some help for the object.
934 934
935 935 obj? or ?obj -> basic information.
936 936 obj?? or ??obj -> more details.
937 937 """
938 938 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
939 939 line = line_info.line
940 940 # We need to make sure that we don't process lines which would be
941 941 # otherwise valid python, such as "x=1 # what?"
942 942 try:
943 943 codeop.compile_command(line)
944 944 except SyntaxError:
945 945 # We should only handle as help stuff which is NOT valid syntax
946 946 if line[0]==ESC_HELP:
947 947 line = line[1:]
948 948 elif line[-1]==ESC_HELP:
949 949 line = line[:-1]
950 950 self.shell.log(line, '#?'+line, line_info.continue_prompt)
951 951 if line:
952 952 #print 'line:<%r>' % line # dbg
953 953 self.shell.magic_pinfo(line)
954 954 else:
955 955 self.shell.show_usage()
956 956 return '' # Empty string is needed here!
957 957 except:
958 958 raise
959 959 # Pass any other exceptions through to the normal handler
960 960 return normal_handler.handle(line_info)
961 961 else:
962 962 # If the code compiles ok, we should handle it normally
963 963 return normal_handler.handle(line_info)
964 964
965 965
966 966 class EmacsHandler(PrefilterHandler):
967 967
968 968 handler_name = Str('emacs')
969 969 esc_strings = List([])
970 970
971 971 def handle(self, line_info):
972 972 """Handle input lines marked by python-mode."""
973 973
974 974 # Currently, nothing is done. Later more functionality can be added
975 975 # here if needed.
976 976
977 977 # The input cache shouldn't be updated
978 978 return line_info.line
979 979
980 980
981 981 #-----------------------------------------------------------------------------
982 982 # Defaults
983 983 #-----------------------------------------------------------------------------
984 984
985 985
986 986 _default_transformers = [
987 987 AssignSystemTransformer,
988 988 AssignMagicTransformer,
989 989 PyPromptTransformer,
990 990 IPyPromptTransformer,
991 991 ]
992 992
993 993 _default_checkers = [
994 994 EmacsChecker,
995 995 ShellEscapeChecker,
996 996 IPyAutocallChecker,
997 997 MultiLineMagicChecker,
998 998 EscCharsChecker,
999 999 AssignmentChecker,
1000 1000 AutoMagicChecker,
1001 1001 AliasChecker,
1002 1002 PythonOpsChecker,
1003 1003 AutocallChecker
1004 1004 ]
1005 1005
1006 1006 _default_handlers = [
1007 1007 PrefilterHandler,
1008 1008 AliasHandler,
1009 1009 ShellEscapeHandler,
1010 1010 MagicHandler,
1011 1011 AutoHandler,
1012 1012 HelpHandler,
1013 1013 EmacsHandler
1014 1014 ]
@@ -1,649 +1,649 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for the inputsplitter module.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2010 The IPython Development Team
6 6 #
7 7 # Distributed under the terms of the BSD License. The full license is in
8 8 # the file COPYING, distributed as part of this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14 # stdlib
15 15 import unittest
16 16 import sys
17 17
18 18 # Third party
19 19 import nose.tools as nt
20 20
21 21 # Our own
22 22 from IPython.core import inputsplitter as isp
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Semi-complete examples (also used as tests)
26 26 #-----------------------------------------------------------------------------
27 27
28 28 # Note: at the bottom, there's a slightly more complete version of this that
29 29 # can be useful during development of code here.
30 30
31 31 def mini_interactive_loop(raw_input):
32 32 """Minimal example of the logic of an interactive interpreter loop.
33 33
34 34 This serves as an example, and it is used by the test system with a fake
35 35 raw_input that simulates interactive input."""
36 36
37 37 from IPython.core.inputsplitter import InputSplitter
38 38
39 39 isp = InputSplitter()
40 40 # In practice, this input loop would be wrapped in an outside loop to read
41 41 # input indefinitely, until some exit/quit command was issued. Here we
42 42 # only illustrate the basic inner loop.
43 43 while isp.push_accepts_more():
44 44 indent = ' '*isp.indent_spaces
45 45 prompt = '>>> ' + indent
46 46 line = indent + raw_input(prompt)
47 47 isp.push(line)
48 48
49 49 # Here we just return input so we can use it in a test suite, but a real
50 50 # interpreter would instead send it for execution somewhere.
51 51 src = isp.source_reset()
52 52 #print 'Input source was:\n', src # dbg
53 53 return src
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Test utilities, just for local use
57 57 #-----------------------------------------------------------------------------
58 58
59 59 def assemble(block):
60 60 """Assemble a block into multi-line sub-blocks."""
61 61 return ['\n'.join(sub_block)+'\n' for sub_block in block]
62 62
63 63
64 64 def pseudo_input(lines):
65 65 """Return a function that acts like raw_input but feeds the input list."""
66 66 ilines = iter(lines)
67 67 def raw_in(prompt):
68 68 try:
69 69 return next(ilines)
70 70 except StopIteration:
71 71 return ''
72 72 return raw_in
73 73
74 74 #-----------------------------------------------------------------------------
75 75 # Tests
76 76 #-----------------------------------------------------------------------------
77 77 def test_spaces():
78 78 tests = [('', 0),
79 79 (' ', 1),
80 80 ('\n', 0),
81 81 (' \n', 1),
82 82 ('x', 0),
83 83 (' x', 1),
84 84 (' x',2),
85 85 (' x',4),
86 86 # Note: tabs are counted as a single whitespace!
87 87 ('\tx', 1),
88 88 ('\t x', 2),
89 89 ]
90 90
91 91 for s, nsp in tests:
92 92 nt.assert_equal(isp.num_ini_spaces(s), nsp)
93 93
94 94
95 95 def test_remove_comments():
96 96 tests = [('text', 'text'),
97 97 ('text # comment', 'text '),
98 98 ('text # comment\n', 'text \n'),
99 99 ('text # comment \n', 'text \n'),
100 100 ('line # c \nline\n','line \nline\n'),
101 101 ('line # c \nline#c2 \nline\nline #c\n\n',
102 102 'line \nline\nline\nline \n\n'),
103 103 ]
104 104
105 105 for inp, out in tests:
106 106 nt.assert_equal(isp.remove_comments(inp), out)
107 107
108 108
109 109 def test_get_input_encoding():
110 110 encoding = isp.get_input_encoding()
111 111 nt.assert_true(isinstance(encoding, basestring))
112 112 # simple-minded check that at least encoding a simple string works with the
113 113 # encoding we got.
114 114 nt.assert_equal('test'.encode(encoding), 'test')
115 115
116 116
117 117 class NoInputEncodingTestCase(unittest.TestCase):
118 118 def setUp(self):
119 119 self.old_stdin = sys.stdin
120 120 class X: pass
121 121 fake_stdin = X()
122 122 sys.stdin = fake_stdin
123 123
124 124 def test(self):
125 125 # Verify that if sys.stdin has no 'encoding' attribute we do the right
126 126 # thing
127 127 enc = isp.get_input_encoding()
128 128 self.assertEqual(enc, 'ascii')
129 129
130 130 def tearDown(self):
131 131 sys.stdin = self.old_stdin
132 132
133 133
134 134 class InputSplitterTestCase(unittest.TestCase):
135 135 def setUp(self):
136 136 self.isp = isp.InputSplitter()
137 137
138 138 def test_reset(self):
139 139 isp = self.isp
140 140 isp.push('x=1')
141 141 isp.reset()
142 142 self.assertEqual(isp._buffer, [])
143 143 self.assertEqual(isp.indent_spaces, 0)
144 144 self.assertEqual(isp.source, '')
145 145 self.assertEqual(isp.code, None)
146 146 self.assertEqual(isp._is_complete, False)
147 147
148 148 def test_source(self):
149 149 self.isp._store('1')
150 150 self.isp._store('2')
151 151 self.assertEqual(self.isp.source, '1\n2\n')
152 152 self.assertTrue(len(self.isp._buffer)>0)
153 153 self.assertEqual(self.isp.source_reset(), '1\n2\n')
154 154 self.assertEqual(self.isp._buffer, [])
155 155 self.assertEqual(self.isp.source, '')
156 156
157 157 def test_indent(self):
158 158 isp = self.isp # shorthand
159 159 isp.push('x=1')
160 160 self.assertEqual(isp.indent_spaces, 0)
161 161 isp.push('if 1:\n x=1')
162 162 self.assertEqual(isp.indent_spaces, 4)
163 163 isp.push('y=2\n')
164 164 self.assertEqual(isp.indent_spaces, 0)
165 165 isp.push('if 1:')
166 166 self.assertEqual(isp.indent_spaces, 4)
167 167 isp.push(' x=1')
168 168 self.assertEqual(isp.indent_spaces, 4)
169 169 # Blank lines shouldn't change the indent level
170 170 isp.push(' '*2)
171 171 self.assertEqual(isp.indent_spaces, 4)
172 172
173 173 def test_indent2(self):
174 174 isp = self.isp
175 175 # When a multiline statement contains parens or multiline strings, we
176 176 # shouldn't get confused.
177 177 isp.push("if 1:")
178 178 isp.push(" x = (1+\n 2)")
179 179 self.assertEqual(isp.indent_spaces, 4)
180 180
181 181 def test_dedent(self):
182 182 isp = self.isp # shorthand
183 183 isp.push('if 1:')
184 184 self.assertEqual(isp.indent_spaces, 4)
185 185 isp.push(' pass')
186 186 self.assertEqual(isp.indent_spaces, 0)
187 187
188 188 def test_push(self):
189 189 isp = self.isp
190 190 self.assertTrue(isp.push('x=1'))
191 191
192 192 def test_push2(self):
193 193 isp = self.isp
194 194 self.assertFalse(isp.push('if 1:'))
195 195 for line in [' x=1', '# a comment', ' y=2']:
196 196 self.assertTrue(isp.push(line))
197 197
198 198 def test_push3(self):
199 199 """Test input with leading whitespace"""
200 200 isp = self.isp
201 201 isp.push(' x=1')
202 202 isp.push(' y=2')
203 203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
204 204
205 205 def test_replace_mode(self):
206 206 isp = self.isp
207 207 isp.input_mode = 'block'
208 208 isp.push('x=1')
209 209 self.assertEqual(isp.source, 'x=1\n')
210 210 isp.push('x=2')
211 211 self.assertEqual(isp.source, 'x=2\n')
212 212
213 213 def test_push_accepts_more(self):
214 214 isp = self.isp
215 215 isp.push('x=1')
216 216 self.assertFalse(isp.push_accepts_more())
217 217
218 218 def test_push_accepts_more2(self):
219 219 isp = self.isp
220 220 isp.push('if 1:')
221 221 self.assertTrue(isp.push_accepts_more())
222 222 isp.push(' x=1')
223 223 self.assertTrue(isp.push_accepts_more())
224 224 isp.push('')
225 225 self.assertFalse(isp.push_accepts_more())
226 226
227 227 def test_push_accepts_more3(self):
228 228 isp = self.isp
229 229 isp.push("x = (2+\n3)")
230 230 self.assertFalse(isp.push_accepts_more())
231 231
232 232 def test_push_accepts_more4(self):
233 233 isp = self.isp
234 234 # When a multiline statement contains parens or multiline strings, we
235 235 # shouldn't get confused.
236 236 # FIXME: we should be able to better handle de-dents in statements like
237 237 # multiline strings and multiline expressions (continued with \ or
238 238 # parens). Right now we aren't handling the indentation tracking quite
239 239 # correctly with this, though in practice it may not be too much of a
240 240 # problem. We'll need to see.
241 241 isp.push("if 1:")
242 242 isp.push(" x = (2+")
243 243 isp.push(" 3)")
244 244 self.assertTrue(isp.push_accepts_more())
245 245 isp.push(" y = 3")
246 246 self.assertTrue(isp.push_accepts_more())
247 247 isp.push('')
248 248 self.assertFalse(isp.push_accepts_more())
249 249
250 250 def test_syntax_error(self):
251 251 isp = self.isp
252 252 # Syntax errors immediately produce a 'ready' block, so the invalid
253 253 # Python can be sent to the kernel for evaluation with possible ipython
254 254 # special-syntax conversion.
255 255 isp.push('run foo')
256 256 self.assertFalse(isp.push_accepts_more())
257 257
258 258 def check_split(self, block_lines, compile=True):
259 259 blocks = assemble(block_lines)
260 260 lines = ''.join(blocks)
261 261 oblock = self.isp.split_blocks(lines)
262 262 self.assertEqual(oblock, blocks)
263 263 if compile:
264 264 for block in blocks:
265 265 self.isp._compile(block)
266 266
267 267 def test_split(self):
268 268 # All blocks of input we want to test in a list. The format for each
269 269 # block is a list of lists, with each inner lists consisting of all the
270 270 # lines (as single-lines) that should make up a sub-block.
271 271
272 272 # Note: do NOT put here sub-blocks that don't compile, as the
273 273 # check_split() routine makes a final verification pass to check that
274 274 # each sub_block, as returned by split_blocks(), does compile
275 275 # correctly.
276 276 all_blocks = [ [['x=1']],
277 277
278 278 [['x=1'],
279 279 ['y=2']],
280 280
281 281 [['x=1',
282 282 '# a comment'],
283 283 ['y=11']],
284 284
285 285 [['if 1:',
286 286 ' x=1'],
287 287 ['y=3']],
288 288
289 289 [['def f(x):',
290 290 ' return x'],
291 291 ['x=1']],
292 292
293 293 [['def f(x):',
294 294 ' x+=1',
295 295 ' ',
296 296 ' return x'],
297 297 ['x=1']],
298 298
299 299 [['def f(x):',
300 300 ' if x>0:',
301 301 ' y=1',
302 302 ' # a comment',
303 303 ' else:',
304 304 ' y=4',
305 305 ' ',
306 306 ' return y'],
307 307 ['x=1'],
308 308 ['if 1:',
309 309 ' y=11'] ],
310 310
311 311 [['for i in range(10):'
312 312 ' x=i**2']],
313 313
314 314 [['for i in range(10):'
315 315 ' x=i**2'],
316 316 ['z = 1']],
317 317 ]
318 318 for block_lines in all_blocks:
319 319 self.check_split(block_lines)
320 320
321 321 def test_split_syntax_errors(self):
322 322 # Block splitting with invalid syntax
323 323 all_blocks = [ [['a syntax error']],
324 324
325 325 [['x=1',
326 326 'another syntax error']],
327 327
328 328 [['for i in range(10):'
329 329 ' yet another error']],
330 330
331 331 ]
332 332 for block_lines in all_blocks:
333 333 self.check_split(block_lines, compile=False)
334 334
335 335
336 336 class InteractiveLoopTestCase(unittest.TestCase):
337 337 """Tests for an interactive loop like a python shell.
338 338 """
339 339 def check_ns(self, lines, ns):
340 340 """Validate that the given input lines produce the resulting namespace.
341 341
342 342 Note: the input lines are given exactly as they would be typed in an
343 343 auto-indenting environment, as mini_interactive_loop above already does
344 344 auto-indenting and prepends spaces to the input.
345 345 """
346 346 src = mini_interactive_loop(pseudo_input(lines))
347 347 test_ns = {}
348 348 exec src in test_ns
349 349 # We can't check that the provided ns is identical to the test_ns,
350 350 # because Python fills test_ns with extra keys (copyright, etc). But
351 351 # we can check that the given dict is *contained* in test_ns
352 352 for k,v in ns.items():
353 353 self.assertEqual(test_ns[k], v)
354 354
355 355 def test_simple(self):
356 356 self.check_ns(['x=1'], dict(x=1))
357 357
358 358 def test_simple2(self):
359 359 self.check_ns(['if 1:', 'x=2'], dict(x=2))
360 360
361 361 def test_xy(self):
362 362 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
363 363
364 364 def test_abc(self):
365 365 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
366 366
367 367 def test_multi(self):
368 368 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
369 369
370 370
371 371 def test_LineInfo():
372 372 """Simple test for LineInfo construction and str()"""
373 373 linfo = isp.LineInfo(' %cd /home')
374 374 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
375 375
376 376
377 377 def test_split_user_input():
378 378 """Unicode test - split_user_input already has good doctests"""
379 379 line = u"PΓ©rez Fernando"
380 380 parts = isp.split_user_input(line)
381 381 parts_expected = (u'', u'', u'', line)
382 382 nt.assert_equal(parts, parts_expected)
383 383
384 384
385 385 # Transformer tests
386 386 def transform_checker(tests, func):
387 387 """Utility to loop over test inputs"""
388 388 for inp, tr in tests:
389 389 nt.assert_equals(func(inp), tr)
390 390
391 391 # Data for all the syntax tests in the form of lists of pairs of
392 392 # raw/transformed input. We store it here as a global dict so that we can use
393 393 # it both within single-function tests and also to validate the behavior of the
394 394 # larger objects
395 395
396 396 syntax = \
397 397 dict(assign_system =
398 [('a =! ls', 'a = get_ipython().magic("sc -l = ls")'),
399 ('b = !ls', 'b = get_ipython().magic("sc -l = ls")'),
398 [('a =! ls', 'a = get_ipython().getoutput("ls")'),
399 ('b = !ls', 'b = get_ipython().getoutput("ls")'),
400 400 ('x=1', 'x=1'), # normal input is unmodified
401 401 (' ',' '), # blank lines are kept intact
402 402 ],
403 403
404 404 assign_magic =
405 405 [('a =% who', 'a = get_ipython().magic("who")'),
406 406 ('b = %who', 'b = get_ipython().magic("who")'),
407 407 ('x=1', 'x=1'), # normal input is unmodified
408 408 (' ',' '), # blank lines are kept intact
409 409 ],
410 410
411 411 classic_prompt =
412 412 [('>>> x=1', 'x=1'),
413 413 ('x=1', 'x=1'), # normal input is unmodified
414 414 (' ', ' '), # blank lines are kept intact
415 415 ('... ', ''), # continuation prompts
416 416 ],
417 417
418 418 ipy_prompt =
419 419 [('In [1]: x=1', 'x=1'),
420 420 ('x=1', 'x=1'), # normal input is unmodified
421 421 (' ',' '), # blank lines are kept intact
422 422 (' ....: ', ''), # continuation prompts
423 423 ],
424 424
425 425 # Tests for the escape transformer to leave normal code alone
426 426 escaped_noesc =
427 427 [ (' ', ' '),
428 428 ('x=1', 'x=1'),
429 429 ],
430 430
431 431 # System calls
432 432 escaped_shell =
433 433 [ ('!ls', 'get_ipython().system("ls")'),
434 434 # Double-escape shell, this means to capture the output of the
435 435 # subprocess and return it
436 436 ('!!ls', 'get_ipython().getoutput("ls")'),
437 437 ],
438 438
439 439 # Help/object info
440 440 escaped_help =
441 441 [ ('?', 'get_ipython().show_usage()'),
442 442 ('?x1', 'get_ipython().magic("pinfo x1")'),
443 443 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
444 444 ('x3?', 'get_ipython().magic("pinfo x3")'),
445 445 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
446 446 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
447 447 ],
448 448
449 449 # Explicit magic calls
450 450 escaped_magic =
451 451 [ ('%cd', 'get_ipython().magic("cd")'),
452 452 ('%cd /home', 'get_ipython().magic("cd /home")'),
453 453 (' %magic', ' get_ipython().magic("magic")'),
454 454 ],
455 455
456 456 # Quoting with separate arguments
457 457 escaped_quote =
458 458 [ (',f', 'f("")'),
459 459 (',f x', 'f("x")'),
460 460 (' ,f y', ' f("y")'),
461 461 (',f a b', 'f("a", "b")'),
462 462 ],
463 463
464 464 # Quoting with single argument
465 465 escaped_quote2 =
466 466 [ (';f', 'f("")'),
467 467 (';f x', 'f("x")'),
468 468 (' ;f y', ' f("y")'),
469 469 (';f a b', 'f("a b")'),
470 470 ],
471 471
472 472 # Simply apply parens
473 473 escaped_paren =
474 474 [ ('/f', 'f()'),
475 475 ('/f x', 'f(x)'),
476 476 (' /f y', ' f(y)'),
477 477 ('/f a b', 'f(a, b)'),
478 478 ],
479 479
480 480 )
481 481
482 482 # multiline syntax examples. Each of these should be a list of lists, with
483 483 # each entry itself having pairs of raw/transformed input. The union (with
484 484 # '\n'.join() of the transformed inputs is what the splitter should produce
485 485 # when fed the raw lines one at a time via push.
486 486 syntax_ml = \
487 487 dict(classic_prompt =
488 488 [ [('>>> for i in range(10):','for i in range(10):'),
489 489 ('... print i',' print i'),
490 490 ('... ', ''),
491 491 ],
492 492 ],
493 493
494 494 ipy_prompt =
495 495 [ [('In [24]: for i in range(10):','for i in range(10):'),
496 496 (' ....: print i',' print i'),
497 497 (' ....: ', ''),
498 498 ],
499 499 ],
500 500 )
501 501
502 502
503 503 def test_assign_system():
504 504 transform_checker(syntax['assign_system'], isp.transform_assign_system)
505 505
506 506
507 507 def test_assign_magic():
508 508 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
509 509
510 510
511 511 def test_classic_prompt():
512 512 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
513 513 for example in syntax_ml['classic_prompt']:
514 514 transform_checker(example, isp.transform_classic_prompt)
515 515
516 516
517 517 def test_ipy_prompt():
518 518 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
519 519 for example in syntax_ml['ipy_prompt']:
520 520 transform_checker(example, isp.transform_ipy_prompt)
521 521
522 522
523 523 def test_escaped_noesc():
524 524 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
525 525
526 526
527 527 def test_escaped_shell():
528 528 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
529 529
530 530
531 531 def test_escaped_help():
532 532 transform_checker(syntax['escaped_help'], isp.transform_escaped)
533 533
534 534
535 535 def test_escaped_magic():
536 536 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
537 537
538 538
539 539 def test_escaped_quote():
540 540 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
541 541
542 542
543 543 def test_escaped_quote2():
544 544 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
545 545
546 546
547 547 def test_escaped_paren():
548 548 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
549 549
550 550
551 551 class IPythonInputTestCase(InputSplitterTestCase):
552 552 """By just creating a new class whose .isp is a different instance, we
553 553 re-run the same test battery on the new input splitter.
554 554
555 555 In addition, this runs the tests over the syntax and syntax_ml dicts that
556 556 were tested by individual functions, as part of the OO interface.
557 557 """
558 558
559 559 def setUp(self):
560 560 self.isp = isp.IPythonInputSplitter(input_mode='line')
561 561
562 562 def test_syntax(self):
563 563 """Call all single-line syntax tests from the main object"""
564 564 isp = self.isp
565 565 for example in syntax.itervalues():
566 566 for raw, out_t in example:
567 567 if raw.startswith(' '):
568 568 continue
569 569
570 570 isp.push(raw)
571 571 out = isp.source_reset().rstrip()
572 572 self.assertEqual(out, out_t)
573 573
574 574 def test_syntax_multiline(self):
575 575 isp = self.isp
576 576 for example in syntax_ml.itervalues():
577 577 out_t_parts = []
578 578 for line_pairs in example:
579 579 for raw, out_t_part in line_pairs:
580 580 isp.push(raw)
581 581 out_t_parts.append(out_t_part)
582 582
583 583 out = isp.source_reset().rstrip()
584 584 out_t = '\n'.join(out_t_parts).rstrip()
585 585 self.assertEqual(out, out_t)
586 586
587 587
588 588 class BlockIPythonInputTestCase(IPythonInputTestCase):
589 589
590 590 # Deactivate tests that don't make sense for the block mode
591 591 test_push3 = test_split = lambda s: None
592 592
593 593 def setUp(self):
594 594 self.isp = isp.IPythonInputSplitter(input_mode='block')
595 595
596 596 def test_syntax_multiline(self):
597 597 isp = self.isp
598 598 for example in syntax_ml.itervalues():
599 599 raw_parts = []
600 600 out_t_parts = []
601 601 for line_pairs in example:
602 602 for raw, out_t_part in line_pairs:
603 603 raw_parts.append(raw)
604 604 out_t_parts.append(out_t_part)
605 605
606 606 raw = '\n'.join(raw_parts)
607 607 out_t = '\n'.join(out_t_parts)
608 608
609 609 isp.push(raw)
610 610 out = isp.source_reset()
611 611 # Match ignoring trailing whitespace
612 612 self.assertEqual(out.rstrip(), out_t.rstrip())
613 613
614 614
615 615 #-----------------------------------------------------------------------------
616 616 # Main - use as a script, mostly for developer experiments
617 617 #-----------------------------------------------------------------------------
618 618
619 619 if __name__ == '__main__':
620 620 # A simple demo for interactive experimentation. This code will not get
621 621 # picked up by any test suite.
622 622 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
623 623
624 624 # configure here the syntax to use, prompt and whether to autoindent
625 625 #isp, start_prompt = InputSplitter(), '>>> '
626 626 isp, start_prompt = IPythonInputSplitter(), 'In> '
627 627
628 628 autoindent = True
629 629 #autoindent = False
630 630
631 631 try:
632 632 while True:
633 633 prompt = start_prompt
634 634 while isp.push_accepts_more():
635 635 indent = ' '*isp.indent_spaces
636 636 if autoindent:
637 637 line = indent + raw_input(prompt+indent)
638 638 else:
639 639 line = raw_input(prompt)
640 640 isp.push(line)
641 641 prompt = '... '
642 642
643 643 # Here we just return input so we can use it in a test suite, but a
644 644 # real interpreter would instead send it for execution somewhere.
645 645 #src = isp.source; raise EOFError # dbg
646 646 src = isp.source_reset()
647 647 print 'Input source was:\n', src
648 648 except EOFError:
649 649 print 'Bye'
@@ -1,121 +1,142 b''
1 1 """Common utilities for the various process_* implementations.
2 2
3 3 This file is only meant to be imported by the platform-specific implementations
4 4 of subprocess utilities, and it contains tools that are common to all of them.
5 5 """
6 6
7 7 #-----------------------------------------------------------------------------
8 8 # Copyright (C) 2010 The IPython Development Team
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17 import subprocess
18 18 import sys
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Function definitions
22 22 #-----------------------------------------------------------------------------
23 23
24 24 def read_no_interrupt(p):
25 25 """Read from a pipe ignoring EINTR errors.
26 26
27 27 This is necessary because when reading from pipes with GUI event loops
28 28 running in the background, often interrupts are raised that stop the
29 29 command from completing."""
30 30 import errno
31 31
32 32 try:
33 33 return p.read()
34 34 except IOError, err:
35 35 if err.errno != errno.EINTR:
36 36 raise
37 37
38 38
39 39 def process_handler(cmd, callback, stderr=subprocess.PIPE):
40 40 """Open a command in a shell subprocess and execute a callback.
41 41
42 42 This function provides common scaffolding for creating subprocess.Popen()
43 43 calls. It creates a Popen object and then calls the callback with it.
44 44
45 45 Parameters
46 46 ----------
47 47 cmd : str
48 48 A string to be executed with the underlying system shell (by calling
49 49 :func:`Popen` with ``shell=True``.
50 50
51 51 callback : callable
52 52 A one-argument function that will be called with the Popen object.
53 53
54 54 stderr : file descriptor number, optional
55 55 By default this is set to ``subprocess.PIPE``, but you can also pass the
56 56 value ``subprocess.STDOUT`` to force the subprocess' stderr to go into
57 57 the same file descriptor as its stdout. This is useful to read stdout
58 58 and stderr combined in the order they are generated.
59 59
60 60 Returns
61 61 -------
62 62 The return value of the provided callback is returned.
63 63 """
64 64 sys.stdout.flush()
65 65 sys.stderr.flush()
66 66 # On win32, close_fds can't be true when using pipes for stdin/out/err
67 67 close_fds = sys.platform != 'win32'
68 68 p = subprocess.Popen(cmd, shell=True,
69 69 stdin=subprocess.PIPE,
70 70 stdout=subprocess.PIPE,
71 71 stderr=stderr,
72 72 close_fds=close_fds)
73 73
74 74 try:
75 75 out = callback(p)
76 76 except KeyboardInterrupt:
77 77 print('^C')
78 78 sys.stdout.flush()
79 79 sys.stderr.flush()
80 80 out = None
81 81 finally:
82 82 # Make really sure that we don't leave processes behind, in case the
83 83 # call above raises an exception
84 84 # We start by assuming the subprocess finished (to avoid NameErrors
85 85 # later depending on the path taken)
86 86 if p.returncode is None:
87 87 try:
88 88 p.terminate()
89 89 p.poll()
90 90 except OSError:
91 91 pass
92 92 # One last try on our way out
93 93 if p.returncode is None:
94 94 try:
95 95 p.kill()
96 96 except OSError:
97 97 pass
98 98
99 99 return out
100 100
101 101
102 def getoutput(cmd):
103 """Return standard output of executing cmd in a shell.
104
105 Accepts the same arguments as os.system().
106
107 Parameters
108 ----------
109 cmd : str
110 A command to be executed in the system shell.
111
112 Returns
113 -------
114 stdout : str
115 """
116
117 out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
118 if out is None:
119 out = ''
120 return out
121
122
102 123 def getoutputerror(cmd):
103 124 """Return (standard output, standard error) of executing cmd in a shell.
104 125
105 126 Accepts the same arguments as os.system().
106 127
107 128 Parameters
108 129 ----------
109 130 cmd : str
110 131 A command to be executed in the system shell.
111 132
112 133 Returns
113 134 -------
114 135 stdout : str
115 136 stderr : str
116 137 """
117 138
118 139 out_err = process_handler(cmd, lambda p: p.communicate())
119 140 if out_err is None:
120 141 out_err = '', ''
121 142 return out_err
@@ -1,169 +1,192 b''
1 1 """Posix-specific implementation of process utilities.
2 2
3 3 This file is only meant to be imported by process.py, not by end-users.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Stdlib
19 19 import subprocess as sp
20 20 import sys
21 21
22 22 # Third-party
23 23 # We ship our own copy of pexpect (it's a single file) to minimize dependencies
24 24 # for users, but it's only used if we don't find the system copy.
25 25 try:
26 26 import pexpect
27 27 except ImportError:
28 28 from IPython.external import pexpect
29 29
30 30 # Our own
31 31 from .autoattr import auto_attr
32 from ._process_common import getoutput
32 33
33 34 #-----------------------------------------------------------------------------
34 35 # Function definitions
35 36 #-----------------------------------------------------------------------------
36 37
37 38 def _find_cmd(cmd):
38 39 """Find the full path to a command using which."""
39 40
40 41 return sp.Popen(['/usr/bin/env', 'which', cmd],
41 42 stdout=sp.PIPE).communicate()[0]
42 43
43 44
44 45 class ProcessHandler(object):
45 46 """Execute subprocesses under the control of pexpect.
46 47 """
47 48 # Timeout in seconds to wait on each reading of the subprocess' output.
48 49 # This should not be set too low to avoid cpu overusage from our side,
49 50 # since we read in a loop whose period is controlled by this timeout.
50 51 read_timeout = 0.05
51 52
52 53 # Timeout to give a process if we receive SIGINT, between sending the
53 54 # SIGINT to the process and forcefully terminating it.
54 55 terminate_timeout = 0.2
55 56
56 57 # File object where stdout and stderr of the subprocess will be written
57 58 logfile = None
58 59
59 60 # Shell to call for subprocesses to execute
60 61 sh = None
61 62
62 63 @auto_attr
63 64 def sh(self):
64 65 sh = pexpect.which('sh')
65 66 if sh is None:
66 67 raise OSError('"sh" shell not found')
67 68 return sh
68 69
69 70 def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
70 71 """Arguments are used for pexpect calls."""
71 72 self.read_timeout = (ProcessHandler.read_timeout if read_timeout is
72 73 None else read_timeout)
73 74 self.terminate_timeout = (ProcessHandler.terminate_timeout if
74 75 terminate_timeout is None else
75 76 terminate_timeout)
76 77 self.logfile = sys.stdout if logfile is None else logfile
77 78
78 79 def getoutput(self, cmd):
79 80 """Run a command and return its stdout/stderr as a string.
80 81
81 82 Parameters
82 83 ----------
83 84 cmd : str
84 85 A command to be executed in the system shell.
85 86
86 87 Returns
87 88 -------
88 89 output : str
89 90 A string containing the combination of stdout and stderr from the
90 91 subprocess, in whatever order the subprocess originally wrote to its
91 92 file descriptors (so the order of the information in this string is the
92 93 correct order as would be seen if running the command in a terminal).
93 94 """
94 95 pcmd = self._make_cmd(cmd)
95 96 try:
96 97 return pexpect.run(pcmd).replace('\r\n', '\n')
97 98 except KeyboardInterrupt:
98 99 print('^C', file=sys.stderr, end='')
99 100
101 def getoutput_pexpect(self, cmd):
102 """Run a command and return its stdout/stderr as a string.
103
104 Parameters
105 ----------
106 cmd : str
107 A command to be executed in the system shell.
108
109 Returns
110 -------
111 output : str
112 A string containing the combination of stdout and stderr from the
113 subprocess, in whatever order the subprocess originally wrote to its
114 file descriptors (so the order of the information in this string is the
115 correct order as would be seen if running the command in a terminal).
116 """
117 pcmd = self._make_cmd(cmd)
118 try:
119 return pexpect.run(pcmd).replace('\r\n', '\n')
120 except KeyboardInterrupt:
121 print('^C', file=sys.stderr, end='')
122
100 123 def system(self, cmd):
101 124 """Execute a command in a subshell.
102 125
103 126 Parameters
104 127 ----------
105 128 cmd : str
106 129 A command to be executed in the system shell.
107 130
108 131 Returns
109 132 -------
110 133 None : we explicitly do NOT return the subprocess status code, as this
111 134 utility is meant to be used extensively in IPython, where any return
112 135 value would trigger :func:`sys.displayhook` calls.
113 136 """
114 137 pcmd = self._make_cmd(cmd)
115 138 # Patterns to match on the output, for pexpect. We read input and
116 139 # allow either a short timeout or EOF
117 140 patterns = [pexpect.TIMEOUT, pexpect.EOF]
118 141 # the index of the EOF pattern in the list.
119 142 EOF_index = 1 # Fix this index if you change the list!!
120 143 # The size of the output stored so far in the process output buffer.
121 144 # Since pexpect only appends to this buffer, each time we print we
122 145 # record how far we've printed, so that next time we only print *new*
123 146 # content from the buffer.
124 147 out_size = 0
125 148 try:
126 149 # Since we're not really searching the buffer for text patterns, we
127 150 # can set pexpect's search window to be tiny and it won't matter.
128 151 # We only search for the 'patterns' timeout or EOF, which aren't in
129 152 # the text itself.
130 153 child = pexpect.spawn(pcmd, searchwindowsize=1)
131 154 flush = sys.stdout.flush
132 155 while True:
133 156 # res is the index of the pattern that caused the match, so we
134 157 # know whether we've finished (if we matched EOF) or not
135 158 res_idx = child.expect_list(patterns, self.read_timeout)
136 159 print(child.before[out_size:], end='')
137 160 flush()
138 161 # Update the pointer to what we've already printed
139 162 out_size = len(child.before)
140 163 if res_idx==EOF_index:
141 164 break
142 165 except KeyboardInterrupt:
143 166 # We need to send ^C to the process. The ascii code for '^C' is 3
144 167 # (the character is known as ETX for 'End of Text', see
145 168 # curses.ascii.ETX).
146 169 child.sendline(chr(3))
147 170 # Read and print any more output the program might produce on its
148 171 # way out.
149 172 try:
150 173 out_size = len(child.before)
151 174 child.expect_list(patterns, self.terminate_timeout)
152 175 print(child.before[out_size:], end='')
153 176 except KeyboardInterrupt:
154 177 # Impatient users tend to type it multiple times
155 178 pass
156 179 finally:
157 180 # Ensure the subprocess really is terminated
158 181 child.terminate(force=True)
159 182
160 183 def _make_cmd(self, cmd):
161 184 return '%s -c "%s"' % (self.sh, cmd)
162 185
163 186
164
165 # Make objects with a functional interface for outside use
166 __ph = ProcessHandler()
167
168 system = __ph.system
169 getoutput = __ph.getoutput
187 # Make system() with a functional interface for outside use. Note that we use
188 # getoutput() from the _common utils, which is built on top of popen(). Using
189 # pexpect to get subprocess output produces difficult to parse output, since
190 # programs think they are talking to a tty and produce highly formatted output
191 # (ls is a good example) that makes them hard.
192 system = ProcessHandler().system
General Comments 0
You need to be logged in to leave comments. Login now