##// END OF EJS Templates
move completer configurables to IPCompleter where they belong...
MinRK -
Show More
@@ -1,910 +1,925 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 Original rlcompleter documentation:
10 10
11 11 This requires the latest extension to the readline module (the
12 12 completes keywords, built-ins and globals in __main__; when completing
13 13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 14 completes its attributes.
15 15
16 16 It's very cool to do "import string" type "string.", hit the
17 17 completion key (twice), and see the list of names defined by the
18 18 string module!
19 19
20 20 Tip: to use the tab key as the completion key, call
21 21
22 22 readline.parse_and_bind("tab: complete")
23 23
24 24 Notes:
25 25
26 26 - Exceptions raised by the completer function are *ignored* (and
27 27 generally cause the completion to fail). This is a feature -- since
28 28 readline sets the tty device in raw (or cbreak) mode, printing a
29 29 traceback wouldn't work well without some complicated hoopla to save,
30 30 reset and restore the tty state.
31 31
32 32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 33 application defined code to be executed if an object with a
34 34 __getattr__ hook is found. Since it is the responsibility of the
35 35 application (or the user) to enable this feature, I consider this an
36 36 acceptable risk. More complicated expressions (e.g. function calls or
37 37 indexing operations) are *not* evaluated.
38 38
39 39 - GNU readline is also used by the built-in functions input() and
40 40 raw_input(), and thus these also benefit/suffer from the completer
41 41 features. Clearly an interactive application can benefit by
42 42 specifying its own completer function and using raw_input() for all
43 43 its input.
44 44
45 45 - When the original stdin is not a tty device, GNU readline is never
46 46 used, and this module (and the readline module) are silently inactive.
47 47 """
48 48
49 49 #*****************************************************************************
50 50 #
51 51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 52 # module which is part of the standard Python distribution, I assume that the
53 53 # proper procedure is to maintain its copyright as belonging to the Python
54 54 # Software Foundation (in addition to my own, for all new code).
55 55 #
56 56 # Copyright (C) 2008-2010 IPython Development Team
57 57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
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 from __future__ import print_function
65 65
66 66 #-----------------------------------------------------------------------------
67 67 # Imports
68 68 #-----------------------------------------------------------------------------
69 69
70 70 import __builtin__
71 71 import __main__
72 72 import glob
73 73 import inspect
74 74 import itertools
75 75 import keyword
76 76 import os
77 77 import re
78 78 import shlex
79 79 import sys
80 80
81 81 from IPython.config.configurable import Configurable
82 82 from IPython.core.error import TryNext
83 83 from IPython.core.prefilter import ESC_MAGIC
84 84 from IPython.utils import generics
85 85 from IPython.utils import io
86 86 from IPython.utils.dir2 import dir2
87 87 from IPython.utils.process import arg_split
88 from IPython.utils.traitlets import CBool
88 from IPython.utils.traitlets import CBool, Enum
89 89
90 90 #-----------------------------------------------------------------------------
91 91 # Globals
92 92 #-----------------------------------------------------------------------------
93 93
94 94 # Public API
95 95 __all__ = ['Completer','IPCompleter']
96 96
97 97 if sys.platform == 'win32':
98 98 PROTECTABLES = ' '
99 99 else:
100 100 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
101 101
102 102 #-----------------------------------------------------------------------------
103 103 # Main functions and classes
104 104 #-----------------------------------------------------------------------------
105 105
106 106 def has_open_quotes(s):
107 107 """Return whether a string has open quotes.
108 108
109 109 This simply counts whether the number of quote characters of either type in
110 110 the string is odd.
111 111
112 112 Returns
113 113 -------
114 114 If there is an open quote, the quote character is returned. Else, return
115 115 False.
116 116 """
117 117 # We check " first, then ', so complex cases with nested quotes will get
118 118 # the " to take precedence.
119 119 if s.count('"') % 2:
120 120 return '"'
121 121 elif s.count("'") % 2:
122 122 return "'"
123 123 else:
124 124 return False
125 125
126 126
127 127 def protect_filename(s):
128 128 """Escape a string to protect certain characters."""
129 129
130 130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
131 131 for ch in s])
132 132
133 133
134 134 def mark_dirs(matches):
135 135 """Mark directories in input list by appending '/' to their names."""
136 136 out = []
137 137 isdir = os.path.isdir
138 138 for x in matches:
139 139 if isdir(x):
140 140 out.append(x+'/')
141 141 else:
142 142 out.append(x)
143 143 return out
144 144
145 145
146 146 def expand_user(path):
147 147 """Expand '~'-style usernames in strings.
148 148
149 149 This is similar to :func:`os.path.expanduser`, but it computes and returns
150 150 extra information that will be useful if the input was being used in
151 151 computing completions, and you wish to return the completions with the
152 152 original '~' instead of its expanded value.
153 153
154 154 Parameters
155 155 ----------
156 156 path : str
157 157 String to be expanded. If no ~ is present, the output is the same as the
158 158 input.
159 159
160 160 Returns
161 161 -------
162 162 newpath : str
163 163 Result of ~ expansion in the input path.
164 164 tilde_expand : bool
165 165 Whether any expansion was performed or not.
166 166 tilde_val : str
167 167 The value that ~ was replaced with.
168 168 """
169 169 # Default values
170 170 tilde_expand = False
171 171 tilde_val = ''
172 172 newpath = path
173 173
174 174 if path.startswith('~'):
175 175 tilde_expand = True
176 176 rest = len(path)-1
177 177 newpath = os.path.expanduser(path)
178 178 if rest:
179 179 tilde_val = newpath[:-rest]
180 180 else:
181 181 tilde_val = newpath
182 182
183 183 return newpath, tilde_expand, tilde_val
184 184
185 185
186 186 def compress_user(path, tilde_expand, tilde_val):
187 187 """Does the opposite of expand_user, with its outputs.
188 188 """
189 189 if tilde_expand:
190 190 return path.replace(tilde_val, '~')
191 191 else:
192 192 return path
193 193
194 194
195 195 def single_dir_expand(matches):
196 196 "Recursively expand match lists containing a single dir."
197 197
198 198 if len(matches) == 1 and os.path.isdir(matches[0]):
199 199 # Takes care of links to directories also. Use '/'
200 200 # explicitly, even under Windows, so that name completions
201 201 # don't end up escaped.
202 202 d = matches[0]
203 203 if d[-1] in ['/','\\']:
204 204 d = d[:-1]
205 205
206 206 subdirs = os.listdir(d)
207 207 if subdirs:
208 208 matches = [ (d + '/' + p) for p in subdirs]
209 209 return single_dir_expand(matches)
210 210 else:
211 211 return matches
212 212 else:
213 213 return matches
214 214
215 215
216 216 class Bunch(object): pass
217 217
218 218 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
219 219 GREEDY_DELIMS = ' \r\n'
220 220
221 221 class CompletionSplitter(object):
222 222 """An object to split an input line in a manner similar to readline.
223 223
224 224 By having our own implementation, we can expose readline-like completion in
225 225 a uniform manner to all frontends. This object only needs to be given the
226 226 line of text to be split and the cursor position on said line, and it
227 227 returns the 'word' to be completed on at the cursor after splitting the
228 228 entire line.
229 229
230 230 What characters are used as splitting delimiters can be controlled by
231 231 setting the `delims` attribute (this is a property that internally
232 232 automatically builds the necessary """
233 233
234 234 # Private interface
235 235
236 236 # A string of delimiter characters. The default value makes sense for
237 237 # IPython's most typical usage patterns.
238 238 _delims = DELIMS
239 239
240 240 # The expression (a normal string) to be compiled into a regular expression
241 241 # for actual splitting. We store it as an attribute mostly for ease of
242 242 # debugging, since this type of code can be so tricky to debug.
243 243 _delim_expr = None
244 244
245 245 # The regular expression that does the actual splitting
246 246 _delim_re = None
247 247
248 248 def __init__(self, delims=None):
249 249 delims = CompletionSplitter._delims if delims is None else delims
250 250 self.set_delims(delims)
251 251
252 252 def set_delims(self, delims):
253 253 """Set the delimiters for line splitting."""
254 254 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
255 255 self._delim_re = re.compile(expr)
256 256 self._delims = delims
257 257 self._delim_expr = expr
258 258
259 259 def get_delims(self):
260 260 """Return the string of delimiter characters."""
261 261 return self._delims
262 262
263 263 def split_line(self, line, cursor_pos=None):
264 264 """Split a line of text with a cursor at the given position.
265 265 """
266 266 l = line if cursor_pos is None else line[:cursor_pos]
267 267 return self._delim_re.split(l)[-1]
268 268
269 269
270 270 class Completer(Configurable):
271 271
272 272 greedy = CBool(False, config=True,
273 273 help="""Activate greedy completion
274 274
275 275 This will enable completion on elements of lists, results of function calls, etc.,
276 276 but can be unsafe because the code is actually evaluated on TAB.
277 277 """
278 278 )
279
279 280
280 def __init__(self, namespace=None, global_namespace=None, config=None):
281 def __init__(self, namespace=None, global_namespace=None, config=None, **kwargs):
281 282 """Create a new completer for the command line.
282 283
283 284 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
284 285
285 286 If unspecified, the default namespace where completions are performed
286 287 is __main__ (technically, __main__.__dict__). Namespaces should be
287 288 given as dictionaries.
288 289
289 290 An optional second namespace can be given. This allows the completer
290 291 to handle cases where both the local and global scopes need to be
291 292 distinguished.
292 293
293 294 Completer instances should be used as the completion mechanism of
294 295 readline via the set_completer() call:
295 296
296 297 readline.set_completer(Completer(my_namespace).complete)
297 298 """
298 299
299 300 # Don't bind to namespace quite yet, but flag whether the user wants a
300 301 # specific namespace or to use __main__.__dict__. This will allow us
301 302 # to bind to __main__.__dict__ at completion time, not now.
302 303 if namespace is None:
303 304 self.use_main_ns = 1
304 305 else:
305 306 self.use_main_ns = 0
306 307 self.namespace = namespace
307 308
308 309 # The global namespace, if given, can be bound directly
309 310 if global_namespace is None:
310 311 self.global_namespace = {}
311 312 else:
312 313 self.global_namespace = global_namespace
313 314
314 super(Completer, self).__init__(config=config)
315 super(Completer, self).__init__(config=config, **kwargs)
315 316
316 317 def complete(self, text, state):
317 318 """Return the next possible completion for 'text'.
318 319
319 320 This is called successively with state == 0, 1, 2, ... until it
320 321 returns None. The completion should begin with 'text'.
321 322
322 323 """
323 324 if self.use_main_ns:
324 325 self.namespace = __main__.__dict__
325 326
326 327 if state == 0:
327 328 if "." in text:
328 329 self.matches = self.attr_matches(text)
329 330 else:
330 331 self.matches = self.global_matches(text)
331 332 try:
332 333 return self.matches[state]
333 334 except IndexError:
334 335 return None
335 336
336 337 def global_matches(self, text):
337 338 """Compute matches when text is a simple name.
338 339
339 340 Return a list of all keywords, built-in functions and names currently
340 341 defined in self.namespace or self.global_namespace that match.
341 342
342 343 """
343 344 #print 'Completer->global_matches, txt=%r' % text # dbg
344 345 matches = []
345 346 match_append = matches.append
346 347 n = len(text)
347 348 for lst in [keyword.kwlist,
348 349 __builtin__.__dict__.keys(),
349 350 self.namespace.keys(),
350 351 self.global_namespace.keys()]:
351 352 for word in lst:
352 353 if word[:n] == text and word != "__builtins__":
353 354 match_append(word)
354 355 return matches
355 356
356 357 def attr_matches(self, text):
357 358 """Compute matches when text contains a dot.
358 359
359 360 Assuming the text is of the form NAME.NAME....[NAME], and is
360 361 evaluatable in self.namespace or self.global_namespace, it will be
361 362 evaluated and its attributes (as revealed by dir()) are used as
362 363 possible completions. (For class instances, class members are are
363 364 also considered.)
364 365
365 366 WARNING: this can still invoke arbitrary C code, if an object
366 367 with a __getattr__ hook is evaluated.
367 368
368 369 """
369 370
370 371 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
371 372 # Another option, seems to work great. Catches things like ''.<tab>
372 373 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
373 374
374 375 if m:
375 376 expr, attr = m.group(1, 3)
376 377 elif self.greedy:
377 378 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
378 379 if not m2:
379 380 return []
380 381 expr, attr = m2.group(1,2)
381 382 else:
382 383 return []
383 384
384 385 try:
385 386 obj = eval(expr, self.namespace)
386 387 except:
387 388 try:
388 389 obj = eval(expr, self.global_namespace)
389 390 except:
390 391 return []
391 392
392 393 words = dir2(obj)
393 394
394 395 try:
395 396 words = generics.complete_object(obj, words)
396 397 except TryNext:
397 398 pass
398 399 except Exception:
399 400 # Silence errors from completion function
400 401 #raise # dbg
401 402 pass
402 403 # Build match list to return
403 404 n = len(attr)
404 405 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
405 406 return res
406 407
407 408
408 409 class IPCompleter(Completer):
409 410 """Extension of the completer class with IPython-specific features"""
410 411
411 412 def _greedy_changed(self, name, old, new):
412 413 """update the splitter and readline delims when greedy is changed"""
413 414 if new:
414 415 self.splitter.set_delims(GREEDY_DELIMS)
415 416 else:
416 417 self.splitter.set_delims(DELIMS)
417 418
418 419 if self.readline:
419 420 self.readline.set_completer_delims(self.splitter.get_delims())
421
422 merge_completions = CBool(True, config=True,
423 help="""Whether to merge completion results into a single list
424
425 If False, only the completion results from the first non-empty
426 completer will be returned.
427 """
428 )
429 omit__names = Enum((0,1,2), default_value=2, config=True,
430 help="""Instruct the completer to omit private method names
431
432 Specifically, when completing on ``object.<tab>``.
433
434 When 2 [default]: all names that start with '_' will be excluded.
435
436 When 1: all 'magic' names (``__foo__``) will be excluded.
437
438 When 0: nothing will be excluded.
439 """
440 )
420 441
421 442 def __init__(self, shell=None, namespace=None, global_namespace=None,
422 omit__names=True, alias_table=None, use_readline=True,
423 config=None):
443 alias_table=None, use_readline=True,
444 config=None, **kwargs):
424 445 """IPCompleter() -> completer
425 446
426 447 Return a completer object suitable for use by the readline library
427 448 via readline.set_completer().
428 449
429 450 Inputs:
430 451
431 452 - shell: a pointer to the ipython shell itself. This is needed
432 453 because this completer knows about magic functions, and those can
433 454 only be accessed via the ipython instance.
434 455
435 456 - namespace: an optional dict where completions are performed.
436 457
437 458 - global_namespace: secondary optional dict for completions, to
438 459 handle cases (such as IPython embedded inside functions) where
439 460 both Python scopes are visible.
440 461
441 - The optional omit__names parameter sets the completer to omit the
442 'magic' names (__magicname__) for python objects unless the text
443 to be completed explicitly starts with one or more underscores.
444
445 462 - If alias_table is supplied, it should be a dictionary of aliases
446 463 to complete.
447 464
448 465 use_readline : bool, optional
449 466 If true, use the readline library. This completer can still function
450 467 without readline, though in that case callers must provide some extra
451 468 information on each call about the current line."""
452 469
453 470 self.magic_escape = ESC_MAGIC
454 471 self.splitter = CompletionSplitter()
455 472
456 473 # Readline configuration, only used by the rlcompleter method.
457 474 if use_readline:
458 475 # We store the right version of readline so that later code
459 476 import IPython.utils.rlineimpl as readline
460 477 self.readline = readline
461 478 else:
462 479 self.readline = None
463 480
464 481 # _greedy_changed() depends on splitter and readline being defined:
465 482 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
466 config=config)
483 config=config, **kwargs)
467 484
468 485 # List where completion matches will be stored
469 486 self.matches = []
470 self.omit__names = omit__names
471 self.merge_completions = shell.readline_merge_completions
472 487 self.shell = shell.shell
473 488 if alias_table is None:
474 489 alias_table = {}
475 490 self.alias_table = alias_table
476 491 # Regexp to split filenames with spaces in them
477 492 self.space_name_re = re.compile(r'([^\\] )')
478 493 # Hold a local ref. to glob.glob for speed
479 494 self.glob = glob.glob
480 495
481 496 # Determine if we are running on 'dumb' terminals, like (X)Emacs
482 497 # buffers, to avoid completion problems.
483 498 term = os.environ.get('TERM','xterm')
484 499 self.dumb_terminal = term in ['dumb','emacs']
485 500
486 501 # Special handling of backslashes needed in win32 platforms
487 502 if sys.platform == "win32":
488 503 self.clean_glob = self._clean_glob_win32
489 504 else:
490 505 self.clean_glob = self._clean_glob
491 506
492 507 # All active matcher routines for completion
493 508 self.matchers = [self.python_matches,
494 509 self.file_matches,
495 510 self.magic_matches,
496 511 self.alias_matches,
497 512 self.python_func_kw_matches,
498 513 ]
499 514
500 515 def all_completions(self, text):
501 516 """
502 517 Wrapper around the complete method for the benefit of emacs
503 518 and pydb.
504 519 """
505 520 return self.complete(text)[1]
506 521
507 522 def _clean_glob(self,text):
508 523 return self.glob("%s*" % text)
509 524
510 525 def _clean_glob_win32(self,text):
511 526 return [f.replace("\\","/")
512 527 for f in self.glob("%s*" % text)]
513 528
514 529 def file_matches(self, text):
515 530 """Match filenames, expanding ~USER type strings.
516 531
517 532 Most of the seemingly convoluted logic in this completer is an
518 533 attempt to handle filenames with spaces in them. And yet it's not
519 534 quite perfect, because Python's readline doesn't expose all of the
520 535 GNU readline details needed for this to be done correctly.
521 536
522 537 For a filename with a space in it, the printed completions will be
523 538 only the parts after what's already been typed (instead of the
524 539 full completions, as is normally done). I don't think with the
525 540 current (as of Python 2.3) Python readline it's possible to do
526 541 better."""
527 542
528 543 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
529 544
530 545 # chars that require escaping with backslash - i.e. chars
531 546 # that readline treats incorrectly as delimiters, but we
532 547 # don't want to treat as delimiters in filename matching
533 548 # when escaped with backslash
534 549 if text.startswith('!'):
535 550 text = text[1:]
536 551 text_prefix = '!'
537 552 else:
538 553 text_prefix = ''
539 554
540 555 text_until_cursor = self.text_until_cursor
541 556 # track strings with open quotes
542 557 open_quotes = has_open_quotes(text_until_cursor)
543 558
544 559 if '(' in text_until_cursor or '[' in text_until_cursor:
545 560 lsplit = text
546 561 else:
547 562 try:
548 563 # arg_split ~ shlex.split, but with unicode bugs fixed by us
549 564 lsplit = arg_split(text_until_cursor)[-1]
550 565 except ValueError:
551 566 # typically an unmatched ", or backslash without escaped char.
552 567 if open_quotes:
553 568 lsplit = text_until_cursor.split(open_quotes)[-1]
554 569 else:
555 570 return []
556 571 except IndexError:
557 572 # tab pressed on empty line
558 573 lsplit = ""
559 574
560 575 if not open_quotes and lsplit != protect_filename(lsplit):
561 576 # if protectables are found, do matching on the whole escaped name
562 577 has_protectables = True
563 578 text0,text = text,lsplit
564 579 else:
565 580 has_protectables = False
566 581 text = os.path.expanduser(text)
567 582
568 583 if text == "":
569 584 return [text_prefix + protect_filename(f) for f in self.glob("*")]
570 585
571 586 # Compute the matches from the filesystem
572 587 m0 = self.clean_glob(text.replace('\\',''))
573 588
574 589 if has_protectables:
575 590 # If we had protectables, we need to revert our changes to the
576 591 # beginning of filename so that we don't double-write the part
577 592 # of the filename we have so far
578 593 len_lsplit = len(lsplit)
579 594 matches = [text_prefix + text0 +
580 595 protect_filename(f[len_lsplit:]) for f in m0]
581 596 else:
582 597 if open_quotes:
583 598 # if we have a string with an open quote, we don't need to
584 599 # protect the names at all (and we _shouldn't_, as it
585 600 # would cause bugs when the filesystem call is made).
586 601 matches = m0
587 602 else:
588 603 matches = [text_prefix +
589 604 protect_filename(f) for f in m0]
590 605
591 606 #io.rprint('mm', matches) # dbg
592 607 return mark_dirs(matches)
593 608
594 609 def magic_matches(self, text):
595 610 """Match magics"""
596 611 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
597 612 # Get all shell magics now rather than statically, so magics loaded at
598 613 # runtime show up too
599 614 magics = self.shell.lsmagic()
600 615 pre = self.magic_escape
601 616 baretext = text.lstrip(pre)
602 617 return [ pre+m for m in magics if m.startswith(baretext)]
603 618
604 619 def alias_matches(self, text):
605 620 """Match internal system aliases"""
606 621 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
607 622
608 623 # if we are not in the first 'item', alias matching
609 624 # doesn't make sense - unless we are starting with 'sudo' command.
610 625 main_text = self.text_until_cursor.lstrip()
611 626 if ' ' in main_text and not main_text.startswith('sudo'):
612 627 return []
613 628 text = os.path.expanduser(text)
614 629 aliases = self.alias_table.keys()
615 630 if text == '':
616 631 return aliases
617 632 else:
618 633 return [a for a in aliases if a.startswith(text)]
619 634
620 635 def python_matches(self,text):
621 636 """Match attributes or global python names"""
622 637
623 638 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
624 639 if "." in text:
625 640 try:
626 641 matches = self.attr_matches(text)
627 642 if text.endswith('.') and self.omit__names:
628 643 if self.omit__names == 1:
629 644 # true if txt is _not_ a __ name, false otherwise:
630 645 no__name = (lambda txt:
631 646 re.match(r'.*\.__.*?__',txt) is None)
632 647 else:
633 648 # true if txt is _not_ a _ name, false otherwise:
634 649 no__name = (lambda txt:
635 650 re.match(r'.*\._.*?',txt) is None)
636 651 matches = filter(no__name, matches)
637 652 except NameError:
638 653 # catches <undefined attributes>.<tab>
639 654 matches = []
640 655 else:
641 656 matches = self.global_matches(text)
642 657
643 658 return matches
644 659
645 660 def _default_arguments(self, obj):
646 661 """Return the list of default arguments of obj if it is callable,
647 662 or empty list otherwise."""
648 663
649 664 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
650 665 # for classes, check for __init__,__new__
651 666 if inspect.isclass(obj):
652 667 obj = (getattr(obj,'__init__',None) or
653 668 getattr(obj,'__new__',None))
654 669 # for all others, check if they are __call__able
655 670 elif hasattr(obj, '__call__'):
656 671 obj = obj.__call__
657 672 # XXX: is there a way to handle the builtins ?
658 673 try:
659 674 args,_,_1,defaults = inspect.getargspec(obj)
660 675 if defaults:
661 676 return args[-len(defaults):]
662 677 except TypeError: pass
663 678 return []
664 679
665 680 def python_func_kw_matches(self,text):
666 681 """Match named parameters (kwargs) of the last open function"""
667 682
668 683 if "." in text: # a parameter cannot be dotted
669 684 return []
670 685 try: regexp = self.__funcParamsRegex
671 686 except AttributeError:
672 687 regexp = self.__funcParamsRegex = re.compile(r'''
673 688 '.*?' | # single quoted strings or
674 689 ".*?" | # double quoted strings or
675 690 \w+ | # identifier
676 691 \S # other characters
677 692 ''', re.VERBOSE | re.DOTALL)
678 693 # 1. find the nearest identifier that comes before an unclosed
679 694 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
680 695 tokens = regexp.findall(self.line_buffer)
681 696 tokens.reverse()
682 697 iterTokens = iter(tokens); openPar = 0
683 698 for token in iterTokens:
684 699 if token == ')':
685 700 openPar -= 1
686 701 elif token == '(':
687 702 openPar += 1
688 703 if openPar > 0:
689 704 # found the last unclosed parenthesis
690 705 break
691 706 else:
692 707 return []
693 708 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
694 709 ids = []
695 710 isId = re.compile(r'\w+$').match
696 711 while True:
697 712 try:
698 713 ids.append(iterTokens.next())
699 714 if not isId(ids[-1]):
700 715 ids.pop(); break
701 716 if not iterTokens.next() == '.':
702 717 break
703 718 except StopIteration:
704 719 break
705 720 # lookup the candidate callable matches either using global_matches
706 721 # or attr_matches for dotted names
707 722 if len(ids) == 1:
708 723 callableMatches = self.global_matches(ids[0])
709 724 else:
710 725 callableMatches = self.attr_matches('.'.join(ids[::-1]))
711 726 argMatches = []
712 727 for callableMatch in callableMatches:
713 728 try:
714 729 namedArgs = self._default_arguments(eval(callableMatch,
715 730 self.namespace))
716 731 except:
717 732 continue
718 733 for namedArg in namedArgs:
719 734 if namedArg.startswith(text):
720 735 argMatches.append("%s=" %namedArg)
721 736 return argMatches
722 737
723 738 def dispatch_custom_completer(self, text):
724 739 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
725 740 line = self.line_buffer
726 741 if not line.strip():
727 742 return None
728 743
729 744 # Create a little structure to pass all the relevant information about
730 745 # the current completion to any custom completer.
731 746 event = Bunch()
732 747 event.line = line
733 748 event.symbol = text
734 749 cmd = line.split(None,1)[0]
735 750 event.command = cmd
736 751 event.text_until_cursor = self.text_until_cursor
737 752
738 753 #print "\ncustom:{%s]\n" % event # dbg
739 754
740 755 # for foo etc, try also to find completer for %foo
741 756 if not cmd.startswith(self.magic_escape):
742 757 try_magic = self.custom_completers.s_matches(
743 758 self.magic_escape + cmd)
744 759 else:
745 760 try_magic = []
746 761
747 762 for c in itertools.chain(self.custom_completers.s_matches(cmd),
748 763 try_magic,
749 764 self.custom_completers.flat_matches(self.text_until_cursor)):
750 765 #print "try",c # dbg
751 766 try:
752 767 res = c(event)
753 768 if res:
754 769 # first, try case sensitive match
755 770 withcase = [r for r in res if r.startswith(text)]
756 771 if withcase:
757 772 return withcase
758 773 # if none, then case insensitive ones are ok too
759 774 text_low = text.lower()
760 775 return [r for r in res if r.lower().startswith(text_low)]
761 776 except TryNext:
762 777 pass
763 778
764 779 return None
765 780
766 781 def complete(self, text=None, line_buffer=None, cursor_pos=None):
767 782 """Find completions for the given text and line context.
768 783
769 784 This is called successively with state == 0, 1, 2, ... until it
770 785 returns None. The completion should begin with 'text'.
771 786
772 787 Note that both the text and the line_buffer are optional, but at least
773 788 one of them must be given.
774 789
775 790 Parameters
776 791 ----------
777 792 text : string, optional
778 793 Text to perform the completion on. If not given, the line buffer
779 794 is split using the instance's CompletionSplitter object.
780 795
781 796 line_buffer : string, optional
782 797 If not given, the completer attempts to obtain the current line
783 798 buffer via readline. This keyword allows clients which are
784 799 requesting for text completions in non-readline contexts to inform
785 800 the completer of the entire text.
786 801
787 802 cursor_pos : int, optional
788 803 Index of the cursor in the full line buffer. Should be provided by
789 804 remote frontends where kernel has no access to frontend state.
790 805
791 806 Returns
792 807 -------
793 808 text : str
794 809 Text that was actually used in the completion.
795 810
796 811 matches : list
797 812 A list of completion matches.
798 813 """
799 814 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
800 815
801 816 # if the cursor position isn't given, the only sane assumption we can
802 817 # make is that it's at the end of the line (the common case)
803 818 if cursor_pos is None:
804 819 cursor_pos = len(line_buffer) if text is None else len(text)
805 820
806 821 # if text is either None or an empty string, rely on the line buffer
807 822 if not text:
808 823 text = self.splitter.split_line(line_buffer, cursor_pos)
809 824
810 825 # If no line buffer is given, assume the input text is all there was
811 826 if line_buffer is None:
812 827 line_buffer = text
813 828
814 829 self.line_buffer = line_buffer
815 830 self.text_until_cursor = self.line_buffer[:cursor_pos]
816 831 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
817 832
818 833 # Start with a clean slate of completions
819 834 self.matches[:] = []
820 835 custom_res = self.dispatch_custom_completer(text)
821 836 if custom_res is not None:
822 837 # did custom completers produce something?
823 838 self.matches = custom_res
824 839 else:
825 840 # Extend the list of completions with the results of each
826 841 # matcher, so we return results to the user from all
827 842 # namespaces.
828 843 if self.merge_completions:
829 844 self.matches = []
830 845 for matcher in self.matchers:
831 846 try:
832 847 self.matches.extend(matcher(text))
833 848 except:
834 849 # Show the ugly traceback if the matcher causes an
835 850 # exception, but do NOT crash the kernel!
836 851 sys.excepthook(*sys.exc_info())
837 852 else:
838 853 for matcher in self.matchers:
839 854 self.matches = matcher(text)
840 855 if self.matches:
841 856 break
842 857 # FIXME: we should extend our api to return a dict with completions for
843 858 # different types of objects. The rlcomplete() method could then
844 859 # simply collapse the dict into a list for readline, but we'd have
845 860 # richer completion semantics in other evironments.
846 861 self.matches = sorted(set(self.matches))
847 862 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
848 863 return text, self.matches
849 864
850 865 def rlcomplete(self, text, state):
851 866 """Return the state-th possible completion for 'text'.
852 867
853 868 This is called successively with state == 0, 1, 2, ... until it
854 869 returns None. The completion should begin with 'text'.
855 870
856 871 Parameters
857 872 ----------
858 873 text : string
859 874 Text to perform the completion on.
860 875
861 876 state : int
862 877 Counter used by readline.
863 878 """
864 879 if state==0:
865 880
866 881 self.line_buffer = line_buffer = self.readline.get_line_buffer()
867 882 cursor_pos = self.readline.get_endidx()
868 883
869 884 #io.rprint("\nRLCOMPLETE: %r %r %r" %
870 885 # (text, line_buffer, cursor_pos) ) # dbg
871 886
872 887 # if there is only a tab on a line with only whitespace, instead of
873 888 # the mostly useless 'do you want to see all million completions'
874 889 # message, just do the right thing and give the user his tab!
875 890 # Incidentally, this enables pasting of tabbed text from an editor
876 891 # (as long as autoindent is off).
877 892
878 893 # It should be noted that at least pyreadline still shows file
879 894 # completions - is there a way around it?
880 895
881 896 # don't apply this on 'dumb' terminals, such as emacs buffers, so
882 897 # we don't interfere with their own tab-completion mechanism.
883 898 if not (self.dumb_terminal or line_buffer.strip()):
884 899 self.readline.insert_text('\t')
885 900 sys.stdout.flush()
886 901 return None
887 902
888 903 # Note: debugging exceptions that may occur in completion is very
889 904 # tricky, because readline unconditionally silences them. So if
890 905 # during development you suspect a bug in the completion code, turn
891 906 # this flag on temporarily by uncommenting the second form (don't
892 907 # flip the value in the first line, as the '# dbg' marker can be
893 908 # automatically detected and is used elsewhere).
894 909 DEBUG = False
895 910 #DEBUG = True # dbg
896 911 if DEBUG:
897 912 try:
898 913 self.complete(text, line_buffer, cursor_pos)
899 914 except:
900 915 import traceback; traceback.print_exc()
901 916 else:
902 917 # The normal production version is here
903 918
904 919 # This method computes the self.matches array
905 920 self.complete(text, line_buffer, cursor_pos)
906 921
907 922 try:
908 923 return self.matches[state]
909 924 except IndexError:
910 925 return None
@@ -1,2695 +1,2692 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__ as builtin_mod
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 try:
33 33 from contextlib import nested
34 34 except:
35 35 from IPython.utils.nested_context import nested
36 36
37 37 from IPython.config.configurable import SingletonConfigurable
38 38 from IPython.core import debugger, oinspect
39 39 from IPython.core import history as ipcorehist
40 40 from IPython.core import page
41 41 from IPython.core import prefilter
42 42 from IPython.core import shadowns
43 43 from IPython.core import ultratb
44 44 from IPython.core.alias import AliasManager, AliasError
45 45 from IPython.core.autocall import ExitAutocall
46 46 from IPython.core.builtin_trap import BuiltinTrap
47 47 from IPython.core.compilerop import CachingCompiler
48 48 from IPython.core.display_trap import DisplayTrap
49 49 from IPython.core.displayhook import DisplayHook
50 50 from IPython.core.displaypub import DisplayPublisher
51 51 from IPython.core.error import TryNext, UsageError
52 52 from IPython.core.extensions import ExtensionManager
53 53 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
54 54 from IPython.core.formatters import DisplayFormatter
55 55 from IPython.core.history import HistoryManager
56 56 from IPython.core.inputsplitter import IPythonInputSplitter
57 57 from IPython.core.logger import Logger
58 58 from IPython.core.macro import Macro
59 59 from IPython.core.magic import Magic
60 60 from IPython.core.payload import PayloadManager
61 61 from IPython.core.plugin import PluginManager
62 62 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
63 63 from IPython.core.profiledir import ProfileDir
64 64 from IPython.external.Itpl import ItplNS
65 65 from IPython.utils import PyColorize
66 66 from IPython.utils import io
67 67 from IPython.utils import py3compat
68 68 from IPython.utils.doctestreload import doctest_reload
69 69 from IPython.utils.io import ask_yes_no, rprint
70 70 from IPython.utils.ipstruct import Struct
71 71 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
72 72 from IPython.utils.pickleshare import PickleShareDB
73 73 from IPython.utils.process import system, getoutput
74 74 from IPython.utils.strdispatch import StrDispatch
75 75 from IPython.utils.syspathcontext import prepended_to_syspath
76 76 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
77 77 from IPython.utils.traitlets import (Int, CBool, CaselessStrEnum, Enum,
78 78 List, Unicode, Instance, Type)
79 79 from IPython.utils.warn import warn, error, fatal
80 80 import IPython.core.hooks
81 81
82 82 #-----------------------------------------------------------------------------
83 83 # Globals
84 84 #-----------------------------------------------------------------------------
85 85
86 86 # compiled regexps for autoindent management
87 87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 88
89 89 #-----------------------------------------------------------------------------
90 90 # Utilities
91 91 #-----------------------------------------------------------------------------
92 92
93 93 def softspace(file, newvalue):
94 94 """Copied from code.py, to remove the dependency"""
95 95
96 96 oldvalue = 0
97 97 try:
98 98 oldvalue = file.softspace
99 99 except AttributeError:
100 100 pass
101 101 try:
102 102 file.softspace = newvalue
103 103 except (AttributeError, TypeError):
104 104 # "attribute-less object" or "read-only attributes"
105 105 pass
106 106 return oldvalue
107 107
108 108
109 109 def no_op(*a, **kw): pass
110 110
111 111 class NoOpContext(object):
112 112 def __enter__(self): pass
113 113 def __exit__(self, type, value, traceback): pass
114 114 no_op_context = NoOpContext()
115 115
116 116 class SpaceInInput(Exception): pass
117 117
118 118 class Bunch: pass
119 119
120 120
121 121 def get_default_colors():
122 122 if sys.platform=='darwin':
123 123 return "LightBG"
124 124 elif os.name=='nt':
125 125 return 'Linux'
126 126 else:
127 127 return 'Linux'
128 128
129 129
130 130 class SeparateUnicode(Unicode):
131 131 """A Unicode subclass to validate separate_in, separate_out, etc.
132 132
133 133 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
134 134 """
135 135
136 136 def validate(self, obj, value):
137 137 if value == '0': value = ''
138 138 value = value.replace('\\n','\n')
139 139 return super(SeparateUnicode, self).validate(obj, value)
140 140
141 141
142 142 class ReadlineNoRecord(object):
143 143 """Context manager to execute some code, then reload readline history
144 144 so that interactive input to the code doesn't appear when pressing up."""
145 145 def __init__(self, shell):
146 146 self.shell = shell
147 147 self._nested_level = 0
148 148
149 149 def __enter__(self):
150 150 if self._nested_level == 0:
151 151 try:
152 152 self.orig_length = self.current_length()
153 153 self.readline_tail = self.get_readline_tail()
154 154 except (AttributeError, IndexError): # Can fail with pyreadline
155 155 self.orig_length, self.readline_tail = 999999, []
156 156 self._nested_level += 1
157 157
158 158 def __exit__(self, type, value, traceback):
159 159 self._nested_level -= 1
160 160 if self._nested_level == 0:
161 161 # Try clipping the end if it's got longer
162 162 try:
163 163 e = self.current_length() - self.orig_length
164 164 if e > 0:
165 165 for _ in range(e):
166 166 self.shell.readline.remove_history_item(self.orig_length)
167 167
168 168 # If it still doesn't match, just reload readline history.
169 169 if self.current_length() != self.orig_length \
170 170 or self.get_readline_tail() != self.readline_tail:
171 171 self.shell.refill_readline_hist()
172 172 except (AttributeError, IndexError):
173 173 pass
174 174 # Returning False will cause exceptions to propagate
175 175 return False
176 176
177 177 def current_length(self):
178 178 return self.shell.readline.get_current_history_length()
179 179
180 180 def get_readline_tail(self, n=10):
181 181 """Get the last n items in readline history."""
182 182 end = self.shell.readline.get_current_history_length() + 1
183 183 start = max(end-n, 1)
184 184 ghi = self.shell.readline.get_history_item
185 185 return [ghi(x) for x in range(start, end)]
186 186
187 187
188 188 _autocall_help = """
189 189 Make IPython automatically call any callable object even if
190 190 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
191 191 automatically. The value can be '0' to disable the feature, '1' for 'smart'
192 192 autocall, where it is not applied if there are no more arguments on the line,
193 193 and '2' for 'full' autocall, where all callable objects are automatically
194 194 called (even if no arguments are present). The default is '1'.
195 195 """
196 196
197 197 #-----------------------------------------------------------------------------
198 198 # Main IPython class
199 199 #-----------------------------------------------------------------------------
200 200
201 201 class InteractiveShell(SingletonConfigurable, Magic):
202 202 """An enhanced, interactive shell for Python."""
203 203
204 204 _instance = None
205 205
206 206 autocall = Enum((0,1,2), default_value=1, config=True, help=
207 207 """
208 208 Make IPython automatically call any callable object even if you didn't
209 209 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
210 210 automatically. The value can be '0' to disable the feature, '1' for
211 211 'smart' autocall, where it is not applied if there are no more
212 212 arguments on the line, and '2' for 'full' autocall, where all callable
213 213 objects are automatically called (even if no arguments are present).
214 214 The default is '1'.
215 215 """
216 216 )
217 217 # TODO: remove all autoindent logic and put into frontends.
218 218 # We can't do this yet because even runlines uses the autoindent.
219 219 autoindent = CBool(True, config=True, help=
220 220 """
221 221 Autoindent IPython code entered interactively.
222 222 """
223 223 )
224 224 automagic = CBool(True, config=True, help=
225 225 """
226 226 Enable magic commands to be called without the leading %.
227 227 """
228 228 )
229 229 cache_size = Int(1000, config=True, help=
230 230 """
231 231 Set the size of the output cache. The default is 1000, you can
232 232 change it permanently in your config file. Setting it to 0 completely
233 233 disables the caching system, and the minimum value accepted is 20 (if
234 234 you provide a value less than 20, it is reset to 0 and a warning is
235 235 issued). This limit is defined because otherwise you'll spend more
236 236 time re-flushing a too small cache than working
237 237 """
238 238 )
239 239 color_info = CBool(True, config=True, help=
240 240 """
241 241 Use colors for displaying information about objects. Because this
242 242 information is passed through a pager (like 'less'), and some pagers
243 243 get confused with color codes, this capability can be turned off.
244 244 """
245 245 )
246 246 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
247 247 default_value=get_default_colors(), config=True,
248 248 help="Set the color scheme (NoColor, Linux, or LightBG)."
249 249 )
250 250 colors_force = CBool(False, help=
251 251 """
252 252 Force use of ANSI color codes, regardless of OS and readline
253 253 availability.
254 254 """
255 255 # FIXME: This is essentially a hack to allow ZMQShell to show colors
256 256 # without readline on Win32. When the ZMQ formatting system is
257 257 # refactored, this should be removed.
258 258 )
259 259 debug = CBool(False, config=True)
260 260 deep_reload = CBool(False, config=True, help=
261 261 """
262 262 Enable deep (recursive) reloading by default. IPython can use the
263 263 deep_reload module which reloads changes in modules recursively (it
264 264 replaces the reload() function, so you don't need to change anything to
265 265 use it). deep_reload() forces a full reload of modules whose code may
266 266 have changed, which the default reload() function does not. When
267 267 deep_reload is off, IPython will use the normal reload(), but
268 268 deep_reload will still be available as dreload().
269 269 """
270 270 )
271 271 display_formatter = Instance(DisplayFormatter)
272 272 displayhook_class = Type(DisplayHook)
273 273 display_pub_class = Type(DisplayPublisher)
274 274
275 275 exit_now = CBool(False)
276 276 exiter = Instance(ExitAutocall)
277 277 def _exiter_default(self):
278 278 return ExitAutocall(self)
279 279 # Monotonically increasing execution counter
280 280 execution_count = Int(1)
281 281 filename = Unicode("<ipython console>")
282 282 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
283 283
284 284 # Input splitter, to split entire cells of input into either individual
285 285 # interactive statements or whole blocks.
286 286 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
287 287 (), {})
288 288 logstart = CBool(False, config=True, help=
289 289 """
290 290 Start logging to the default log file.
291 291 """
292 292 )
293 293 logfile = Unicode('', config=True, help=
294 294 """
295 295 The name of the logfile to use.
296 296 """
297 297 )
298 298 logappend = Unicode('', config=True, help=
299 299 """
300 300 Start logging to the given file in append mode.
301 301 """
302 302 )
303 303 object_info_string_level = Enum((0,1,2), default_value=0,
304 304 config=True)
305 305 pdb = CBool(False, config=True, help=
306 306 """
307 307 Automatically call the pdb debugger after every exception.
308 308 """
309 309 )
310 310 multiline_history = CBool(sys.platform != 'win32', config=True,
311 311 help="Store multiple line spanning cells as a single entry in history."
312 312 )
313 313
314 314 prompt_in1 = Unicode('In [\\#]: ', config=True)
315 315 prompt_in2 = Unicode(' .\\D.: ', config=True)
316 316 prompt_out = Unicode('Out[\\#]: ', config=True)
317 317 prompts_pad_left = CBool(True, config=True)
318 318 quiet = CBool(False, config=True)
319 319
320 320 history_length = Int(10000, config=True)
321 321
322 322 # The readline stuff will eventually be moved to the terminal subclass
323 323 # but for now, we can't do that as readline is welded in everywhere.
324 324 readline_use = CBool(True, config=True)
325 readline_merge_completions = CBool(True, config=True)
326 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
327 325 readline_remove_delims = Unicode('-/~', config=True)
328 326 # don't use \M- bindings by default, because they
329 327 # conflict with 8-bit encodings. See gh-58,gh-88
330 328 readline_parse_and_bind = List([
331 329 'tab: complete',
332 330 '"\C-l": clear-screen',
333 331 'set show-all-if-ambiguous on',
334 332 '"\C-o": tab-insert',
335 333 '"\C-r": reverse-search-history',
336 334 '"\C-s": forward-search-history',
337 335 '"\C-p": history-search-backward',
338 336 '"\C-n": history-search-forward',
339 337 '"\e[A": history-search-backward',
340 338 '"\e[B": history-search-forward',
341 339 '"\C-k": kill-line',
342 340 '"\C-u": unix-line-discard',
343 341 ], allow_none=False, config=True)
344 342
345 343 # TODO: this part of prompt management should be moved to the frontends.
346 344 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
347 345 separate_in = SeparateUnicode('\n', config=True)
348 346 separate_out = SeparateUnicode('', config=True)
349 347 separate_out2 = SeparateUnicode('', config=True)
350 348 wildcards_case_sensitive = CBool(True, config=True)
351 349 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
352 350 default_value='Context', config=True)
353 351
354 352 # Subcomponents of InteractiveShell
355 353 alias_manager = Instance('IPython.core.alias.AliasManager')
356 354 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
357 355 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
358 356 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
359 357 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
360 358 plugin_manager = Instance('IPython.core.plugin.PluginManager')
361 359 payload_manager = Instance('IPython.core.payload.PayloadManager')
362 360 history_manager = Instance('IPython.core.history.HistoryManager')
363 361
364 362 profile_dir = Instance('IPython.core.application.ProfileDir')
365 363 @property
366 364 def profile(self):
367 365 if self.profile_dir is not None:
368 366 name = os.path.basename(self.profile_dir.location)
369 367 return name.replace('profile_','')
370 368
371 369
372 370 # Private interface
373 371 _post_execute = Instance(dict)
374 372
375 373 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
376 374 user_ns=None, user_global_ns=None,
377 375 custom_exceptions=((), None)):
378 376
379 377 # This is where traits with a config_key argument are updated
380 378 # from the values on config.
381 379 super(InteractiveShell, self).__init__(config=config)
382 380 self.configurables = [self]
383 381
384 382 # These are relatively independent and stateless
385 383 self.init_ipython_dir(ipython_dir)
386 384 self.init_profile_dir(profile_dir)
387 385 self.init_instance_attrs()
388 386 self.init_environment()
389 387
390 388 # Create namespaces (user_ns, user_global_ns, etc.)
391 389 self.init_create_namespaces(user_ns, user_global_ns)
392 390 # This has to be done after init_create_namespaces because it uses
393 391 # something in self.user_ns, but before init_sys_modules, which
394 392 # is the first thing to modify sys.
395 393 # TODO: When we override sys.stdout and sys.stderr before this class
396 394 # is created, we are saving the overridden ones here. Not sure if this
397 395 # is what we want to do.
398 396 self.save_sys_module_state()
399 397 self.init_sys_modules()
400 398
401 399 # While we're trying to have each part of the code directly access what
402 400 # it needs without keeping redundant references to objects, we have too
403 401 # much legacy code that expects ip.db to exist.
404 402 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
405 403
406 404 self.init_history()
407 405 self.init_encoding()
408 406 self.init_prefilter()
409 407
410 408 Magic.__init__(self, self)
411 409
412 410 self.init_syntax_highlighting()
413 411 self.init_hooks()
414 412 self.init_pushd_popd_magic()
415 413 # self.init_traceback_handlers use to be here, but we moved it below
416 414 # because it and init_io have to come after init_readline.
417 415 self.init_user_ns()
418 416 self.init_logger()
419 417 self.init_alias()
420 418 self.init_builtins()
421 419
422 420 # pre_config_initialization
423 421
424 422 # The next section should contain everything that was in ipmaker.
425 423 self.init_logstart()
426 424
427 425 # The following was in post_config_initialization
428 426 self.init_inspector()
429 427 # init_readline() must come before init_io(), because init_io uses
430 428 # readline related things.
431 429 self.init_readline()
432 430 # We save this here in case user code replaces raw_input, but it needs
433 431 # to be after init_readline(), because PyPy's readline works by replacing
434 432 # raw_input.
435 433 if py3compat.PY3:
436 434 self.raw_input_original = input
437 435 else:
438 436 self.raw_input_original = raw_input
439 437 # init_completer must come after init_readline, because it needs to
440 438 # know whether readline is present or not system-wide to configure the
441 439 # completers, since the completion machinery can now operate
442 440 # independently of readline (e.g. over the network)
443 441 self.init_completer()
444 442 # TODO: init_io() needs to happen before init_traceback handlers
445 443 # because the traceback handlers hardcode the stdout/stderr streams.
446 444 # This logic in in debugger.Pdb and should eventually be changed.
447 445 self.init_io()
448 446 self.init_traceback_handlers(custom_exceptions)
449 447 self.init_prompts()
450 448 self.init_display_formatter()
451 449 self.init_display_pub()
452 450 self.init_displayhook()
453 451 self.init_reload_doctest()
454 452 self.init_magics()
455 453 self.init_pdb()
456 454 self.init_extension_manager()
457 455 self.init_plugin_manager()
458 456 self.init_payload()
459 457 self.hooks.late_startup_hook()
460 458 atexit.register(self.atexit_operations)
461 459
462 460 def get_ipython(self):
463 461 """Return the currently running IPython instance."""
464 462 return self
465 463
466 464 #-------------------------------------------------------------------------
467 465 # Trait changed handlers
468 466 #-------------------------------------------------------------------------
469 467
470 468 def _ipython_dir_changed(self, name, new):
471 469 if not os.path.isdir(new):
472 470 os.makedirs(new, mode = 0777)
473 471
474 472 def set_autoindent(self,value=None):
475 473 """Set the autoindent flag, checking for readline support.
476 474
477 475 If called with no arguments, it acts as a toggle."""
478 476
479 477 if value != 0 and not self.has_readline:
480 478 if os.name == 'posix':
481 479 warn("The auto-indent feature requires the readline library")
482 480 self.autoindent = 0
483 481 return
484 482 if value is None:
485 483 self.autoindent = not self.autoindent
486 484 else:
487 485 self.autoindent = value
488 486
489 487 #-------------------------------------------------------------------------
490 488 # init_* methods called by __init__
491 489 #-------------------------------------------------------------------------
492 490
493 491 def init_ipython_dir(self, ipython_dir):
494 492 if ipython_dir is not None:
495 493 self.ipython_dir = ipython_dir
496 494 return
497 495
498 496 self.ipython_dir = get_ipython_dir()
499 497
500 498 def init_profile_dir(self, profile_dir):
501 499 if profile_dir is not None:
502 500 self.profile_dir = profile_dir
503 501 return
504 502 self.profile_dir =\
505 503 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
506 504
507 505 def init_instance_attrs(self):
508 506 self.more = False
509 507
510 508 # command compiler
511 509 self.compile = CachingCompiler()
512 510
513 511 # Make an empty namespace, which extension writers can rely on both
514 512 # existing and NEVER being used by ipython itself. This gives them a
515 513 # convenient location for storing additional information and state
516 514 # their extensions may require, without fear of collisions with other
517 515 # ipython names that may develop later.
518 516 self.meta = Struct()
519 517
520 518 # Temporary files used for various purposes. Deleted at exit.
521 519 self.tempfiles = []
522 520
523 521 # Keep track of readline usage (later set by init_readline)
524 522 self.has_readline = False
525 523
526 524 # keep track of where we started running (mainly for crash post-mortem)
527 525 # This is not being used anywhere currently.
528 526 self.starting_dir = os.getcwdu()
529 527
530 528 # Indentation management
531 529 self.indent_current_nsp = 0
532 530
533 531 # Dict to track post-execution functions that have been registered
534 532 self._post_execute = {}
535 533
536 534 def init_environment(self):
537 535 """Any changes we need to make to the user's environment."""
538 536 pass
539 537
540 538 def init_encoding(self):
541 539 # Get system encoding at startup time. Certain terminals (like Emacs
542 540 # under Win32 have it set to None, and we need to have a known valid
543 541 # encoding to use in the raw_input() method
544 542 try:
545 543 self.stdin_encoding = sys.stdin.encoding or 'ascii'
546 544 except AttributeError:
547 545 self.stdin_encoding = 'ascii'
548 546
549 547 def init_syntax_highlighting(self):
550 548 # Python source parser/formatter for syntax highlighting
551 549 pyformat = PyColorize.Parser().format
552 550 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
553 551
554 552 def init_pushd_popd_magic(self):
555 553 # for pushd/popd management
556 554 try:
557 555 self.home_dir = get_home_dir()
558 556 except HomeDirError, msg:
559 557 fatal(msg)
560 558
561 559 self.dir_stack = []
562 560
563 561 def init_logger(self):
564 562 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
565 563 logmode='rotate')
566 564
567 565 def init_logstart(self):
568 566 """Initialize logging in case it was requested at the command line.
569 567 """
570 568 if self.logappend:
571 569 self.magic_logstart(self.logappend + ' append')
572 570 elif self.logfile:
573 571 self.magic_logstart(self.logfile)
574 572 elif self.logstart:
575 573 self.magic_logstart()
576 574
577 575 def init_builtins(self):
578 576 self.builtin_trap = BuiltinTrap(shell=self)
579 577
580 578 def init_inspector(self):
581 579 # Object inspector
582 580 self.inspector = oinspect.Inspector(oinspect.InspectColors,
583 581 PyColorize.ANSICodeColors,
584 582 'NoColor',
585 583 self.object_info_string_level)
586 584
587 585 def init_io(self):
588 586 # This will just use sys.stdout and sys.stderr. If you want to
589 587 # override sys.stdout and sys.stderr themselves, you need to do that
590 588 # *before* instantiating this class, because io holds onto
591 589 # references to the underlying streams.
592 590 if sys.platform == 'win32' and self.has_readline:
593 591 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
594 592 else:
595 593 io.stdout = io.IOStream(sys.stdout)
596 594 io.stderr = io.IOStream(sys.stderr)
597 595
598 596 def init_prompts(self):
599 597 # TODO: This is a pass for now because the prompts are managed inside
600 598 # the DisplayHook. Once there is a separate prompt manager, this
601 599 # will initialize that object and all prompt related information.
602 600 pass
603 601
604 602 def init_display_formatter(self):
605 603 self.display_formatter = DisplayFormatter(config=self.config)
606 604 self.configurables.append(self.display_formatter)
607 605
608 606 def init_display_pub(self):
609 607 self.display_pub = self.display_pub_class(config=self.config)
610 608 self.configurables.append(self.display_pub)
611 609
612 610 def init_displayhook(self):
613 611 # Initialize displayhook, set in/out prompts and printing system
614 612 self.displayhook = self.displayhook_class(
615 613 config=self.config,
616 614 shell=self,
617 615 cache_size=self.cache_size,
618 616 input_sep = self.separate_in,
619 617 output_sep = self.separate_out,
620 618 output_sep2 = self.separate_out2,
621 619 ps1 = self.prompt_in1,
622 620 ps2 = self.prompt_in2,
623 621 ps_out = self.prompt_out,
624 622 pad_left = self.prompts_pad_left
625 623 )
626 624 self.configurables.append(self.displayhook)
627 625 # This is a context manager that installs/revmoes the displayhook at
628 626 # the appropriate time.
629 627 self.display_trap = DisplayTrap(hook=self.displayhook)
630 628
631 629 def init_reload_doctest(self):
632 630 # Do a proper resetting of doctest, including the necessary displayhook
633 631 # monkeypatching
634 632 try:
635 633 doctest_reload()
636 634 except ImportError:
637 635 warn("doctest module does not exist.")
638 636
639 637 #-------------------------------------------------------------------------
640 638 # Things related to injections into the sys module
641 639 #-------------------------------------------------------------------------
642 640
643 641 def save_sys_module_state(self):
644 642 """Save the state of hooks in the sys module.
645 643
646 644 This has to be called after self.user_ns is created.
647 645 """
648 646 self._orig_sys_module_state = {}
649 647 self._orig_sys_module_state['stdin'] = sys.stdin
650 648 self._orig_sys_module_state['stdout'] = sys.stdout
651 649 self._orig_sys_module_state['stderr'] = sys.stderr
652 650 self._orig_sys_module_state['excepthook'] = sys.excepthook
653 651 try:
654 652 self._orig_sys_modules_main_name = self.user_ns['__name__']
655 653 except KeyError:
656 654 pass
657 655
658 656 def restore_sys_module_state(self):
659 657 """Restore the state of the sys module."""
660 658 try:
661 659 for k, v in self._orig_sys_module_state.iteritems():
662 660 setattr(sys, k, v)
663 661 except AttributeError:
664 662 pass
665 663 # Reset what what done in self.init_sys_modules
666 664 try:
667 665 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
668 666 except (AttributeError, KeyError):
669 667 pass
670 668
671 669 #-------------------------------------------------------------------------
672 670 # Things related to hooks
673 671 #-------------------------------------------------------------------------
674 672
675 673 def init_hooks(self):
676 674 # hooks holds pointers used for user-side customizations
677 675 self.hooks = Struct()
678 676
679 677 self.strdispatchers = {}
680 678
681 679 # Set all default hooks, defined in the IPython.hooks module.
682 680 hooks = IPython.core.hooks
683 681 for hook_name in hooks.__all__:
684 682 # default hooks have priority 100, i.e. low; user hooks should have
685 683 # 0-100 priority
686 684 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
687 685
688 686 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
689 687 """set_hook(name,hook) -> sets an internal IPython hook.
690 688
691 689 IPython exposes some of its internal API as user-modifiable hooks. By
692 690 adding your function to one of these hooks, you can modify IPython's
693 691 behavior to call at runtime your own routines."""
694 692
695 693 # At some point in the future, this should validate the hook before it
696 694 # accepts it. Probably at least check that the hook takes the number
697 695 # of args it's supposed to.
698 696
699 697 f = types.MethodType(hook,self)
700 698
701 699 # check if the hook is for strdispatcher first
702 700 if str_key is not None:
703 701 sdp = self.strdispatchers.get(name, StrDispatch())
704 702 sdp.add_s(str_key, f, priority )
705 703 self.strdispatchers[name] = sdp
706 704 return
707 705 if re_key is not None:
708 706 sdp = self.strdispatchers.get(name, StrDispatch())
709 707 sdp.add_re(re.compile(re_key), f, priority )
710 708 self.strdispatchers[name] = sdp
711 709 return
712 710
713 711 dp = getattr(self.hooks, name, None)
714 712 if name not in IPython.core.hooks.__all__:
715 713 print "Warning! Hook '%s' is not one of %s" % \
716 714 (name, IPython.core.hooks.__all__ )
717 715 if not dp:
718 716 dp = IPython.core.hooks.CommandChainDispatcher()
719 717
720 718 try:
721 719 dp.add(f,priority)
722 720 except AttributeError:
723 721 # it was not commandchain, plain old func - replace
724 722 dp = f
725 723
726 724 setattr(self.hooks,name, dp)
727 725
728 726 def register_post_execute(self, func):
729 727 """Register a function for calling after code execution.
730 728 """
731 729 if not callable(func):
732 730 raise ValueError('argument %s must be callable' % func)
733 731 self._post_execute[func] = True
734 732
735 733 #-------------------------------------------------------------------------
736 734 # Things related to the "main" module
737 735 #-------------------------------------------------------------------------
738 736
739 737 def new_main_mod(self,ns=None):
740 738 """Return a new 'main' module object for user code execution.
741 739 """
742 740 main_mod = self._user_main_module
743 741 init_fakemod_dict(main_mod,ns)
744 742 return main_mod
745 743
746 744 def cache_main_mod(self,ns,fname):
747 745 """Cache a main module's namespace.
748 746
749 747 When scripts are executed via %run, we must keep a reference to the
750 748 namespace of their __main__ module (a FakeModule instance) around so
751 749 that Python doesn't clear it, rendering objects defined therein
752 750 useless.
753 751
754 752 This method keeps said reference in a private dict, keyed by the
755 753 absolute path of the module object (which corresponds to the script
756 754 path). This way, for multiple executions of the same script we only
757 755 keep one copy of the namespace (the last one), thus preventing memory
758 756 leaks from old references while allowing the objects from the last
759 757 execution to be accessible.
760 758
761 759 Note: we can not allow the actual FakeModule instances to be deleted,
762 760 because of how Python tears down modules (it hard-sets all their
763 761 references to None without regard for reference counts). This method
764 762 must therefore make a *copy* of the given namespace, to allow the
765 763 original module's __dict__ to be cleared and reused.
766 764
767 765
768 766 Parameters
769 767 ----------
770 768 ns : a namespace (a dict, typically)
771 769
772 770 fname : str
773 771 Filename associated with the namespace.
774 772
775 773 Examples
776 774 --------
777 775
778 776 In [10]: import IPython
779 777
780 778 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
781 779
782 780 In [12]: IPython.__file__ in _ip._main_ns_cache
783 781 Out[12]: True
784 782 """
785 783 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
786 784
787 785 def clear_main_mod_cache(self):
788 786 """Clear the cache of main modules.
789 787
790 788 Mainly for use by utilities like %reset.
791 789
792 790 Examples
793 791 --------
794 792
795 793 In [15]: import IPython
796 794
797 795 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
798 796
799 797 In [17]: len(_ip._main_ns_cache) > 0
800 798 Out[17]: True
801 799
802 800 In [18]: _ip.clear_main_mod_cache()
803 801
804 802 In [19]: len(_ip._main_ns_cache) == 0
805 803 Out[19]: True
806 804 """
807 805 self._main_ns_cache.clear()
808 806
809 807 #-------------------------------------------------------------------------
810 808 # Things related to debugging
811 809 #-------------------------------------------------------------------------
812 810
813 811 def init_pdb(self):
814 812 # Set calling of pdb on exceptions
815 813 # self.call_pdb is a property
816 814 self.call_pdb = self.pdb
817 815
818 816 def _get_call_pdb(self):
819 817 return self._call_pdb
820 818
821 819 def _set_call_pdb(self,val):
822 820
823 821 if val not in (0,1,False,True):
824 822 raise ValueError,'new call_pdb value must be boolean'
825 823
826 824 # store value in instance
827 825 self._call_pdb = val
828 826
829 827 # notify the actual exception handlers
830 828 self.InteractiveTB.call_pdb = val
831 829
832 830 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
833 831 'Control auto-activation of pdb at exceptions')
834 832
835 833 def debugger(self,force=False):
836 834 """Call the pydb/pdb debugger.
837 835
838 836 Keywords:
839 837
840 838 - force(False): by default, this routine checks the instance call_pdb
841 839 flag and does not actually invoke the debugger if the flag is false.
842 840 The 'force' option forces the debugger to activate even if the flag
843 841 is false.
844 842 """
845 843
846 844 if not (force or self.call_pdb):
847 845 return
848 846
849 847 if not hasattr(sys,'last_traceback'):
850 848 error('No traceback has been produced, nothing to debug.')
851 849 return
852 850
853 851 # use pydb if available
854 852 if debugger.has_pydb:
855 853 from pydb import pm
856 854 else:
857 855 # fallback to our internal debugger
858 856 pm = lambda : self.InteractiveTB.debugger(force=True)
859 857
860 858 with self.readline_no_record:
861 859 pm()
862 860
863 861 #-------------------------------------------------------------------------
864 862 # Things related to IPython's various namespaces
865 863 #-------------------------------------------------------------------------
866 864
867 865 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
868 866 # Create the namespace where the user will operate. user_ns is
869 867 # normally the only one used, and it is passed to the exec calls as
870 868 # the locals argument. But we do carry a user_global_ns namespace
871 869 # given as the exec 'globals' argument, This is useful in embedding
872 870 # situations where the ipython shell opens in a context where the
873 871 # distinction between locals and globals is meaningful. For
874 872 # non-embedded contexts, it is just the same object as the user_ns dict.
875 873
876 874 # FIXME. For some strange reason, __builtins__ is showing up at user
877 875 # level as a dict instead of a module. This is a manual fix, but I
878 876 # should really track down where the problem is coming from. Alex
879 877 # Schmolck reported this problem first.
880 878
881 879 # A useful post by Alex Martelli on this topic:
882 880 # Re: inconsistent value from __builtins__
883 881 # Von: Alex Martelli <aleaxit@yahoo.com>
884 882 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
885 883 # Gruppen: comp.lang.python
886 884
887 885 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
888 886 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
889 887 # > <type 'dict'>
890 888 # > >>> print type(__builtins__)
891 889 # > <type 'module'>
892 890 # > Is this difference in return value intentional?
893 891
894 892 # Well, it's documented that '__builtins__' can be either a dictionary
895 893 # or a module, and it's been that way for a long time. Whether it's
896 894 # intentional (or sensible), I don't know. In any case, the idea is
897 895 # that if you need to access the built-in namespace directly, you
898 896 # should start with "import __builtin__" (note, no 's') which will
899 897 # definitely give you a module. Yeah, it's somewhat confusing:-(.
900 898
901 899 # These routines return properly built dicts as needed by the rest of
902 900 # the code, and can also be used by extension writers to generate
903 901 # properly initialized namespaces.
904 902 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
905 903 user_global_ns)
906 904
907 905 # Assign namespaces
908 906 # This is the namespace where all normal user variables live
909 907 self.user_ns = user_ns
910 908 self.user_global_ns = user_global_ns
911 909
912 910 # An auxiliary namespace that checks what parts of the user_ns were
913 911 # loaded at startup, so we can list later only variables defined in
914 912 # actual interactive use. Since it is always a subset of user_ns, it
915 913 # doesn't need to be separately tracked in the ns_table.
916 914 self.user_ns_hidden = {}
917 915
918 916 # A namespace to keep track of internal data structures to prevent
919 917 # them from cluttering user-visible stuff. Will be updated later
920 918 self.internal_ns = {}
921 919
922 920 # Now that FakeModule produces a real module, we've run into a nasty
923 921 # problem: after script execution (via %run), the module where the user
924 922 # code ran is deleted. Now that this object is a true module (needed
925 923 # so docetst and other tools work correctly), the Python module
926 924 # teardown mechanism runs over it, and sets to None every variable
927 925 # present in that module. Top-level references to objects from the
928 926 # script survive, because the user_ns is updated with them. However,
929 927 # calling functions defined in the script that use other things from
930 928 # the script will fail, because the function's closure had references
931 929 # to the original objects, which are now all None. So we must protect
932 930 # these modules from deletion by keeping a cache.
933 931 #
934 932 # To avoid keeping stale modules around (we only need the one from the
935 933 # last run), we use a dict keyed with the full path to the script, so
936 934 # only the last version of the module is held in the cache. Note,
937 935 # however, that we must cache the module *namespace contents* (their
938 936 # __dict__). Because if we try to cache the actual modules, old ones
939 937 # (uncached) could be destroyed while still holding references (such as
940 938 # those held by GUI objects that tend to be long-lived)>
941 939 #
942 940 # The %reset command will flush this cache. See the cache_main_mod()
943 941 # and clear_main_mod_cache() methods for details on use.
944 942
945 943 # This is the cache used for 'main' namespaces
946 944 self._main_ns_cache = {}
947 945 # And this is the single instance of FakeModule whose __dict__ we keep
948 946 # copying and clearing for reuse on each %run
949 947 self._user_main_module = FakeModule()
950 948
951 949 # A table holding all the namespaces IPython deals with, so that
952 950 # introspection facilities can search easily.
953 951 self.ns_table = {'user':user_ns,
954 952 'user_global':user_global_ns,
955 953 'internal':self.internal_ns,
956 954 'builtin':builtin_mod.__dict__
957 955 }
958 956
959 957 # Similarly, track all namespaces where references can be held and that
960 958 # we can safely clear (so it can NOT include builtin). This one can be
961 959 # a simple list. Note that the main execution namespaces, user_ns and
962 960 # user_global_ns, can NOT be listed here, as clearing them blindly
963 961 # causes errors in object __del__ methods. Instead, the reset() method
964 962 # clears them manually and carefully.
965 963 self.ns_refs_table = [ self.user_ns_hidden,
966 964 self.internal_ns, self._main_ns_cache ]
967 965
968 966 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
969 967 """Return a valid local and global user interactive namespaces.
970 968
971 969 This builds a dict with the minimal information needed to operate as a
972 970 valid IPython user namespace, which you can pass to the various
973 971 embedding classes in ipython. The default implementation returns the
974 972 same dict for both the locals and the globals to allow functions to
975 973 refer to variables in the namespace. Customized implementations can
976 974 return different dicts. The locals dictionary can actually be anything
977 975 following the basic mapping protocol of a dict, but the globals dict
978 976 must be a true dict, not even a subclass. It is recommended that any
979 977 custom object for the locals namespace synchronize with the globals
980 978 dict somehow.
981 979
982 980 Raises TypeError if the provided globals namespace is not a true dict.
983 981
984 982 Parameters
985 983 ----------
986 984 user_ns : dict-like, optional
987 985 The current user namespace. The items in this namespace should
988 986 be included in the output. If None, an appropriate blank
989 987 namespace should be created.
990 988 user_global_ns : dict, optional
991 989 The current user global namespace. The items in this namespace
992 990 should be included in the output. If None, an appropriate
993 991 blank namespace should be created.
994 992
995 993 Returns
996 994 -------
997 995 A pair of dictionary-like object to be used as the local namespace
998 996 of the interpreter and a dict to be used as the global namespace.
999 997 """
1000 998
1001 999
1002 1000 # We must ensure that __builtin__ (without the final 's') is always
1003 1001 # available and pointing to the __builtin__ *module*. For more details:
1004 1002 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1005 1003
1006 1004 if user_ns is None:
1007 1005 # Set __name__ to __main__ to better match the behavior of the
1008 1006 # normal interpreter.
1009 1007 user_ns = {'__name__' :'__main__',
1010 1008 py3compat.builtin_mod_name: builtin_mod,
1011 1009 '__builtins__' : builtin_mod,
1012 1010 }
1013 1011 else:
1014 1012 user_ns.setdefault('__name__','__main__')
1015 1013 user_ns.setdefault(py3compat.builtin_mod_name,builtin_mod)
1016 1014 user_ns.setdefault('__builtins__',builtin_mod)
1017 1015
1018 1016 if user_global_ns is None:
1019 1017 user_global_ns = user_ns
1020 1018 if type(user_global_ns) is not dict:
1021 1019 raise TypeError("user_global_ns must be a true dict; got %r"
1022 1020 % type(user_global_ns))
1023 1021
1024 1022 return user_ns, user_global_ns
1025 1023
1026 1024 def init_sys_modules(self):
1027 1025 # We need to insert into sys.modules something that looks like a
1028 1026 # module but which accesses the IPython namespace, for shelve and
1029 1027 # pickle to work interactively. Normally they rely on getting
1030 1028 # everything out of __main__, but for embedding purposes each IPython
1031 1029 # instance has its own private namespace, so we can't go shoving
1032 1030 # everything into __main__.
1033 1031
1034 1032 # note, however, that we should only do this for non-embedded
1035 1033 # ipythons, which really mimic the __main__.__dict__ with their own
1036 1034 # namespace. Embedded instances, on the other hand, should not do
1037 1035 # this because they need to manage the user local/global namespaces
1038 1036 # only, but they live within a 'normal' __main__ (meaning, they
1039 1037 # shouldn't overtake the execution environment of the script they're
1040 1038 # embedded in).
1041 1039
1042 1040 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1043 1041
1044 1042 try:
1045 1043 main_name = self.user_ns['__name__']
1046 1044 except KeyError:
1047 1045 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1048 1046 else:
1049 1047 sys.modules[main_name] = FakeModule(self.user_ns)
1050 1048
1051 1049 def init_user_ns(self):
1052 1050 """Initialize all user-visible namespaces to their minimum defaults.
1053 1051
1054 1052 Certain history lists are also initialized here, as they effectively
1055 1053 act as user namespaces.
1056 1054
1057 1055 Notes
1058 1056 -----
1059 1057 All data structures here are only filled in, they are NOT reset by this
1060 1058 method. If they were not empty before, data will simply be added to
1061 1059 therm.
1062 1060 """
1063 1061 # This function works in two parts: first we put a few things in
1064 1062 # user_ns, and we sync that contents into user_ns_hidden so that these
1065 1063 # initial variables aren't shown by %who. After the sync, we add the
1066 1064 # rest of what we *do* want the user to see with %who even on a new
1067 1065 # session (probably nothing, so theye really only see their own stuff)
1068 1066
1069 1067 # The user dict must *always* have a __builtin__ reference to the
1070 1068 # Python standard __builtin__ namespace, which must be imported.
1071 1069 # This is so that certain operations in prompt evaluation can be
1072 1070 # reliably executed with builtins. Note that we can NOT use
1073 1071 # __builtins__ (note the 's'), because that can either be a dict or a
1074 1072 # module, and can even mutate at runtime, depending on the context
1075 1073 # (Python makes no guarantees on it). In contrast, __builtin__ is
1076 1074 # always a module object, though it must be explicitly imported.
1077 1075
1078 1076 # For more details:
1079 1077 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1080 1078 ns = dict(__builtin__ = builtin_mod)
1081 1079
1082 1080 # Put 'help' in the user namespace
1083 1081 try:
1084 1082 from site import _Helper
1085 1083 ns['help'] = _Helper()
1086 1084 except ImportError:
1087 1085 warn('help() not available - check site.py')
1088 1086
1089 1087 # make global variables for user access to the histories
1090 1088 ns['_ih'] = self.history_manager.input_hist_parsed
1091 1089 ns['_oh'] = self.history_manager.output_hist
1092 1090 ns['_dh'] = self.history_manager.dir_hist
1093 1091
1094 1092 ns['_sh'] = shadowns
1095 1093
1096 1094 # user aliases to input and output histories. These shouldn't show up
1097 1095 # in %who, as they can have very large reprs.
1098 1096 ns['In'] = self.history_manager.input_hist_parsed
1099 1097 ns['Out'] = self.history_manager.output_hist
1100 1098
1101 1099 # Store myself as the public api!!!
1102 1100 ns['get_ipython'] = self.get_ipython
1103 1101
1104 1102 ns['exit'] = self.exiter
1105 1103 ns['quit'] = self.exiter
1106 1104
1107 1105 # Sync what we've added so far to user_ns_hidden so these aren't seen
1108 1106 # by %who
1109 1107 self.user_ns_hidden.update(ns)
1110 1108
1111 1109 # Anything put into ns now would show up in %who. Think twice before
1112 1110 # putting anything here, as we really want %who to show the user their
1113 1111 # stuff, not our variables.
1114 1112
1115 1113 # Finally, update the real user's namespace
1116 1114 self.user_ns.update(ns)
1117 1115
1118 1116 def reset(self, new_session=True):
1119 1117 """Clear all internal namespaces, and attempt to release references to
1120 1118 user objects.
1121 1119
1122 1120 If new_session is True, a new history session will be opened.
1123 1121 """
1124 1122 # Clear histories
1125 1123 self.history_manager.reset(new_session)
1126 1124 # Reset counter used to index all histories
1127 1125 if new_session:
1128 1126 self.execution_count = 1
1129 1127
1130 1128 # Flush cached output items
1131 1129 if self.displayhook.do_full_cache:
1132 1130 self.displayhook.flush()
1133 1131
1134 1132 # Restore the user namespaces to minimal usability
1135 1133 for ns in self.ns_refs_table:
1136 1134 ns.clear()
1137 1135
1138 1136 # The main execution namespaces must be cleared very carefully,
1139 1137 # skipping the deletion of the builtin-related keys, because doing so
1140 1138 # would cause errors in many object's __del__ methods.
1141 1139 for ns in [self.user_ns, self.user_global_ns]:
1142 1140 drop_keys = set(ns.keys())
1143 1141 drop_keys.discard('__builtin__')
1144 1142 drop_keys.discard('__builtins__')
1145 1143 for k in drop_keys:
1146 1144 del ns[k]
1147 1145
1148 1146 # Restore the user namespaces to minimal usability
1149 1147 self.init_user_ns()
1150 1148
1151 1149 # Restore the default and user aliases
1152 1150 self.alias_manager.clear_aliases()
1153 1151 self.alias_manager.init_aliases()
1154 1152
1155 1153 # Flush the private list of module references kept for script
1156 1154 # execution protection
1157 1155 self.clear_main_mod_cache()
1158 1156
1159 1157 # Clear out the namespace from the last %run
1160 1158 self.new_main_mod()
1161 1159
1162 1160 def del_var(self, varname, by_name=False):
1163 1161 """Delete a variable from the various namespaces, so that, as
1164 1162 far as possible, we're not keeping any hidden references to it.
1165 1163
1166 1164 Parameters
1167 1165 ----------
1168 1166 varname : str
1169 1167 The name of the variable to delete.
1170 1168 by_name : bool
1171 1169 If True, delete variables with the given name in each
1172 1170 namespace. If False (default), find the variable in the user
1173 1171 namespace, and delete references to it.
1174 1172 """
1175 1173 if varname in ('__builtin__', '__builtins__'):
1176 1174 raise ValueError("Refusing to delete %s" % varname)
1177 1175 ns_refs = self.ns_refs_table + [self.user_ns,
1178 1176 self.user_global_ns, self._user_main_module.__dict__] +\
1179 1177 self._main_ns_cache.values()
1180 1178
1181 1179 if by_name: # Delete by name
1182 1180 for ns in ns_refs:
1183 1181 try:
1184 1182 del ns[varname]
1185 1183 except KeyError:
1186 1184 pass
1187 1185 else: # Delete by object
1188 1186 try:
1189 1187 obj = self.user_ns[varname]
1190 1188 except KeyError:
1191 1189 raise NameError("name '%s' is not defined" % varname)
1192 1190 # Also check in output history
1193 1191 ns_refs.append(self.history_manager.output_hist)
1194 1192 for ns in ns_refs:
1195 1193 to_delete = [n for n, o in ns.iteritems() if o is obj]
1196 1194 for name in to_delete:
1197 1195 del ns[name]
1198 1196
1199 1197 # displayhook keeps extra references, but not in a dictionary
1200 1198 for name in ('_', '__', '___'):
1201 1199 if getattr(self.displayhook, name) is obj:
1202 1200 setattr(self.displayhook, name, None)
1203 1201
1204 1202 def reset_selective(self, regex=None):
1205 1203 """Clear selective variables from internal namespaces based on a
1206 1204 specified regular expression.
1207 1205
1208 1206 Parameters
1209 1207 ----------
1210 1208 regex : string or compiled pattern, optional
1211 1209 A regular expression pattern that will be used in searching
1212 1210 variable names in the users namespaces.
1213 1211 """
1214 1212 if regex is not None:
1215 1213 try:
1216 1214 m = re.compile(regex)
1217 1215 except TypeError:
1218 1216 raise TypeError('regex must be a string or compiled pattern')
1219 1217 # Search for keys in each namespace that match the given regex
1220 1218 # If a match is found, delete the key/value pair.
1221 1219 for ns in self.ns_refs_table:
1222 1220 for var in ns:
1223 1221 if m.search(var):
1224 1222 del ns[var]
1225 1223
1226 1224 def push(self, variables, interactive=True):
1227 1225 """Inject a group of variables into the IPython user namespace.
1228 1226
1229 1227 Parameters
1230 1228 ----------
1231 1229 variables : dict, str or list/tuple of str
1232 1230 The variables to inject into the user's namespace. If a dict, a
1233 1231 simple update is done. If a str, the string is assumed to have
1234 1232 variable names separated by spaces. A list/tuple of str can also
1235 1233 be used to give the variable names. If just the variable names are
1236 1234 give (list/tuple/str) then the variable values looked up in the
1237 1235 callers frame.
1238 1236 interactive : bool
1239 1237 If True (default), the variables will be listed with the ``who``
1240 1238 magic.
1241 1239 """
1242 1240 vdict = None
1243 1241
1244 1242 # We need a dict of name/value pairs to do namespace updates.
1245 1243 if isinstance(variables, dict):
1246 1244 vdict = variables
1247 1245 elif isinstance(variables, (basestring, list, tuple)):
1248 1246 if isinstance(variables, basestring):
1249 1247 vlist = variables.split()
1250 1248 else:
1251 1249 vlist = variables
1252 1250 vdict = {}
1253 1251 cf = sys._getframe(1)
1254 1252 for name in vlist:
1255 1253 try:
1256 1254 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1257 1255 except:
1258 1256 print ('Could not get variable %s from %s' %
1259 1257 (name,cf.f_code.co_name))
1260 1258 else:
1261 1259 raise ValueError('variables must be a dict/str/list/tuple')
1262 1260
1263 1261 # Propagate variables to user namespace
1264 1262 self.user_ns.update(vdict)
1265 1263
1266 1264 # And configure interactive visibility
1267 1265 config_ns = self.user_ns_hidden
1268 1266 if interactive:
1269 1267 for name, val in vdict.iteritems():
1270 1268 config_ns.pop(name, None)
1271 1269 else:
1272 1270 for name,val in vdict.iteritems():
1273 1271 config_ns[name] = val
1274 1272
1275 1273 def drop_by_id(self, variables):
1276 1274 """Remove a dict of variables from the user namespace, if they are the
1277 1275 same as the values in the dictionary.
1278 1276
1279 1277 This is intended for use by extensions: variables that they've added can
1280 1278 be taken back out if they are unloaded, without removing any that the
1281 1279 user has overwritten.
1282 1280
1283 1281 Parameters
1284 1282 ----------
1285 1283 variables : dict
1286 1284 A dictionary mapping object names (as strings) to the objects.
1287 1285 """
1288 1286 for name, obj in variables.iteritems():
1289 1287 if name in self.user_ns and self.user_ns[name] is obj:
1290 1288 del self.user_ns[name]
1291 1289 self.user_ns_hidden.pop(name, None)
1292 1290
1293 1291 #-------------------------------------------------------------------------
1294 1292 # Things related to object introspection
1295 1293 #-------------------------------------------------------------------------
1296 1294
1297 1295 def _ofind(self, oname, namespaces=None):
1298 1296 """Find an object in the available namespaces.
1299 1297
1300 1298 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1301 1299
1302 1300 Has special code to detect magic functions.
1303 1301 """
1304 1302 oname = oname.strip()
1305 1303 #print '1- oname: <%r>' % oname # dbg
1306 1304 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1307 1305 return dict(found=False)
1308 1306
1309 1307 alias_ns = None
1310 1308 if namespaces is None:
1311 1309 # Namespaces to search in:
1312 1310 # Put them in a list. The order is important so that we
1313 1311 # find things in the same order that Python finds them.
1314 1312 namespaces = [ ('Interactive', self.user_ns),
1315 1313 ('IPython internal', self.internal_ns),
1316 1314 ('Python builtin', builtin_mod.__dict__),
1317 1315 ('Alias', self.alias_manager.alias_table),
1318 1316 ]
1319 1317 alias_ns = self.alias_manager.alias_table
1320 1318
1321 1319 # initialize results to 'null'
1322 1320 found = False; obj = None; ospace = None; ds = None;
1323 1321 ismagic = False; isalias = False; parent = None
1324 1322
1325 1323 # We need to special-case 'print', which as of python2.6 registers as a
1326 1324 # function but should only be treated as one if print_function was
1327 1325 # loaded with a future import. In this case, just bail.
1328 1326 if (oname == 'print' and not py3compat.PY3 and not \
1329 1327 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1330 1328 return {'found':found, 'obj':obj, 'namespace':ospace,
1331 1329 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1332 1330
1333 1331 # Look for the given name by splitting it in parts. If the head is
1334 1332 # found, then we look for all the remaining parts as members, and only
1335 1333 # declare success if we can find them all.
1336 1334 oname_parts = oname.split('.')
1337 1335 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1338 1336 for nsname,ns in namespaces:
1339 1337 try:
1340 1338 obj = ns[oname_head]
1341 1339 except KeyError:
1342 1340 continue
1343 1341 else:
1344 1342 #print 'oname_rest:', oname_rest # dbg
1345 1343 for part in oname_rest:
1346 1344 try:
1347 1345 parent = obj
1348 1346 obj = getattr(obj,part)
1349 1347 except:
1350 1348 # Blanket except b/c some badly implemented objects
1351 1349 # allow __getattr__ to raise exceptions other than
1352 1350 # AttributeError, which then crashes IPython.
1353 1351 break
1354 1352 else:
1355 1353 # If we finish the for loop (no break), we got all members
1356 1354 found = True
1357 1355 ospace = nsname
1358 1356 if ns == alias_ns:
1359 1357 isalias = True
1360 1358 break # namespace loop
1361 1359
1362 1360 # Try to see if it's magic
1363 1361 if not found:
1364 1362 if oname.startswith(ESC_MAGIC):
1365 1363 oname = oname[1:]
1366 1364 obj = getattr(self,'magic_'+oname,None)
1367 1365 if obj is not None:
1368 1366 found = True
1369 1367 ospace = 'IPython internal'
1370 1368 ismagic = True
1371 1369
1372 1370 # Last try: special-case some literals like '', [], {}, etc:
1373 1371 if not found and oname_head in ["''",'""','[]','{}','()']:
1374 1372 obj = eval(oname_head)
1375 1373 found = True
1376 1374 ospace = 'Interactive'
1377 1375
1378 1376 return {'found':found, 'obj':obj, 'namespace':ospace,
1379 1377 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1380 1378
1381 1379 def _ofind_property(self, oname, info):
1382 1380 """Second part of object finding, to look for property details."""
1383 1381 if info.found:
1384 1382 # Get the docstring of the class property if it exists.
1385 1383 path = oname.split('.')
1386 1384 root = '.'.join(path[:-1])
1387 1385 if info.parent is not None:
1388 1386 try:
1389 1387 target = getattr(info.parent, '__class__')
1390 1388 # The object belongs to a class instance.
1391 1389 try:
1392 1390 target = getattr(target, path[-1])
1393 1391 # The class defines the object.
1394 1392 if isinstance(target, property):
1395 1393 oname = root + '.__class__.' + path[-1]
1396 1394 info = Struct(self._ofind(oname))
1397 1395 except AttributeError: pass
1398 1396 except AttributeError: pass
1399 1397
1400 1398 # We return either the new info or the unmodified input if the object
1401 1399 # hadn't been found
1402 1400 return info
1403 1401
1404 1402 def _object_find(self, oname, namespaces=None):
1405 1403 """Find an object and return a struct with info about it."""
1406 1404 inf = Struct(self._ofind(oname, namespaces))
1407 1405 return Struct(self._ofind_property(oname, inf))
1408 1406
1409 1407 def _inspect(self, meth, oname, namespaces=None, **kw):
1410 1408 """Generic interface to the inspector system.
1411 1409
1412 1410 This function is meant to be called by pdef, pdoc & friends."""
1413 1411 info = self._object_find(oname)
1414 1412 if info.found:
1415 1413 pmethod = getattr(self.inspector, meth)
1416 1414 formatter = format_screen if info.ismagic else None
1417 1415 if meth == 'pdoc':
1418 1416 pmethod(info.obj, oname, formatter)
1419 1417 elif meth == 'pinfo':
1420 1418 pmethod(info.obj, oname, formatter, info, **kw)
1421 1419 else:
1422 1420 pmethod(info.obj, oname)
1423 1421 else:
1424 1422 print 'Object `%s` not found.' % oname
1425 1423 return 'not found' # so callers can take other action
1426 1424
1427 1425 def object_inspect(self, oname):
1428 1426 with self.builtin_trap:
1429 1427 info = self._object_find(oname)
1430 1428 if info.found:
1431 1429 return self.inspector.info(info.obj, oname, info=info)
1432 1430 else:
1433 1431 return oinspect.object_info(name=oname, found=False)
1434 1432
1435 1433 #-------------------------------------------------------------------------
1436 1434 # Things related to history management
1437 1435 #-------------------------------------------------------------------------
1438 1436
1439 1437 def init_history(self):
1440 1438 """Sets up the command history, and starts regular autosaves."""
1441 1439 self.history_manager = HistoryManager(shell=self, config=self.config)
1442 1440 self.configurables.append(self.history_manager)
1443 1441
1444 1442 #-------------------------------------------------------------------------
1445 1443 # Things related to exception handling and tracebacks (not debugging)
1446 1444 #-------------------------------------------------------------------------
1447 1445
1448 1446 def init_traceback_handlers(self, custom_exceptions):
1449 1447 # Syntax error handler.
1450 1448 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1451 1449
1452 1450 # The interactive one is initialized with an offset, meaning we always
1453 1451 # want to remove the topmost item in the traceback, which is our own
1454 1452 # internal code. Valid modes: ['Plain','Context','Verbose']
1455 1453 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1456 1454 color_scheme='NoColor',
1457 1455 tb_offset = 1,
1458 1456 check_cache=self.compile.check_cache)
1459 1457
1460 1458 # The instance will store a pointer to the system-wide exception hook,
1461 1459 # so that runtime code (such as magics) can access it. This is because
1462 1460 # during the read-eval loop, it may get temporarily overwritten.
1463 1461 self.sys_excepthook = sys.excepthook
1464 1462
1465 1463 # and add any custom exception handlers the user may have specified
1466 1464 self.set_custom_exc(*custom_exceptions)
1467 1465
1468 1466 # Set the exception mode
1469 1467 self.InteractiveTB.set_mode(mode=self.xmode)
1470 1468
1471 1469 def set_custom_exc(self, exc_tuple, handler):
1472 1470 """set_custom_exc(exc_tuple,handler)
1473 1471
1474 1472 Set a custom exception handler, which will be called if any of the
1475 1473 exceptions in exc_tuple occur in the mainloop (specifically, in the
1476 1474 run_code() method).
1477 1475
1478 1476 Parameters
1479 1477 ----------
1480 1478
1481 1479 exc_tuple : tuple of exception classes
1482 1480 A *tuple* of exception classes, for which to call the defined
1483 1481 handler. It is very important that you use a tuple, and NOT A
1484 1482 LIST here, because of the way Python's except statement works. If
1485 1483 you only want to trap a single exception, use a singleton tuple::
1486 1484
1487 1485 exc_tuple == (MyCustomException,)
1488 1486
1489 1487 handler : callable
1490 1488 handler must have the following signature::
1491 1489
1492 1490 def my_handler(self, etype, value, tb, tb_offset=None):
1493 1491 ...
1494 1492 return structured_traceback
1495 1493
1496 1494 Your handler must return a structured traceback (a list of strings),
1497 1495 or None.
1498 1496
1499 1497 This will be made into an instance method (via types.MethodType)
1500 1498 of IPython itself, and it will be called if any of the exceptions
1501 1499 listed in the exc_tuple are caught. If the handler is None, an
1502 1500 internal basic one is used, which just prints basic info.
1503 1501
1504 1502 To protect IPython from crashes, if your handler ever raises an
1505 1503 exception or returns an invalid result, it will be immediately
1506 1504 disabled.
1507 1505
1508 1506 WARNING: by putting in your own exception handler into IPython's main
1509 1507 execution loop, you run a very good chance of nasty crashes. This
1510 1508 facility should only be used if you really know what you are doing."""
1511 1509
1512 1510 assert type(exc_tuple)==type(()) , \
1513 1511 "The custom exceptions must be given AS A TUPLE."
1514 1512
1515 1513 def dummy_handler(self,etype,value,tb,tb_offset=None):
1516 1514 print '*** Simple custom exception handler ***'
1517 1515 print 'Exception type :',etype
1518 1516 print 'Exception value:',value
1519 1517 print 'Traceback :',tb
1520 1518 #print 'Source code :','\n'.join(self.buffer)
1521 1519
1522 1520 def validate_stb(stb):
1523 1521 """validate structured traceback return type
1524 1522
1525 1523 return type of CustomTB *should* be a list of strings, but allow
1526 1524 single strings or None, which are harmless.
1527 1525
1528 1526 This function will *always* return a list of strings,
1529 1527 and will raise a TypeError if stb is inappropriate.
1530 1528 """
1531 1529 msg = "CustomTB must return list of strings, not %r" % stb
1532 1530 if stb is None:
1533 1531 return []
1534 1532 elif isinstance(stb, basestring):
1535 1533 return [stb]
1536 1534 elif not isinstance(stb, list):
1537 1535 raise TypeError(msg)
1538 1536 # it's a list
1539 1537 for line in stb:
1540 1538 # check every element
1541 1539 if not isinstance(line, basestring):
1542 1540 raise TypeError(msg)
1543 1541 return stb
1544 1542
1545 1543 if handler is None:
1546 1544 wrapped = dummy_handler
1547 1545 else:
1548 1546 def wrapped(self,etype,value,tb,tb_offset=None):
1549 1547 """wrap CustomTB handler, to protect IPython from user code
1550 1548
1551 1549 This makes it harder (but not impossible) for custom exception
1552 1550 handlers to crash IPython.
1553 1551 """
1554 1552 try:
1555 1553 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1556 1554 return validate_stb(stb)
1557 1555 except:
1558 1556 # clear custom handler immediately
1559 1557 self.set_custom_exc((), None)
1560 1558 print >> io.stderr, "Custom TB Handler failed, unregistering"
1561 1559 # show the exception in handler first
1562 1560 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1563 1561 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1564 1562 print >> io.stdout, "The original exception:"
1565 1563 stb = self.InteractiveTB.structured_traceback(
1566 1564 (etype,value,tb), tb_offset=tb_offset
1567 1565 )
1568 1566 return stb
1569 1567
1570 1568 self.CustomTB = types.MethodType(wrapped,self)
1571 1569 self.custom_exceptions = exc_tuple
1572 1570
1573 1571 def excepthook(self, etype, value, tb):
1574 1572 """One more defense for GUI apps that call sys.excepthook.
1575 1573
1576 1574 GUI frameworks like wxPython trap exceptions and call
1577 1575 sys.excepthook themselves. I guess this is a feature that
1578 1576 enables them to keep running after exceptions that would
1579 1577 otherwise kill their mainloop. This is a bother for IPython
1580 1578 which excepts to catch all of the program exceptions with a try:
1581 1579 except: statement.
1582 1580
1583 1581 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1584 1582 any app directly invokes sys.excepthook, it will look to the user like
1585 1583 IPython crashed. In order to work around this, we can disable the
1586 1584 CrashHandler and replace it with this excepthook instead, which prints a
1587 1585 regular traceback using our InteractiveTB. In this fashion, apps which
1588 1586 call sys.excepthook will generate a regular-looking exception from
1589 1587 IPython, and the CrashHandler will only be triggered by real IPython
1590 1588 crashes.
1591 1589
1592 1590 This hook should be used sparingly, only in places which are not likely
1593 1591 to be true IPython errors.
1594 1592 """
1595 1593 self.showtraceback((etype,value,tb),tb_offset=0)
1596 1594
1597 1595 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1598 1596 exception_only=False):
1599 1597 """Display the exception that just occurred.
1600 1598
1601 1599 If nothing is known about the exception, this is the method which
1602 1600 should be used throughout the code for presenting user tracebacks,
1603 1601 rather than directly invoking the InteractiveTB object.
1604 1602
1605 1603 A specific showsyntaxerror() also exists, but this method can take
1606 1604 care of calling it if needed, so unless you are explicitly catching a
1607 1605 SyntaxError exception, don't try to analyze the stack manually and
1608 1606 simply call this method."""
1609 1607
1610 1608 try:
1611 1609 if exc_tuple is None:
1612 1610 etype, value, tb = sys.exc_info()
1613 1611 else:
1614 1612 etype, value, tb = exc_tuple
1615 1613
1616 1614 if etype is None:
1617 1615 if hasattr(sys, 'last_type'):
1618 1616 etype, value, tb = sys.last_type, sys.last_value, \
1619 1617 sys.last_traceback
1620 1618 else:
1621 1619 self.write_err('No traceback available to show.\n')
1622 1620 return
1623 1621
1624 1622 if etype is SyntaxError:
1625 1623 # Though this won't be called by syntax errors in the input
1626 1624 # line, there may be SyntaxError cases with imported code.
1627 1625 self.showsyntaxerror(filename)
1628 1626 elif etype is UsageError:
1629 1627 self.write_err("UsageError: %s" % value)
1630 1628 else:
1631 1629 # WARNING: these variables are somewhat deprecated and not
1632 1630 # necessarily safe to use in a threaded environment, but tools
1633 1631 # like pdb depend on their existence, so let's set them. If we
1634 1632 # find problems in the field, we'll need to revisit their use.
1635 1633 sys.last_type = etype
1636 1634 sys.last_value = value
1637 1635 sys.last_traceback = tb
1638 1636 if etype in self.custom_exceptions:
1639 1637 stb = self.CustomTB(etype, value, tb, tb_offset)
1640 1638 else:
1641 1639 if exception_only:
1642 1640 stb = ['An exception has occurred, use %tb to see '
1643 1641 'the full traceback.\n']
1644 1642 stb.extend(self.InteractiveTB.get_exception_only(etype,
1645 1643 value))
1646 1644 else:
1647 1645 stb = self.InteractiveTB.structured_traceback(etype,
1648 1646 value, tb, tb_offset=tb_offset)
1649 1647
1650 1648 self._showtraceback(etype, value, stb)
1651 1649 if self.call_pdb:
1652 1650 # drop into debugger
1653 1651 self.debugger(force=True)
1654 1652 return
1655 1653
1656 1654 # Actually show the traceback
1657 1655 self._showtraceback(etype, value, stb)
1658 1656
1659 1657 except KeyboardInterrupt:
1660 1658 self.write_err("\nKeyboardInterrupt\n")
1661 1659
1662 1660 def _showtraceback(self, etype, evalue, stb):
1663 1661 """Actually show a traceback.
1664 1662
1665 1663 Subclasses may override this method to put the traceback on a different
1666 1664 place, like a side channel.
1667 1665 """
1668 1666 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1669 1667
1670 1668 def showsyntaxerror(self, filename=None):
1671 1669 """Display the syntax error that just occurred.
1672 1670
1673 1671 This doesn't display a stack trace because there isn't one.
1674 1672
1675 1673 If a filename is given, it is stuffed in the exception instead
1676 1674 of what was there before (because Python's parser always uses
1677 1675 "<string>" when reading from a string).
1678 1676 """
1679 1677 etype, value, last_traceback = sys.exc_info()
1680 1678
1681 1679 # See note about these variables in showtraceback() above
1682 1680 sys.last_type = etype
1683 1681 sys.last_value = value
1684 1682 sys.last_traceback = last_traceback
1685 1683
1686 1684 if filename and etype is SyntaxError:
1687 1685 # Work hard to stuff the correct filename in the exception
1688 1686 try:
1689 1687 msg, (dummy_filename, lineno, offset, line) = value
1690 1688 except:
1691 1689 # Not the format we expect; leave it alone
1692 1690 pass
1693 1691 else:
1694 1692 # Stuff in the right filename
1695 1693 try:
1696 1694 # Assume SyntaxError is a class exception
1697 1695 value = SyntaxError(msg, (filename, lineno, offset, line))
1698 1696 except:
1699 1697 # If that failed, assume SyntaxError is a string
1700 1698 value = msg, (filename, lineno, offset, line)
1701 1699 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1702 1700 self._showtraceback(etype, value, stb)
1703 1701
1704 1702 # This is overridden in TerminalInteractiveShell to show a message about
1705 1703 # the %paste magic.
1706 1704 def showindentationerror(self):
1707 1705 """Called by run_cell when there's an IndentationError in code entered
1708 1706 at the prompt.
1709 1707
1710 1708 This is overridden in TerminalInteractiveShell to show a message about
1711 1709 the %paste magic."""
1712 1710 self.showsyntaxerror()
1713 1711
1714 1712 #-------------------------------------------------------------------------
1715 1713 # Things related to readline
1716 1714 #-------------------------------------------------------------------------
1717 1715
1718 1716 def init_readline(self):
1719 1717 """Command history completion/saving/reloading."""
1720 1718
1721 1719 if self.readline_use:
1722 1720 import IPython.utils.rlineimpl as readline
1723 1721
1724 1722 self.rl_next_input = None
1725 1723 self.rl_do_indent = False
1726 1724
1727 1725 if not self.readline_use or not readline.have_readline:
1728 1726 self.has_readline = False
1729 1727 self.readline = None
1730 1728 # Set a number of methods that depend on readline to be no-op
1731 1729 self.readline_no_record = no_op_context
1732 1730 self.set_readline_completer = no_op
1733 1731 self.set_custom_completer = no_op
1734 1732 self.set_completer_frame = no_op
1735 1733 if self.readline_use:
1736 1734 warn('Readline services not available or not loaded.')
1737 1735 else:
1738 1736 self.has_readline = True
1739 1737 self.readline = readline
1740 1738 sys.modules['readline'] = readline
1741 1739
1742 1740 # Platform-specific configuration
1743 1741 if os.name == 'nt':
1744 1742 # FIXME - check with Frederick to see if we can harmonize
1745 1743 # naming conventions with pyreadline to avoid this
1746 1744 # platform-dependent check
1747 1745 self.readline_startup_hook = readline.set_pre_input_hook
1748 1746 else:
1749 1747 self.readline_startup_hook = readline.set_startup_hook
1750 1748
1751 1749 # Load user's initrc file (readline config)
1752 1750 # Or if libedit is used, load editrc.
1753 1751 inputrc_name = os.environ.get('INPUTRC')
1754 1752 if inputrc_name is None:
1755 1753 home_dir = get_home_dir()
1756 1754 if home_dir is not None:
1757 1755 inputrc_name = '.inputrc'
1758 1756 if readline.uses_libedit:
1759 1757 inputrc_name = '.editrc'
1760 1758 inputrc_name = os.path.join(home_dir, inputrc_name)
1761 1759 if os.path.isfile(inputrc_name):
1762 1760 try:
1763 1761 readline.read_init_file(inputrc_name)
1764 1762 except:
1765 1763 warn('Problems reading readline initialization file <%s>'
1766 1764 % inputrc_name)
1767 1765
1768 1766 # Configure readline according to user's prefs
1769 1767 # This is only done if GNU readline is being used. If libedit
1770 1768 # is being used (as on Leopard) the readline config is
1771 1769 # not run as the syntax for libedit is different.
1772 1770 if not readline.uses_libedit:
1773 1771 for rlcommand in self.readline_parse_and_bind:
1774 1772 #print "loading rl:",rlcommand # dbg
1775 1773 readline.parse_and_bind(rlcommand)
1776 1774
1777 1775 # Remove some chars from the delimiters list. If we encounter
1778 1776 # unicode chars, discard them.
1779 1777 delims = readline.get_completer_delims()
1780 1778 if not py3compat.PY3:
1781 1779 delims = delims.encode("ascii", "ignore")
1782 1780 for d in self.readline_remove_delims:
1783 1781 delims = delims.replace(d, "")
1784 1782 delims = delims.replace(ESC_MAGIC, '')
1785 1783 readline.set_completer_delims(delims)
1786 1784 # otherwise we end up with a monster history after a while:
1787 1785 readline.set_history_length(self.history_length)
1788 1786
1789 1787 self.refill_readline_hist()
1790 1788 self.readline_no_record = ReadlineNoRecord(self)
1791 1789
1792 1790 # Configure auto-indent for all platforms
1793 1791 self.set_autoindent(self.autoindent)
1794 1792
1795 1793 def refill_readline_hist(self):
1796 1794 # Load the last 1000 lines from history
1797 1795 self.readline.clear_history()
1798 1796 stdin_encoding = sys.stdin.encoding or "utf-8"
1799 1797 for _, _, cell in self.history_manager.get_tail(1000,
1800 1798 include_latest=True):
1801 1799 if cell.strip(): # Ignore blank lines
1802 1800 if self.multiline_history:
1803 1801 self.readline.add_history(py3compat.unicode_to_str(cell.rstrip(),
1804 1802 stdin_encoding))
1805 1803 else:
1806 1804 for line in cell.splitlines():
1807 1805 self.readline.add_history(py3compat.unicode_to_str(line,
1808 1806 stdin_encoding))
1809 1807
1810 1808 def set_next_input(self, s):
1811 1809 """ Sets the 'default' input string for the next command line.
1812 1810
1813 1811 Requires readline.
1814 1812
1815 1813 Example:
1816 1814
1817 1815 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1818 1816 [D:\ipython]|2> Hello Word_ # cursor is here
1819 1817 """
1820 1818 if isinstance(s, unicode):
1821 1819 s = s.encode(self.stdin_encoding, 'replace')
1822 1820 self.rl_next_input = s
1823 1821
1824 1822 # Maybe move this to the terminal subclass?
1825 1823 def pre_readline(self):
1826 1824 """readline hook to be used at the start of each line.
1827 1825
1828 1826 Currently it handles auto-indent only."""
1829 1827
1830 1828 if self.rl_do_indent:
1831 1829 self.readline.insert_text(self._indent_current_str())
1832 1830 if self.rl_next_input is not None:
1833 1831 self.readline.insert_text(self.rl_next_input)
1834 1832 self.rl_next_input = None
1835 1833
1836 1834 def _indent_current_str(self):
1837 1835 """return the current level of indentation as a string"""
1838 1836 return self.input_splitter.indent_spaces * ' '
1839 1837
1840 1838 #-------------------------------------------------------------------------
1841 1839 # Things related to text completion
1842 1840 #-------------------------------------------------------------------------
1843 1841
1844 1842 def init_completer(self):
1845 1843 """Initialize the completion machinery.
1846 1844
1847 1845 This creates completion machinery that can be used by client code,
1848 1846 either interactively in-process (typically triggered by the readline
1849 1847 library), programatically (such as in test suites) or out-of-prcess
1850 1848 (typically over the network by remote frontends).
1851 1849 """
1852 1850 from IPython.core.completer import IPCompleter
1853 1851 from IPython.core.completerlib import (module_completer,
1854 1852 magic_run_completer, cd_completer)
1855 1853
1856 1854 self.Completer = IPCompleter(shell=self,
1857 1855 namespace=self.user_ns,
1858 1856 global_namespace=self.user_global_ns,
1859 omit__names=self.readline_omit__names,
1860 1857 alias_table=self.alias_manager.alias_table,
1861 1858 use_readline=self.has_readline,
1862 1859 config=self.config,
1863 1860 )
1864 1861 self.configurables.append(self.Completer)
1865 1862
1866 1863 # Add custom completers to the basic ones built into IPCompleter
1867 1864 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1868 1865 self.strdispatchers['complete_command'] = sdisp
1869 1866 self.Completer.custom_completers = sdisp
1870 1867
1871 1868 self.set_hook('complete_command', module_completer, str_key = 'import')
1872 1869 self.set_hook('complete_command', module_completer, str_key = 'from')
1873 1870 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1874 1871 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1875 1872
1876 1873 # Only configure readline if we truly are using readline. IPython can
1877 1874 # do tab-completion over the network, in GUIs, etc, where readline
1878 1875 # itself may be absent
1879 1876 if self.has_readline:
1880 1877 self.set_readline_completer()
1881 1878
1882 1879 def complete(self, text, line=None, cursor_pos=None):
1883 1880 """Return the completed text and a list of completions.
1884 1881
1885 1882 Parameters
1886 1883 ----------
1887 1884
1888 1885 text : string
1889 1886 A string of text to be completed on. It can be given as empty and
1890 1887 instead a line/position pair are given. In this case, the
1891 1888 completer itself will split the line like readline does.
1892 1889
1893 1890 line : string, optional
1894 1891 The complete line that text is part of.
1895 1892
1896 1893 cursor_pos : int, optional
1897 1894 The position of the cursor on the input line.
1898 1895
1899 1896 Returns
1900 1897 -------
1901 1898 text : string
1902 1899 The actual text that was completed.
1903 1900
1904 1901 matches : list
1905 1902 A sorted list with all possible completions.
1906 1903
1907 1904 The optional arguments allow the completion to take more context into
1908 1905 account, and are part of the low-level completion API.
1909 1906
1910 1907 This is a wrapper around the completion mechanism, similar to what
1911 1908 readline does at the command line when the TAB key is hit. By
1912 1909 exposing it as a method, it can be used by other non-readline
1913 1910 environments (such as GUIs) for text completion.
1914 1911
1915 1912 Simple usage example:
1916 1913
1917 1914 In [1]: x = 'hello'
1918 1915
1919 1916 In [2]: _ip.complete('x.l')
1920 1917 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1921 1918 """
1922 1919
1923 1920 # Inject names into __builtin__ so we can complete on the added names.
1924 1921 with self.builtin_trap:
1925 1922 return self.Completer.complete(text, line, cursor_pos)
1926 1923
1927 1924 def set_custom_completer(self, completer, pos=0):
1928 1925 """Adds a new custom completer function.
1929 1926
1930 1927 The position argument (defaults to 0) is the index in the completers
1931 1928 list where you want the completer to be inserted."""
1932 1929
1933 1930 newcomp = types.MethodType(completer,self.Completer)
1934 1931 self.Completer.matchers.insert(pos,newcomp)
1935 1932
1936 1933 def set_readline_completer(self):
1937 1934 """Reset readline's completer to be our own."""
1938 1935 self.readline.set_completer(self.Completer.rlcomplete)
1939 1936
1940 1937 def set_completer_frame(self, frame=None):
1941 1938 """Set the frame of the completer."""
1942 1939 if frame:
1943 1940 self.Completer.namespace = frame.f_locals
1944 1941 self.Completer.global_namespace = frame.f_globals
1945 1942 else:
1946 1943 self.Completer.namespace = self.user_ns
1947 1944 self.Completer.global_namespace = self.user_global_ns
1948 1945
1949 1946 #-------------------------------------------------------------------------
1950 1947 # Things related to magics
1951 1948 #-------------------------------------------------------------------------
1952 1949
1953 1950 def init_magics(self):
1954 1951 # FIXME: Move the color initialization to the DisplayHook, which
1955 1952 # should be split into a prompt manager and displayhook. We probably
1956 1953 # even need a centralize colors management object.
1957 1954 self.magic_colors(self.colors)
1958 1955 # History was moved to a separate module
1959 1956 from . import history
1960 1957 history.init_ipython(self)
1961 1958
1962 1959 def magic(self, arg_s, next_input=None):
1963 1960 """Call a magic function by name.
1964 1961
1965 1962 Input: a string containing the name of the magic function to call and
1966 1963 any additional arguments to be passed to the magic.
1967 1964
1968 1965 magic('name -opt foo bar') is equivalent to typing at the ipython
1969 1966 prompt:
1970 1967
1971 1968 In[1]: %name -opt foo bar
1972 1969
1973 1970 To call a magic without arguments, simply use magic('name').
1974 1971
1975 1972 This provides a proper Python function to call IPython's magics in any
1976 1973 valid Python code you can type at the interpreter, including loops and
1977 1974 compound statements.
1978 1975 """
1979 1976 # Allow setting the next input - this is used if the user does `a=abs?`.
1980 1977 # We do this first so that magic functions can override it.
1981 1978 if next_input:
1982 1979 self.set_next_input(next_input)
1983 1980
1984 1981 args = arg_s.split(' ',1)
1985 1982 magic_name = args[0]
1986 1983 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1987 1984
1988 1985 try:
1989 1986 magic_args = args[1]
1990 1987 except IndexError:
1991 1988 magic_args = ''
1992 1989 fn = getattr(self,'magic_'+magic_name,None)
1993 1990 if fn is None:
1994 1991 error("Magic function `%s` not found." % magic_name)
1995 1992 else:
1996 1993 magic_args = self.var_expand(magic_args,1)
1997 1994 # Grab local namespace if we need it:
1998 1995 if getattr(fn, "needs_local_scope", False):
1999 1996 self._magic_locals = sys._getframe(1).f_locals
2000 1997 with self.builtin_trap:
2001 1998 result = fn(magic_args)
2002 1999 # Ensure we're not keeping object references around:
2003 2000 self._magic_locals = {}
2004 2001 return result
2005 2002
2006 2003 def define_magic(self, magicname, func):
2007 2004 """Expose own function as magic function for ipython
2008 2005
2009 2006 def foo_impl(self,parameter_s=''):
2010 2007 'My very own magic!. (Use docstrings, IPython reads them).'
2011 2008 print 'Magic function. Passed parameter is between < >:'
2012 2009 print '<%s>' % parameter_s
2013 2010 print 'The self object is:',self
2014 2011
2015 2012 self.define_magic('foo',foo_impl)
2016 2013 """
2017 2014 im = types.MethodType(func,self)
2018 2015 old = getattr(self, "magic_" + magicname, None)
2019 2016 setattr(self, "magic_" + magicname, im)
2020 2017 return old
2021 2018
2022 2019 #-------------------------------------------------------------------------
2023 2020 # Things related to macros
2024 2021 #-------------------------------------------------------------------------
2025 2022
2026 2023 def define_macro(self, name, themacro):
2027 2024 """Define a new macro
2028 2025
2029 2026 Parameters
2030 2027 ----------
2031 2028 name : str
2032 2029 The name of the macro.
2033 2030 themacro : str or Macro
2034 2031 The action to do upon invoking the macro. If a string, a new
2035 2032 Macro object is created by passing the string to it.
2036 2033 """
2037 2034
2038 2035 from IPython.core import macro
2039 2036
2040 2037 if isinstance(themacro, basestring):
2041 2038 themacro = macro.Macro(themacro)
2042 2039 if not isinstance(themacro, macro.Macro):
2043 2040 raise ValueError('A macro must be a string or a Macro instance.')
2044 2041 self.user_ns[name] = themacro
2045 2042
2046 2043 #-------------------------------------------------------------------------
2047 2044 # Things related to the running of system commands
2048 2045 #-------------------------------------------------------------------------
2049 2046
2050 2047 def system_piped(self, cmd):
2051 2048 """Call the given cmd in a subprocess, piping stdout/err
2052 2049
2053 2050 Parameters
2054 2051 ----------
2055 2052 cmd : str
2056 2053 Command to execute (can not end in '&', as background processes are
2057 2054 not supported. Should not be a command that expects input
2058 2055 other than simple text.
2059 2056 """
2060 2057 if cmd.rstrip().endswith('&'):
2061 2058 # this is *far* from a rigorous test
2062 2059 # We do not support backgrounding processes because we either use
2063 2060 # pexpect or pipes to read from. Users can always just call
2064 2061 # os.system() or use ip.system=ip.system_raw
2065 2062 # if they really want a background process.
2066 2063 raise OSError("Background processes not supported.")
2067 2064
2068 2065 # we explicitly do NOT return the subprocess status code, because
2069 2066 # a non-None value would trigger :func:`sys.displayhook` calls.
2070 2067 # Instead, we store the exit_code in user_ns.
2071 2068 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2072 2069
2073 2070 def system_raw(self, cmd):
2074 2071 """Call the given cmd in a subprocess using os.system
2075 2072
2076 2073 Parameters
2077 2074 ----------
2078 2075 cmd : str
2079 2076 Command to execute.
2080 2077 """
2081 2078 # We explicitly do NOT return the subprocess status code, because
2082 2079 # a non-None value would trigger :func:`sys.displayhook` calls.
2083 2080 # Instead, we store the exit_code in user_ns.
2084 2081 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
2085 2082
2086 2083 # use piped system by default, because it is better behaved
2087 2084 system = system_piped
2088 2085
2089 2086 def getoutput(self, cmd, split=True):
2090 2087 """Get output (possibly including stderr) from a subprocess.
2091 2088
2092 2089 Parameters
2093 2090 ----------
2094 2091 cmd : str
2095 2092 Command to execute (can not end in '&', as background processes are
2096 2093 not supported.
2097 2094 split : bool, optional
2098 2095
2099 2096 If True, split the output into an IPython SList. Otherwise, an
2100 2097 IPython LSString is returned. These are objects similar to normal
2101 2098 lists and strings, with a few convenience attributes for easier
2102 2099 manipulation of line-based output. You can use '?' on them for
2103 2100 details.
2104 2101 """
2105 2102 if cmd.rstrip().endswith('&'):
2106 2103 # this is *far* from a rigorous test
2107 2104 raise OSError("Background processes not supported.")
2108 2105 out = getoutput(self.var_expand(cmd, depth=2))
2109 2106 if split:
2110 2107 out = SList(out.splitlines())
2111 2108 else:
2112 2109 out = LSString(out)
2113 2110 return out
2114 2111
2115 2112 #-------------------------------------------------------------------------
2116 2113 # Things related to aliases
2117 2114 #-------------------------------------------------------------------------
2118 2115
2119 2116 def init_alias(self):
2120 2117 self.alias_manager = AliasManager(shell=self, config=self.config)
2121 2118 self.configurables.append(self.alias_manager)
2122 2119 self.ns_table['alias'] = self.alias_manager.alias_table,
2123 2120
2124 2121 #-------------------------------------------------------------------------
2125 2122 # Things related to extensions and plugins
2126 2123 #-------------------------------------------------------------------------
2127 2124
2128 2125 def init_extension_manager(self):
2129 2126 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2130 2127 self.configurables.append(self.extension_manager)
2131 2128
2132 2129 def init_plugin_manager(self):
2133 2130 self.plugin_manager = PluginManager(config=self.config)
2134 2131 self.configurables.append(self.plugin_manager)
2135 2132
2136 2133
2137 2134 #-------------------------------------------------------------------------
2138 2135 # Things related to payloads
2139 2136 #-------------------------------------------------------------------------
2140 2137
2141 2138 def init_payload(self):
2142 2139 self.payload_manager = PayloadManager(config=self.config)
2143 2140 self.configurables.append(self.payload_manager)
2144 2141
2145 2142 #-------------------------------------------------------------------------
2146 2143 # Things related to the prefilter
2147 2144 #-------------------------------------------------------------------------
2148 2145
2149 2146 def init_prefilter(self):
2150 2147 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2151 2148 self.configurables.append(self.prefilter_manager)
2152 2149 # Ultimately this will be refactored in the new interpreter code, but
2153 2150 # for now, we should expose the main prefilter method (there's legacy
2154 2151 # code out there that may rely on this).
2155 2152 self.prefilter = self.prefilter_manager.prefilter_lines
2156 2153
2157 2154 def auto_rewrite_input(self, cmd):
2158 2155 """Print to the screen the rewritten form of the user's command.
2159 2156
2160 2157 This shows visual feedback by rewriting input lines that cause
2161 2158 automatic calling to kick in, like::
2162 2159
2163 2160 /f x
2164 2161
2165 2162 into::
2166 2163
2167 2164 ------> f(x)
2168 2165
2169 2166 after the user's input prompt. This helps the user understand that the
2170 2167 input line was transformed automatically by IPython.
2171 2168 """
2172 2169 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2173 2170
2174 2171 try:
2175 2172 # plain ascii works better w/ pyreadline, on some machines, so
2176 2173 # we use it and only print uncolored rewrite if we have unicode
2177 2174 rw = str(rw)
2178 2175 print >> io.stdout, rw
2179 2176 except UnicodeEncodeError:
2180 2177 print "------> " + cmd
2181 2178
2182 2179 #-------------------------------------------------------------------------
2183 2180 # Things related to extracting values/expressions from kernel and user_ns
2184 2181 #-------------------------------------------------------------------------
2185 2182
2186 2183 def _simple_error(self):
2187 2184 etype, value = sys.exc_info()[:2]
2188 2185 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2189 2186
2190 2187 def user_variables(self, names):
2191 2188 """Get a list of variable names from the user's namespace.
2192 2189
2193 2190 Parameters
2194 2191 ----------
2195 2192 names : list of strings
2196 2193 A list of names of variables to be read from the user namespace.
2197 2194
2198 2195 Returns
2199 2196 -------
2200 2197 A dict, keyed by the input names and with the repr() of each value.
2201 2198 """
2202 2199 out = {}
2203 2200 user_ns = self.user_ns
2204 2201 for varname in names:
2205 2202 try:
2206 2203 value = repr(user_ns[varname])
2207 2204 except:
2208 2205 value = self._simple_error()
2209 2206 out[varname] = value
2210 2207 return out
2211 2208
2212 2209 def user_expressions(self, expressions):
2213 2210 """Evaluate a dict of expressions in the user's namespace.
2214 2211
2215 2212 Parameters
2216 2213 ----------
2217 2214 expressions : dict
2218 2215 A dict with string keys and string values. The expression values
2219 2216 should be valid Python expressions, each of which will be evaluated
2220 2217 in the user namespace.
2221 2218
2222 2219 Returns
2223 2220 -------
2224 2221 A dict, keyed like the input expressions dict, with the repr() of each
2225 2222 value.
2226 2223 """
2227 2224 out = {}
2228 2225 user_ns = self.user_ns
2229 2226 global_ns = self.user_global_ns
2230 2227 for key, expr in expressions.iteritems():
2231 2228 try:
2232 2229 value = repr(eval(expr, global_ns, user_ns))
2233 2230 except:
2234 2231 value = self._simple_error()
2235 2232 out[key] = value
2236 2233 return out
2237 2234
2238 2235 #-------------------------------------------------------------------------
2239 2236 # Things related to the running of code
2240 2237 #-------------------------------------------------------------------------
2241 2238
2242 2239 def ex(self, cmd):
2243 2240 """Execute a normal python statement in user namespace."""
2244 2241 with self.builtin_trap:
2245 2242 exec cmd in self.user_global_ns, self.user_ns
2246 2243
2247 2244 def ev(self, expr):
2248 2245 """Evaluate python expression expr in user namespace.
2249 2246
2250 2247 Returns the result of evaluation
2251 2248 """
2252 2249 with self.builtin_trap:
2253 2250 return eval(expr, self.user_global_ns, self.user_ns)
2254 2251
2255 2252 def safe_execfile(self, fname, *where, **kw):
2256 2253 """A safe version of the builtin execfile().
2257 2254
2258 2255 This version will never throw an exception, but instead print
2259 2256 helpful error messages to the screen. This only works on pure
2260 2257 Python files with the .py extension.
2261 2258
2262 2259 Parameters
2263 2260 ----------
2264 2261 fname : string
2265 2262 The name of the file to be executed.
2266 2263 where : tuple
2267 2264 One or two namespaces, passed to execfile() as (globals,locals).
2268 2265 If only one is given, it is passed as both.
2269 2266 exit_ignore : bool (False)
2270 2267 If True, then silence SystemExit for non-zero status (it is always
2271 2268 silenced for zero status, as it is so common).
2272 2269 raise_exceptions : bool (False)
2273 2270 If True raise exceptions everywhere. Meant for testing.
2274 2271
2275 2272 """
2276 2273 kw.setdefault('exit_ignore', False)
2277 2274 kw.setdefault('raise_exceptions', False)
2278 2275
2279 2276 fname = os.path.abspath(os.path.expanduser(fname))
2280 2277
2281 2278 # Make sure we can open the file
2282 2279 try:
2283 2280 with open(fname) as thefile:
2284 2281 pass
2285 2282 except:
2286 2283 warn('Could not open file <%s> for safe execution.' % fname)
2287 2284 return
2288 2285
2289 2286 # Find things also in current directory. This is needed to mimic the
2290 2287 # behavior of running a script from the system command line, where
2291 2288 # Python inserts the script's directory into sys.path
2292 2289 dname = os.path.dirname(fname)
2293 2290
2294 2291 with prepended_to_syspath(dname):
2295 2292 try:
2296 2293 py3compat.execfile(fname,*where)
2297 2294 except SystemExit, status:
2298 2295 # If the call was made with 0 or None exit status (sys.exit(0)
2299 2296 # or sys.exit() ), don't bother showing a traceback, as both of
2300 2297 # these are considered normal by the OS:
2301 2298 # > python -c'import sys;sys.exit(0)'; echo $?
2302 2299 # 0
2303 2300 # > python -c'import sys;sys.exit()'; echo $?
2304 2301 # 0
2305 2302 # For other exit status, we show the exception unless
2306 2303 # explicitly silenced, but only in short form.
2307 2304 if kw['raise_exceptions']:
2308 2305 raise
2309 2306 if status.code not in (0, None) and not kw['exit_ignore']:
2310 2307 self.showtraceback(exception_only=True)
2311 2308 except:
2312 2309 if kw['raise_exceptions']:
2313 2310 raise
2314 2311 self.showtraceback()
2315 2312
2316 2313 def safe_execfile_ipy(self, fname):
2317 2314 """Like safe_execfile, but for .ipy files with IPython syntax.
2318 2315
2319 2316 Parameters
2320 2317 ----------
2321 2318 fname : str
2322 2319 The name of the file to execute. The filename must have a
2323 2320 .ipy extension.
2324 2321 """
2325 2322 fname = os.path.abspath(os.path.expanduser(fname))
2326 2323
2327 2324 # Make sure we can open the file
2328 2325 try:
2329 2326 with open(fname) as thefile:
2330 2327 pass
2331 2328 except:
2332 2329 warn('Could not open file <%s> for safe execution.' % fname)
2333 2330 return
2334 2331
2335 2332 # Find things also in current directory. This is needed to mimic the
2336 2333 # behavior of running a script from the system command line, where
2337 2334 # Python inserts the script's directory into sys.path
2338 2335 dname = os.path.dirname(fname)
2339 2336
2340 2337 with prepended_to_syspath(dname):
2341 2338 try:
2342 2339 with open(fname) as thefile:
2343 2340 # self.run_cell currently captures all exceptions
2344 2341 # raised in user code. It would be nice if there were
2345 2342 # versions of runlines, execfile that did raise, so
2346 2343 # we could catch the errors.
2347 2344 self.run_cell(thefile.read(), store_history=False)
2348 2345 except:
2349 2346 self.showtraceback()
2350 2347 warn('Unknown failure executing file: <%s>' % fname)
2351 2348
2352 2349 def run_cell(self, raw_cell, store_history=False):
2353 2350 """Run a complete IPython cell.
2354 2351
2355 2352 Parameters
2356 2353 ----------
2357 2354 raw_cell : str
2358 2355 The code (including IPython code such as %magic functions) to run.
2359 2356 store_history : bool
2360 2357 If True, the raw and translated cell will be stored in IPython's
2361 2358 history. For user code calling back into IPython's machinery, this
2362 2359 should be set to False.
2363 2360 """
2364 2361 if (not raw_cell) or raw_cell.isspace():
2365 2362 return
2366 2363
2367 2364 for line in raw_cell.splitlines():
2368 2365 self.input_splitter.push(line)
2369 2366 cell = self.input_splitter.source_reset()
2370 2367
2371 2368 with self.builtin_trap:
2372 2369 prefilter_failed = False
2373 2370 if len(cell.splitlines()) == 1:
2374 2371 try:
2375 2372 # use prefilter_lines to handle trailing newlines
2376 2373 # restore trailing newline for ast.parse
2377 2374 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2378 2375 except AliasError as e:
2379 2376 error(e)
2380 2377 prefilter_failed = True
2381 2378 except Exception:
2382 2379 # don't allow prefilter errors to crash IPython
2383 2380 self.showtraceback()
2384 2381 prefilter_failed = True
2385 2382
2386 2383 # Store raw and processed history
2387 2384 if store_history:
2388 2385 self.history_manager.store_inputs(self.execution_count,
2389 2386 cell, raw_cell)
2390 2387
2391 2388 self.logger.log(cell, raw_cell)
2392 2389
2393 2390 if not prefilter_failed:
2394 2391 # don't run if prefilter failed
2395 2392 cell_name = self.compile.cache(cell, self.execution_count)
2396 2393
2397 2394 with self.display_trap:
2398 2395 try:
2399 2396 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2400 2397 except IndentationError:
2401 2398 self.showindentationerror()
2402 2399 self.execution_count += 1
2403 2400 return None
2404 2401 except (OverflowError, SyntaxError, ValueError, TypeError,
2405 2402 MemoryError):
2406 2403 self.showsyntaxerror()
2407 2404 self.execution_count += 1
2408 2405 return None
2409 2406
2410 2407 self.run_ast_nodes(code_ast.body, cell_name,
2411 2408 interactivity="last_expr")
2412 2409
2413 2410 # Execute any registered post-execution functions.
2414 2411 for func, status in self._post_execute.iteritems():
2415 2412 if not status:
2416 2413 continue
2417 2414 try:
2418 2415 func()
2419 2416 except:
2420 2417 self.showtraceback()
2421 2418 # Deactivate failing function
2422 2419 self._post_execute[func] = False
2423 2420
2424 2421 if store_history:
2425 2422 # Write output to the database. Does nothing unless
2426 2423 # history output logging is enabled.
2427 2424 self.history_manager.store_output(self.execution_count)
2428 2425 # Each cell is a *single* input, regardless of how many lines it has
2429 2426 self.execution_count += 1
2430 2427
2431 2428 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2432 2429 """Run a sequence of AST nodes. The execution mode depends on the
2433 2430 interactivity parameter.
2434 2431
2435 2432 Parameters
2436 2433 ----------
2437 2434 nodelist : list
2438 2435 A sequence of AST nodes to run.
2439 2436 cell_name : str
2440 2437 Will be passed to the compiler as the filename of the cell. Typically
2441 2438 the value returned by ip.compile.cache(cell).
2442 2439 interactivity : str
2443 2440 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2444 2441 run interactively (displaying output from expressions). 'last_expr'
2445 2442 will run the last node interactively only if it is an expression (i.e.
2446 2443 expressions in loops or other blocks are not displayed. Other values
2447 2444 for this parameter will raise a ValueError.
2448 2445 """
2449 2446 if not nodelist:
2450 2447 return
2451 2448
2452 2449 if interactivity == 'last_expr':
2453 2450 if isinstance(nodelist[-1], ast.Expr):
2454 2451 interactivity = "last"
2455 2452 else:
2456 2453 interactivity = "none"
2457 2454
2458 2455 if interactivity == 'none':
2459 2456 to_run_exec, to_run_interactive = nodelist, []
2460 2457 elif interactivity == 'last':
2461 2458 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2462 2459 elif interactivity == 'all':
2463 2460 to_run_exec, to_run_interactive = [], nodelist
2464 2461 else:
2465 2462 raise ValueError("Interactivity was %r" % interactivity)
2466 2463
2467 2464 exec_count = self.execution_count
2468 2465
2469 2466 try:
2470 2467 for i, node in enumerate(to_run_exec):
2471 2468 mod = ast.Module([node])
2472 2469 code = self.compile(mod, cell_name, "exec")
2473 2470 if self.run_code(code):
2474 2471 return True
2475 2472
2476 2473 for i, node in enumerate(to_run_interactive):
2477 2474 mod = ast.Interactive([node])
2478 2475 code = self.compile(mod, cell_name, "single")
2479 2476 if self.run_code(code):
2480 2477 return True
2481 2478 except:
2482 2479 # It's possible to have exceptions raised here, typically by
2483 2480 # compilation of odd code (such as a naked 'return' outside a
2484 2481 # function) that did parse but isn't valid. Typically the exception
2485 2482 # is a SyntaxError, but it's safest just to catch anything and show
2486 2483 # the user a traceback.
2487 2484
2488 2485 # We do only one try/except outside the loop to minimize the impact
2489 2486 # on runtime, and also because if any node in the node list is
2490 2487 # broken, we should stop execution completely.
2491 2488 self.showtraceback()
2492 2489
2493 2490 return False
2494 2491
2495 2492 def run_code(self, code_obj):
2496 2493 """Execute a code object.
2497 2494
2498 2495 When an exception occurs, self.showtraceback() is called to display a
2499 2496 traceback.
2500 2497
2501 2498 Parameters
2502 2499 ----------
2503 2500 code_obj : code object
2504 2501 A compiled code object, to be executed
2505 2502 post_execute : bool [default: True]
2506 2503 whether to call post_execute hooks after this particular execution.
2507 2504
2508 2505 Returns
2509 2506 -------
2510 2507 False : successful execution.
2511 2508 True : an error occurred.
2512 2509 """
2513 2510
2514 2511 # Set our own excepthook in case the user code tries to call it
2515 2512 # directly, so that the IPython crash handler doesn't get triggered
2516 2513 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2517 2514
2518 2515 # we save the original sys.excepthook in the instance, in case config
2519 2516 # code (such as magics) needs access to it.
2520 2517 self.sys_excepthook = old_excepthook
2521 2518 outflag = 1 # happens in more places, so it's easier as default
2522 2519 try:
2523 2520 try:
2524 2521 self.hooks.pre_run_code_hook()
2525 2522 #rprint('Running code', repr(code_obj)) # dbg
2526 2523 exec code_obj in self.user_global_ns, self.user_ns
2527 2524 finally:
2528 2525 # Reset our crash handler in place
2529 2526 sys.excepthook = old_excepthook
2530 2527 except SystemExit:
2531 2528 self.showtraceback(exception_only=True)
2532 2529 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2533 2530 except self.custom_exceptions:
2534 2531 etype,value,tb = sys.exc_info()
2535 2532 self.CustomTB(etype,value,tb)
2536 2533 except:
2537 2534 self.showtraceback()
2538 2535 else:
2539 2536 outflag = 0
2540 2537 if softspace(sys.stdout, 0):
2541 2538 print
2542 2539
2543 2540 return outflag
2544 2541
2545 2542 # For backwards compatibility
2546 2543 runcode = run_code
2547 2544
2548 2545 #-------------------------------------------------------------------------
2549 2546 # Things related to GUI support and pylab
2550 2547 #-------------------------------------------------------------------------
2551 2548
2552 2549 def enable_pylab(self, gui=None, import_all=True):
2553 2550 raise NotImplementedError('Implement enable_pylab in a subclass')
2554 2551
2555 2552 #-------------------------------------------------------------------------
2556 2553 # Utilities
2557 2554 #-------------------------------------------------------------------------
2558 2555
2559 2556 def var_expand(self,cmd,depth=0):
2560 2557 """Expand python variables in a string.
2561 2558
2562 2559 The depth argument indicates how many frames above the caller should
2563 2560 be walked to look for the local namespace where to expand variables.
2564 2561
2565 2562 The global namespace for expansion is always the user's interactive
2566 2563 namespace.
2567 2564 """
2568 2565 res = ItplNS(cmd, self.user_ns, # globals
2569 2566 # Skip our own frame in searching for locals:
2570 2567 sys._getframe(depth+1).f_locals # locals
2571 2568 )
2572 2569 return py3compat.str_to_unicode(str(res), res.codec)
2573 2570
2574 2571 def mktempfile(self, data=None, prefix='ipython_edit_'):
2575 2572 """Make a new tempfile and return its filename.
2576 2573
2577 2574 This makes a call to tempfile.mktemp, but it registers the created
2578 2575 filename internally so ipython cleans it up at exit time.
2579 2576
2580 2577 Optional inputs:
2581 2578
2582 2579 - data(None): if data is given, it gets written out to the temp file
2583 2580 immediately, and the file is closed again."""
2584 2581
2585 2582 filename = tempfile.mktemp('.py', prefix)
2586 2583 self.tempfiles.append(filename)
2587 2584
2588 2585 if data:
2589 2586 tmp_file = open(filename,'w')
2590 2587 tmp_file.write(data)
2591 2588 tmp_file.close()
2592 2589 return filename
2593 2590
2594 2591 # TODO: This should be removed when Term is refactored.
2595 2592 def write(self,data):
2596 2593 """Write a string to the default output"""
2597 2594 io.stdout.write(data)
2598 2595
2599 2596 # TODO: This should be removed when Term is refactored.
2600 2597 def write_err(self,data):
2601 2598 """Write a string to the default error output"""
2602 2599 io.stderr.write(data)
2603 2600
2604 2601 def ask_yes_no(self,prompt,default=True):
2605 2602 if self.quiet:
2606 2603 return True
2607 2604 return ask_yes_no(prompt,default)
2608 2605
2609 2606 def show_usage(self):
2610 2607 """Show a usage message"""
2611 2608 page.page(IPython.core.usage.interactive_usage)
2612 2609
2613 2610 def find_user_code(self, target, raw=True):
2614 2611 """Get a code string from history, file, or a string or macro.
2615 2612
2616 2613 This is mainly used by magic functions.
2617 2614
2618 2615 Parameters
2619 2616 ----------
2620 2617 target : str
2621 2618 A string specifying code to retrieve. This will be tried respectively
2622 2619 as: ranges of input history (see %history for syntax), a filename, or
2623 2620 an expression evaluating to a string or Macro in the user namespace.
2624 2621 raw : bool
2625 2622 If true (default), retrieve raw history. Has no effect on the other
2626 2623 retrieval mechanisms.
2627 2624
2628 2625 Returns
2629 2626 -------
2630 2627 A string of code.
2631 2628
2632 2629 ValueError is raised if nothing is found, and TypeError if it evaluates
2633 2630 to an object of another type. In each case, .args[0] is a printable
2634 2631 message.
2635 2632 """
2636 2633 code = self.extract_input_lines(target, raw=raw) # Grab history
2637 2634 if code:
2638 2635 return code
2639 2636 if os.path.isfile(target): # Read file
2640 2637 return open(target, "r").read()
2641 2638
2642 2639 try: # User namespace
2643 2640 codeobj = eval(target, self.user_ns)
2644 2641 except Exception:
2645 2642 raise ValueError(("'%s' was not found in history, as a file, nor in"
2646 2643 " the user namespace.") % target)
2647 2644 if isinstance(codeobj, basestring):
2648 2645 return codeobj
2649 2646 elif isinstance(codeobj, Macro):
2650 2647 return codeobj.value
2651 2648
2652 2649 raise TypeError("%s is neither a string nor a macro." % target,
2653 2650 codeobj)
2654 2651
2655 2652 #-------------------------------------------------------------------------
2656 2653 # Things related to IPython exiting
2657 2654 #-------------------------------------------------------------------------
2658 2655 def atexit_operations(self):
2659 2656 """This will be executed at the time of exit.
2660 2657
2661 2658 Cleanup operations and saving of persistent data that is done
2662 2659 unconditionally by IPython should be performed here.
2663 2660
2664 2661 For things that may depend on startup flags or platform specifics (such
2665 2662 as having readline or not), register a separate atexit function in the
2666 2663 code that has the appropriate information, rather than trying to
2667 2664 clutter
2668 2665 """
2669 2666 # Close the history session (this stores the end time and line count)
2670 2667 # this must be *before* the tempfile cleanup, in case of temporary
2671 2668 # history db
2672 2669 self.history_manager.end_session()
2673 2670
2674 2671 # Cleanup all tempfiles left around
2675 2672 for tfile in self.tempfiles:
2676 2673 try:
2677 2674 os.unlink(tfile)
2678 2675 except OSError:
2679 2676 pass
2680 2677
2681 2678 # Clear all user namespaces to release all references cleanly.
2682 2679 self.reset(new_session=False)
2683 2680
2684 2681 # Run user hooks
2685 2682 self.hooks.shutdown_hook()
2686 2683
2687 2684 def cleanup(self):
2688 2685 self.restore_sys_module_state()
2689 2686
2690 2687
2691 2688 class InteractiveShellABC(object):
2692 2689 """An abstract base class for InteractiveShell."""
2693 2690 __metaclass__ = abc.ABCMeta
2694 2691
2695 2692 InteractiveShellABC.register(InteractiveShell)
@@ -1,3713 +1,3726 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__ as builtin_mod
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import imp
23 23 import os
24 24 import sys
25 25 import shutil
26 26 import re
27 27 import time
28 28 import textwrap
29 29 from StringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pformat
32 32 from xmlrpclib import ServerProxy
33 33
34 34 # cProfile was added in Python2.5
35 35 try:
36 36 import cProfile as profile
37 37 import pstats
38 38 except ImportError:
39 39 # profile isn't bundled by default in Debian for license reasons
40 40 try:
41 41 import profile,pstats
42 42 except ImportError:
43 43 profile = pstats = None
44 44
45 45 import IPython
46 46 from IPython.core import debugger, oinspect
47 47 from IPython.core.error import TryNext
48 48 from IPython.core.error import UsageError
49 49 from IPython.core.fakemodule import FakeModule
50 50 from IPython.core.profiledir import ProfileDir
51 51 from IPython.core.macro import Macro
52 52 from IPython.core import magic_arguments, page
53 53 from IPython.core.prefilter import ESC_MAGIC
54 54 from IPython.lib.pylabtools import mpl_runner
55 55 from IPython.testing.skipdoctest import skip_doctest
56 56 from IPython.utils import py3compat
57 57 from IPython.utils.io import file_read, nlprint
58 58 from IPython.utils.module_paths import find_mod
59 59 from IPython.utils.path import get_py_filename, unquote_filename
60 60 from IPython.utils.process import arg_split, abbrev_cwd
61 61 from IPython.utils.terminal import set_term_title
62 62 from IPython.utils.text import LSString, SList, format_screen
63 63 from IPython.utils.timing import clock, clock2
64 64 from IPython.utils.warn import warn, error
65 65 from IPython.utils.ipstruct import Struct
66 66 from IPython.config.application import Application
67 67
68 68 #-----------------------------------------------------------------------------
69 69 # Utility functions
70 70 #-----------------------------------------------------------------------------
71 71
72 72 def on_off(tag):
73 73 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
74 74 return ['OFF','ON'][tag]
75 75
76 76 class Bunch: pass
77 77
78 78 def compress_dhist(dh):
79 79 head, tail = dh[:-10], dh[-10:]
80 80
81 81 newhead = []
82 82 done = set()
83 83 for h in head:
84 84 if h in done:
85 85 continue
86 86 newhead.append(h)
87 87 done.add(h)
88 88
89 89 return newhead + tail
90 90
91 91 def needs_local_scope(func):
92 92 """Decorator to mark magic functions which need to local scope to run."""
93 93 func.needs_local_scope = True
94 94 return func
95 95
96 96
97 97 # Used for exception handling in magic_edit
98 98 class MacroToEdit(ValueError): pass
99 99
100 100 #***************************************************************************
101 101 # Main class implementing Magic functionality
102 102
103 103 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
104 104 # on construction of the main InteractiveShell object. Something odd is going
105 105 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
106 106 # eventually this needs to be clarified.
107 107 # BG: This is because InteractiveShell inherits from this, but is itself a
108 108 # Configurable. This messes up the MRO in some way. The fix is that we need to
109 109 # make Magic a configurable that InteractiveShell does not subclass.
110 110
111 111 class Magic:
112 112 """Magic functions for InteractiveShell.
113 113
114 114 Shell functions which can be reached as %function_name. All magic
115 115 functions should accept a string, which they can parse for their own
116 116 needs. This can make some functions easier to type, eg `%cd ../`
117 117 vs. `%cd("../")`
118 118
119 119 ALL definitions MUST begin with the prefix magic_. The user won't need it
120 120 at the command line, but it is is needed in the definition. """
121 121
122 122 # class globals
123 123 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
124 124 'Automagic is ON, % prefix NOT needed for magic functions.']
125 125
126 126
127 127 configurables = None
128 128 #......................................................................
129 129 # some utility functions
130 130
131 131 def __init__(self,shell):
132 132
133 133 self.options_table = {}
134 134 if profile is None:
135 135 self.magic_prun = self.profile_missing_notice
136 136 self.shell = shell
137 137 if self.configurables is None:
138 138 self.configurables = []
139 139
140 140 # namespace for holding state we may need
141 141 self._magic_state = Bunch()
142 142
143 143 def profile_missing_notice(self, *args, **kwargs):
144 144 error("""\
145 145 The profile module could not be found. It has been removed from the standard
146 146 python packages because of its non-free license. To use profiling, install the
147 147 python-profiler package from non-free.""")
148 148
149 149 def default_option(self,fn,optstr):
150 150 """Make an entry in the options_table for fn, with value optstr"""
151 151
152 152 if fn not in self.lsmagic():
153 153 error("%s is not a magic function" % fn)
154 154 self.options_table[fn] = optstr
155 155
156 156 def lsmagic(self):
157 157 """Return a list of currently available magic functions.
158 158
159 159 Gives a list of the bare names after mangling (['ls','cd', ...], not
160 160 ['magic_ls','magic_cd',...]"""
161 161
162 162 # FIXME. This needs a cleanup, in the way the magics list is built.
163 163
164 164 # magics in class definition
165 165 class_magic = lambda fn: fn.startswith('magic_') and \
166 166 callable(Magic.__dict__[fn])
167 167 # in instance namespace (run-time user additions)
168 168 inst_magic = lambda fn: fn.startswith('magic_') and \
169 169 callable(self.__dict__[fn])
170 170 # and bound magics by user (so they can access self):
171 171 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
172 172 callable(self.__class__.__dict__[fn])
173 173 magics = filter(class_magic,Magic.__dict__.keys()) + \
174 174 filter(inst_magic,self.__dict__.keys()) + \
175 175 filter(inst_bound_magic,self.__class__.__dict__.keys())
176 176 out = []
177 177 for fn in set(magics):
178 178 out.append(fn.replace('magic_','',1))
179 179 out.sort()
180 180 return out
181 181
182 182 def extract_input_lines(self, range_str, raw=False):
183 183 """Return as a string a set of input history slices.
184 184
185 185 Inputs:
186 186
187 187 - range_str: the set of slices is given as a string, like
188 188 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
189 189 which get their arguments as strings. The number before the / is the
190 190 session number: ~n goes n back from the current session.
191 191
192 192 Optional inputs:
193 193
194 194 - raw(False): by default, the processed input is used. If this is
195 195 true, the raw input history is used instead.
196 196
197 197 Note that slices can be called with two notations:
198 198
199 199 N:M -> standard python form, means including items N...(M-1).
200 200
201 201 N-M -> include items N..M (closed endpoint)."""
202 202 lines = self.shell.history_manager.\
203 203 get_range_by_str(range_str, raw=raw)
204 204 return "\n".join(x for _, _, x in lines)
205 205
206 206 def arg_err(self,func):
207 207 """Print docstring if incorrect arguments were passed"""
208 208 print 'Error in arguments:'
209 209 print oinspect.getdoc(func)
210 210
211 211 def format_latex(self,strng):
212 212 """Format a string for latex inclusion."""
213 213
214 214 # Characters that need to be escaped for latex:
215 215 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
216 216 # Magic command names as headers:
217 217 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
218 218 re.MULTILINE)
219 219 # Magic commands
220 220 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
221 221 re.MULTILINE)
222 222 # Paragraph continue
223 223 par_re = re.compile(r'\\$',re.MULTILINE)
224 224
225 225 # The "\n" symbol
226 226 newline_re = re.compile(r'\\n')
227 227
228 228 # Now build the string for output:
229 229 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
230 230 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
231 231 strng)
232 232 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
233 233 strng = par_re.sub(r'\\\\',strng)
234 234 strng = escape_re.sub(r'\\\1',strng)
235 235 strng = newline_re.sub(r'\\textbackslash{}n',strng)
236 236 return strng
237 237
238 238 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
239 239 """Parse options passed to an argument string.
240 240
241 241 The interface is similar to that of getopt(), but it returns back a
242 242 Struct with the options as keys and the stripped argument string still
243 243 as a string.
244 244
245 245 arg_str is quoted as a true sys.argv vector by using shlex.split.
246 246 This allows us to easily expand variables, glob files, quote
247 247 arguments, etc.
248 248
249 249 Options:
250 250 -mode: default 'string'. If given as 'list', the argument string is
251 251 returned as a list (split on whitespace) instead of a string.
252 252
253 253 -list_all: put all option values in lists. Normally only options
254 254 appearing more than once are put in a list.
255 255
256 256 -posix (True): whether to split the input line in POSIX mode or not,
257 257 as per the conventions outlined in the shlex module from the
258 258 standard library."""
259 259
260 260 # inject default options at the beginning of the input line
261 261 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
262 262 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
263 263
264 264 mode = kw.get('mode','string')
265 265 if mode not in ['string','list']:
266 266 raise ValueError,'incorrect mode given: %s' % mode
267 267 # Get options
268 268 list_all = kw.get('list_all',0)
269 269 posix = kw.get('posix', os.name == 'posix')
270 270
271 271 # Check if we have more than one argument to warrant extra processing:
272 272 odict = {} # Dictionary with options
273 273 args = arg_str.split()
274 274 if len(args) >= 1:
275 275 # If the list of inputs only has 0 or 1 thing in it, there's no
276 276 # need to look for options
277 277 argv = arg_split(arg_str,posix)
278 278 # Do regular option processing
279 279 try:
280 280 opts,args = getopt(argv,opt_str,*long_opts)
281 281 except GetoptError,e:
282 282 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
283 283 " ".join(long_opts)))
284 284 for o,a in opts:
285 285 if o.startswith('--'):
286 286 o = o[2:]
287 287 else:
288 288 o = o[1:]
289 289 try:
290 290 odict[o].append(a)
291 291 except AttributeError:
292 292 odict[o] = [odict[o],a]
293 293 except KeyError:
294 294 if list_all:
295 295 odict[o] = [a]
296 296 else:
297 297 odict[o] = a
298 298
299 299 # Prepare opts,args for return
300 300 opts = Struct(odict)
301 301 if mode == 'string':
302 302 args = ' '.join(args)
303 303
304 304 return opts,args
305 305
306 306 #......................................................................
307 307 # And now the actual magic functions
308 308
309 309 # Functions for IPython shell work (vars,funcs, config, etc)
310 310 def magic_lsmagic(self, parameter_s = ''):
311 311 """List currently available magic functions."""
312 312 mesc = ESC_MAGIC
313 313 print 'Available magic functions:\n'+mesc+\
314 314 (' '+mesc).join(self.lsmagic())
315 315 print '\n' + Magic.auto_status[self.shell.automagic]
316 316 return None
317 317
318 318 def magic_magic(self, parameter_s = ''):
319 319 """Print information about the magic function system.
320 320
321 321 Supported formats: -latex, -brief, -rest
322 322 """
323 323
324 324 mode = ''
325 325 try:
326 326 if parameter_s.split()[0] == '-latex':
327 327 mode = 'latex'
328 328 if parameter_s.split()[0] == '-brief':
329 329 mode = 'brief'
330 330 if parameter_s.split()[0] == '-rest':
331 331 mode = 'rest'
332 332 rest_docs = []
333 333 except:
334 334 pass
335 335
336 336 magic_docs = []
337 337 for fname in self.lsmagic():
338 338 mname = 'magic_' + fname
339 339 for space in (Magic,self,self.__class__):
340 340 try:
341 341 fn = space.__dict__[mname]
342 342 except KeyError:
343 343 pass
344 344 else:
345 345 break
346 346 if mode == 'brief':
347 347 # only first line
348 348 if fn.__doc__:
349 349 fndoc = fn.__doc__.split('\n',1)[0]
350 350 else:
351 351 fndoc = 'No documentation'
352 352 else:
353 353 if fn.__doc__:
354 354 fndoc = fn.__doc__.rstrip()
355 355 else:
356 356 fndoc = 'No documentation'
357 357
358 358
359 359 if mode == 'rest':
360 360 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
361 361 fname,fndoc))
362 362
363 363 else:
364 364 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
365 365 fname,fndoc))
366 366
367 367 magic_docs = ''.join(magic_docs)
368 368
369 369 if mode == 'rest':
370 370 return "".join(rest_docs)
371 371
372 372 if mode == 'latex':
373 373 print self.format_latex(magic_docs)
374 374 return
375 375 else:
376 376 magic_docs = format_screen(magic_docs)
377 377 if mode == 'brief':
378 378 return magic_docs
379 379
380 380 outmsg = """
381 381 IPython's 'magic' functions
382 382 ===========================
383 383
384 384 The magic function system provides a series of functions which allow you to
385 385 control the behavior of IPython itself, plus a lot of system-type
386 386 features. All these functions are prefixed with a % character, but parameters
387 387 are given without parentheses or quotes.
388 388
389 389 NOTE: If you have 'automagic' enabled (via the command line option or with the
390 390 %automagic function), you don't need to type in the % explicitly. By default,
391 391 IPython ships with automagic on, so you should only rarely need the % escape.
392 392
393 393 Example: typing '%cd mydir' (without the quotes) changes you working directory
394 394 to 'mydir', if it exists.
395 395
396 396 For a list of the available magic functions, use %lsmagic. For a description
397 397 of any of them, type %magic_name?, e.g. '%cd?'.
398 398
399 399 Currently the magic system has the following functions:\n"""
400 400
401 401 mesc = ESC_MAGIC
402 402 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
403 403 "\n\n%s%s\n\n%s" % (outmsg,
404 404 magic_docs,mesc,mesc,
405 405 (' '+mesc).join(self.lsmagic()),
406 406 Magic.auto_status[self.shell.automagic] ) )
407 407 page.page(outmsg)
408 408
409 409 def magic_automagic(self, parameter_s = ''):
410 410 """Make magic functions callable without having to type the initial %.
411 411
412 412 Without argumentsl toggles on/off (when off, you must call it as
413 413 %automagic, of course). With arguments it sets the value, and you can
414 414 use any of (case insensitive):
415 415
416 416 - on,1,True: to activate
417 417
418 418 - off,0,False: to deactivate.
419 419
420 420 Note that magic functions have lowest priority, so if there's a
421 421 variable whose name collides with that of a magic fn, automagic won't
422 422 work for that function (you get the variable instead). However, if you
423 423 delete the variable (del var), the previously shadowed magic function
424 424 becomes visible to automagic again."""
425 425
426 426 arg = parameter_s.lower()
427 427 if parameter_s in ('on','1','true'):
428 428 self.shell.automagic = True
429 429 elif parameter_s in ('off','0','false'):
430 430 self.shell.automagic = False
431 431 else:
432 432 self.shell.automagic = not self.shell.automagic
433 433 print '\n' + Magic.auto_status[self.shell.automagic]
434 434
435 435 @skip_doctest
436 436 def magic_autocall(self, parameter_s = ''):
437 437 """Make functions callable without having to type parentheses.
438 438
439 439 Usage:
440 440
441 441 %autocall [mode]
442 442
443 443 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
444 444 value is toggled on and off (remembering the previous state).
445 445
446 446 In more detail, these values mean:
447 447
448 448 0 -> fully disabled
449 449
450 450 1 -> active, but do not apply if there are no arguments on the line.
451 451
452 452 In this mode, you get:
453 453
454 454 In [1]: callable
455 455 Out[1]: <built-in function callable>
456 456
457 457 In [2]: callable 'hello'
458 458 ------> callable('hello')
459 459 Out[2]: False
460 460
461 461 2 -> Active always. Even if no arguments are present, the callable
462 462 object is called:
463 463
464 464 In [2]: float
465 465 ------> float()
466 466 Out[2]: 0.0
467 467
468 468 Note that even with autocall off, you can still use '/' at the start of
469 469 a line to treat the first argument on the command line as a function
470 470 and add parentheses to it:
471 471
472 472 In [8]: /str 43
473 473 ------> str(43)
474 474 Out[8]: '43'
475 475
476 476 # all-random (note for auto-testing)
477 477 """
478 478
479 479 if parameter_s:
480 480 arg = int(parameter_s)
481 481 else:
482 482 arg = 'toggle'
483 483
484 484 if not arg in (0,1,2,'toggle'):
485 485 error('Valid modes: (0->Off, 1->Smart, 2->Full')
486 486 return
487 487
488 488 if arg in (0,1,2):
489 489 self.shell.autocall = arg
490 490 else: # toggle
491 491 if self.shell.autocall:
492 492 self._magic_state.autocall_save = self.shell.autocall
493 493 self.shell.autocall = 0
494 494 else:
495 495 try:
496 496 self.shell.autocall = self._magic_state.autocall_save
497 497 except AttributeError:
498 498 self.shell.autocall = self._magic_state.autocall_save = 1
499 499
500 500 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
501 501
502 502
503 503 def magic_page(self, parameter_s=''):
504 504 """Pretty print the object and display it through a pager.
505 505
506 506 %page [options] OBJECT
507 507
508 508 If no object is given, use _ (last output).
509 509
510 510 Options:
511 511
512 512 -r: page str(object), don't pretty-print it."""
513 513
514 514 # After a function contributed by Olivier Aubert, slightly modified.
515 515
516 516 # Process options/args
517 517 opts,args = self.parse_options(parameter_s,'r')
518 518 raw = 'r' in opts
519 519
520 520 oname = args and args or '_'
521 521 info = self._ofind(oname)
522 522 if info['found']:
523 523 txt = (raw and str or pformat)( info['obj'] )
524 524 page.page(txt)
525 525 else:
526 526 print 'Object `%s` not found' % oname
527 527
528 528 def magic_profile(self, parameter_s=''):
529 529 """Print your currently active IPython profile."""
530 530 print self.shell.profile
531 531
532 532 def magic_pinfo(self, parameter_s='', namespaces=None):
533 533 """Provide detailed information about an object.
534 534
535 535 '%pinfo object' is just a synonym for object? or ?object."""
536 536
537 537 #print 'pinfo par: <%s>' % parameter_s # dbg
538 538
539 539
540 540 # detail_level: 0 -> obj? , 1 -> obj??
541 541 detail_level = 0
542 542 # We need to detect if we got called as 'pinfo pinfo foo', which can
543 543 # happen if the user types 'pinfo foo?' at the cmd line.
544 544 pinfo,qmark1,oname,qmark2 = \
545 545 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
546 546 if pinfo or qmark1 or qmark2:
547 547 detail_level = 1
548 548 if "*" in oname:
549 549 self.magic_psearch(oname)
550 550 else:
551 551 self.shell._inspect('pinfo', oname, detail_level=detail_level,
552 552 namespaces=namespaces)
553 553
554 554 def magic_pinfo2(self, parameter_s='', namespaces=None):
555 555 """Provide extra detailed information about an object.
556 556
557 557 '%pinfo2 object' is just a synonym for object?? or ??object."""
558 558 self.shell._inspect('pinfo', parameter_s, detail_level=1,
559 559 namespaces=namespaces)
560 560
561 561 @skip_doctest
562 562 def magic_pdef(self, parameter_s='', namespaces=None):
563 563 """Print the definition header for any callable object.
564 564
565 565 If the object is a class, print the constructor information.
566 566
567 567 Examples
568 568 --------
569 569 ::
570 570
571 571 In [3]: %pdef urllib.urlopen
572 572 urllib.urlopen(url, data=None, proxies=None)
573 573 """
574 574 self._inspect('pdef',parameter_s, namespaces)
575 575
576 576 def magic_pdoc(self, parameter_s='', namespaces=None):
577 577 """Print the docstring for an object.
578 578
579 579 If the given object is a class, it will print both the class and the
580 580 constructor docstrings."""
581 581 self._inspect('pdoc',parameter_s, namespaces)
582 582
583 583 def magic_psource(self, parameter_s='', namespaces=None):
584 584 """Print (or run through pager) the source code for an object."""
585 585 self._inspect('psource',parameter_s, namespaces)
586 586
587 587 def magic_pfile(self, parameter_s=''):
588 588 """Print (or run through pager) the file where an object is defined.
589 589
590 590 The file opens at the line where the object definition begins. IPython
591 591 will honor the environment variable PAGER if set, and otherwise will
592 592 do its best to print the file in a convenient form.
593 593
594 594 If the given argument is not an object currently defined, IPython will
595 595 try to interpret it as a filename (automatically adding a .py extension
596 596 if needed). You can thus use %pfile as a syntax highlighting code
597 597 viewer."""
598 598
599 599 # first interpret argument as an object name
600 600 out = self._inspect('pfile',parameter_s)
601 601 # if not, try the input as a filename
602 602 if out == 'not found':
603 603 try:
604 604 filename = get_py_filename(parameter_s)
605 605 except IOError,msg:
606 606 print msg
607 607 return
608 608 page.page(self.shell.inspector.format(file(filename).read()))
609 609
610 610 def magic_psearch(self, parameter_s=''):
611 611 """Search for object in namespaces by wildcard.
612 612
613 613 %psearch [options] PATTERN [OBJECT TYPE]
614 614
615 615 Note: ? can be used as a synonym for %psearch, at the beginning or at
616 616 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
617 617 rest of the command line must be unchanged (options come first), so
618 618 for example the following forms are equivalent
619 619
620 620 %psearch -i a* function
621 621 -i a* function?
622 622 ?-i a* function
623 623
624 624 Arguments:
625 625
626 626 PATTERN
627 627
628 628 where PATTERN is a string containing * as a wildcard similar to its
629 629 use in a shell. The pattern is matched in all namespaces on the
630 630 search path. By default objects starting with a single _ are not
631 631 matched, many IPython generated objects have a single
632 632 underscore. The default is case insensitive matching. Matching is
633 633 also done on the attributes of objects and not only on the objects
634 634 in a module.
635 635
636 636 [OBJECT TYPE]
637 637
638 638 Is the name of a python type from the types module. The name is
639 639 given in lowercase without the ending type, ex. StringType is
640 640 written string. By adding a type here only objects matching the
641 641 given type are matched. Using all here makes the pattern match all
642 642 types (this is the default).
643 643
644 644 Options:
645 645
646 646 -a: makes the pattern match even objects whose names start with a
647 647 single underscore. These names are normally ommitted from the
648 648 search.
649 649
650 650 -i/-c: make the pattern case insensitive/sensitive. If neither of
651 651 these options are given, the default is read from your configuration
652 652 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
653 653 If this option is not specified in your configuration file, IPython's
654 654 internal default is to do a case sensitive search.
655 655
656 656 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
657 657 specifiy can be searched in any of the following namespaces:
658 658 'builtin', 'user', 'user_global','internal', 'alias', where
659 659 'builtin' and 'user' are the search defaults. Note that you should
660 660 not use quotes when specifying namespaces.
661 661
662 662 'Builtin' contains the python module builtin, 'user' contains all
663 663 user data, 'alias' only contain the shell aliases and no python
664 664 objects, 'internal' contains objects used by IPython. The
665 665 'user_global' namespace is only used by embedded IPython instances,
666 666 and it contains module-level globals. You can add namespaces to the
667 667 search with -s or exclude them with -e (these options can be given
668 668 more than once).
669 669
670 670 Examples:
671 671
672 672 %psearch a* -> objects beginning with an a
673 673 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
674 674 %psearch a* function -> all functions beginning with an a
675 675 %psearch re.e* -> objects beginning with an e in module re
676 676 %psearch r*.e* -> objects that start with e in modules starting in r
677 677 %psearch r*.* string -> all strings in modules beginning with r
678 678
679 679 Case sensitve search:
680 680
681 681 %psearch -c a* list all object beginning with lower case a
682 682
683 683 Show objects beginning with a single _:
684 684
685 685 %psearch -a _* list objects beginning with a single underscore"""
686 686 try:
687 687 parameter_s.encode('ascii')
688 688 except UnicodeEncodeError:
689 689 print 'Python identifiers can only contain ascii characters.'
690 690 return
691 691
692 692 # default namespaces to be searched
693 693 def_search = ['user','builtin']
694 694
695 695 # Process options/args
696 696 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
697 697 opt = opts.get
698 698 shell = self.shell
699 699 psearch = shell.inspector.psearch
700 700
701 701 # select case options
702 702 if opts.has_key('i'):
703 703 ignore_case = True
704 704 elif opts.has_key('c'):
705 705 ignore_case = False
706 706 else:
707 707 ignore_case = not shell.wildcards_case_sensitive
708 708
709 709 # Build list of namespaces to search from user options
710 710 def_search.extend(opt('s',[]))
711 711 ns_exclude = ns_exclude=opt('e',[])
712 712 ns_search = [nm for nm in def_search if nm not in ns_exclude]
713 713
714 714 # Call the actual search
715 715 try:
716 716 psearch(args,shell.ns_table,ns_search,
717 717 show_all=opt('a'),ignore_case=ignore_case)
718 718 except:
719 719 shell.showtraceback()
720 720
721 721 @skip_doctest
722 722 def magic_who_ls(self, parameter_s=''):
723 723 """Return a sorted list of all interactive variables.
724 724
725 725 If arguments are given, only variables of types matching these
726 726 arguments are returned.
727 727
728 728 Examples
729 729 --------
730 730
731 731 Define two variables and list them with who_ls::
732 732
733 733 In [1]: alpha = 123
734 734
735 735 In [2]: beta = 'test'
736 736
737 737 In [3]: %who_ls
738 738 Out[3]: ['alpha', 'beta']
739 739
740 740 In [4]: %who_ls int
741 741 Out[4]: ['alpha']
742 742
743 743 In [5]: %who_ls str
744 744 Out[5]: ['beta']
745 745 """
746 746
747 747 user_ns = self.shell.user_ns
748 748 internal_ns = self.shell.internal_ns
749 749 user_ns_hidden = self.shell.user_ns_hidden
750 750 out = [ i for i in user_ns
751 751 if not i.startswith('_') \
752 752 and not (i in internal_ns or i in user_ns_hidden) ]
753 753
754 754 typelist = parameter_s.split()
755 755 if typelist:
756 756 typeset = set(typelist)
757 757 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
758 758
759 759 out.sort()
760 760 return out
761 761
762 762 @skip_doctest
763 763 def magic_who(self, parameter_s=''):
764 764 """Print all interactive variables, with some minimal formatting.
765 765
766 766 If any arguments are given, only variables whose type matches one of
767 767 these are printed. For example:
768 768
769 769 %who function str
770 770
771 771 will only list functions and strings, excluding all other types of
772 772 variables. To find the proper type names, simply use type(var) at a
773 773 command line to see how python prints type names. For example:
774 774
775 775 In [1]: type('hello')\\
776 776 Out[1]: <type 'str'>
777 777
778 778 indicates that the type name for strings is 'str'.
779 779
780 780 %who always excludes executed names loaded through your configuration
781 781 file and things which are internal to IPython.
782 782
783 783 This is deliberate, as typically you may load many modules and the
784 784 purpose of %who is to show you only what you've manually defined.
785 785
786 786 Examples
787 787 --------
788 788
789 789 Define two variables and list them with who::
790 790
791 791 In [1]: alpha = 123
792 792
793 793 In [2]: beta = 'test'
794 794
795 795 In [3]: %who
796 796 alpha beta
797 797
798 798 In [4]: %who int
799 799 alpha
800 800
801 801 In [5]: %who str
802 802 beta
803 803 """
804 804
805 805 varlist = self.magic_who_ls(parameter_s)
806 806 if not varlist:
807 807 if parameter_s:
808 808 print 'No variables match your requested type.'
809 809 else:
810 810 print 'Interactive namespace is empty.'
811 811 return
812 812
813 813 # if we have variables, move on...
814 814 count = 0
815 815 for i in varlist:
816 816 print i+'\t',
817 817 count += 1
818 818 if count > 8:
819 819 count = 0
820 820 print
821 821 print
822 822
823 823 @skip_doctest
824 824 def magic_whos(self, parameter_s=''):
825 825 """Like %who, but gives some extra information about each variable.
826 826
827 827 The same type filtering of %who can be applied here.
828 828
829 829 For all variables, the type is printed. Additionally it prints:
830 830
831 831 - For {},[],(): their length.
832 832
833 833 - For numpy arrays, a summary with shape, number of
834 834 elements, typecode and size in memory.
835 835
836 836 - Everything else: a string representation, snipping their middle if
837 837 too long.
838 838
839 839 Examples
840 840 --------
841 841
842 842 Define two variables and list them with whos::
843 843
844 844 In [1]: alpha = 123
845 845
846 846 In [2]: beta = 'test'
847 847
848 848 In [3]: %whos
849 849 Variable Type Data/Info
850 850 --------------------------------
851 851 alpha int 123
852 852 beta str test
853 853 """
854 854
855 855 varnames = self.magic_who_ls(parameter_s)
856 856 if not varnames:
857 857 if parameter_s:
858 858 print 'No variables match your requested type.'
859 859 else:
860 860 print 'Interactive namespace is empty.'
861 861 return
862 862
863 863 # if we have variables, move on...
864 864
865 865 # for these types, show len() instead of data:
866 866 seq_types = ['dict', 'list', 'tuple']
867 867
868 868 # for numpy arrays, display summary info
869 869 ndarray_type = None
870 870 if 'numpy' in sys.modules:
871 871 try:
872 872 from numpy import ndarray
873 873 except ImportError:
874 874 pass
875 875 else:
876 876 ndarray_type = ndarray.__name__
877 877
878 878 # Find all variable names and types so we can figure out column sizes
879 879 def get_vars(i):
880 880 return self.shell.user_ns[i]
881 881
882 882 # some types are well known and can be shorter
883 883 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
884 884 def type_name(v):
885 885 tn = type(v).__name__
886 886 return abbrevs.get(tn,tn)
887 887
888 888 varlist = map(get_vars,varnames)
889 889
890 890 typelist = []
891 891 for vv in varlist:
892 892 tt = type_name(vv)
893 893
894 894 if tt=='instance':
895 895 typelist.append( abbrevs.get(str(vv.__class__),
896 896 str(vv.__class__)))
897 897 else:
898 898 typelist.append(tt)
899 899
900 900 # column labels and # of spaces as separator
901 901 varlabel = 'Variable'
902 902 typelabel = 'Type'
903 903 datalabel = 'Data/Info'
904 904 colsep = 3
905 905 # variable format strings
906 906 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
907 907 aformat = "%s: %s elems, type `%s`, %s bytes"
908 908 # find the size of the columns to format the output nicely
909 909 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
910 910 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
911 911 # table header
912 912 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
913 913 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
914 914 # and the table itself
915 915 kb = 1024
916 916 Mb = 1048576 # kb**2
917 917 for vname,var,vtype in zip(varnames,varlist,typelist):
918 918 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
919 919 if vtype in seq_types:
920 920 print "n="+str(len(var))
921 921 elif vtype == ndarray_type:
922 922 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
923 923 if vtype==ndarray_type:
924 924 # numpy
925 925 vsize = var.size
926 926 vbytes = vsize*var.itemsize
927 927 vdtype = var.dtype
928 928 else:
929 929 # Numeric
930 930 vsize = Numeric.size(var)
931 931 vbytes = vsize*var.itemsize()
932 932 vdtype = var.typecode()
933 933
934 934 if vbytes < 100000:
935 935 print aformat % (vshape,vsize,vdtype,vbytes)
936 936 else:
937 937 print aformat % (vshape,vsize,vdtype,vbytes),
938 938 if vbytes < Mb:
939 939 print '(%s kb)' % (vbytes/kb,)
940 940 else:
941 941 print '(%s Mb)' % (vbytes/Mb,)
942 942 else:
943 943 try:
944 944 vstr = str(var)
945 945 except UnicodeEncodeError:
946 946 vstr = unicode(var).encode(sys.getdefaultencoding(),
947 947 'backslashreplace')
948 948 vstr = vstr.replace('\n','\\n')
949 949 if len(vstr) < 50:
950 950 print vstr
951 951 else:
952 952 print vstr[:25] + "<...>" + vstr[-25:]
953 953
954 954 def magic_reset(self, parameter_s=''):
955 955 """Resets the namespace by removing all names defined by the user.
956 956
957 957 Parameters
958 958 ----------
959 959 -f : force reset without asking for confirmation.
960 960
961 961 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
962 962 References to objects may be kept. By default (without this option),
963 963 we do a 'hard' reset, giving you a new session and removing all
964 964 references to objects from the current session.
965 965
966 966 Examples
967 967 --------
968 968 In [6]: a = 1
969 969
970 970 In [7]: a
971 971 Out[7]: 1
972 972
973 973 In [8]: 'a' in _ip.user_ns
974 974 Out[8]: True
975 975
976 976 In [9]: %reset -f
977 977
978 978 In [1]: 'a' in _ip.user_ns
979 979 Out[1]: False
980 980 """
981 981 opts, args = self.parse_options(parameter_s,'sf')
982 982 if 'f' in opts:
983 983 ans = True
984 984 else:
985 985 ans = self.shell.ask_yes_no(
986 986 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
987 987 if not ans:
988 988 print 'Nothing done.'
989 989 return
990 990
991 991 if 's' in opts: # Soft reset
992 992 user_ns = self.shell.user_ns
993 993 for i in self.magic_who_ls():
994 994 del(user_ns[i])
995 995
996 996 else: # Hard reset
997 997 self.shell.reset(new_session = False)
998 998
999 999
1000 1000
1001 1001 def magic_reset_selective(self, parameter_s=''):
1002 1002 """Resets the namespace by removing names defined by the user.
1003 1003
1004 1004 Input/Output history are left around in case you need them.
1005 1005
1006 1006 %reset_selective [-f] regex
1007 1007
1008 1008 No action is taken if regex is not included
1009 1009
1010 1010 Options
1011 1011 -f : force reset without asking for confirmation.
1012 1012
1013 1013 Examples
1014 1014 --------
1015 1015
1016 1016 We first fully reset the namespace so your output looks identical to
1017 1017 this example for pedagogical reasons; in practice you do not need a
1018 1018 full reset.
1019 1019
1020 1020 In [1]: %reset -f
1021 1021
1022 1022 Now, with a clean namespace we can make a few variables and use
1023 1023 %reset_selective to only delete names that match our regexp:
1024 1024
1025 1025 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1026 1026
1027 1027 In [3]: who_ls
1028 1028 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1029 1029
1030 1030 In [4]: %reset_selective -f b[2-3]m
1031 1031
1032 1032 In [5]: who_ls
1033 1033 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1034 1034
1035 1035 In [6]: %reset_selective -f d
1036 1036
1037 1037 In [7]: who_ls
1038 1038 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1039 1039
1040 1040 In [8]: %reset_selective -f c
1041 1041
1042 1042 In [9]: who_ls
1043 1043 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1044 1044
1045 1045 In [10]: %reset_selective -f b
1046 1046
1047 1047 In [11]: who_ls
1048 1048 Out[11]: ['a']
1049 1049 """
1050 1050
1051 1051 opts, regex = self.parse_options(parameter_s,'f')
1052 1052
1053 1053 if opts.has_key('f'):
1054 1054 ans = True
1055 1055 else:
1056 1056 ans = self.shell.ask_yes_no(
1057 1057 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1058 1058 if not ans:
1059 1059 print 'Nothing done.'
1060 1060 return
1061 1061 user_ns = self.shell.user_ns
1062 1062 if not regex:
1063 1063 print 'No regex pattern specified. Nothing done.'
1064 1064 return
1065 1065 else:
1066 1066 try:
1067 1067 m = re.compile(regex)
1068 1068 except TypeError:
1069 1069 raise TypeError('regex must be a string or compiled pattern')
1070 1070 for i in self.magic_who_ls():
1071 1071 if m.search(i):
1072 1072 del(user_ns[i])
1073 1073
1074 1074 def magic_xdel(self, parameter_s=''):
1075 1075 """Delete a variable, trying to clear it from anywhere that
1076 1076 IPython's machinery has references to it. By default, this uses
1077 1077 the identity of the named object in the user namespace to remove
1078 1078 references held under other names. The object is also removed
1079 1079 from the output history.
1080 1080
1081 1081 Options
1082 1082 -n : Delete the specified name from all namespaces, without
1083 1083 checking their identity.
1084 1084 """
1085 1085 opts, varname = self.parse_options(parameter_s,'n')
1086 1086 try:
1087 1087 self.shell.del_var(varname, ('n' in opts))
1088 1088 except (NameError, ValueError) as e:
1089 1089 print type(e).__name__ +": "+ str(e)
1090 1090
1091 1091 def magic_logstart(self,parameter_s=''):
1092 1092 """Start logging anywhere in a session.
1093 1093
1094 1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1095 1095
1096 1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 1097 current directory, in 'rotate' mode (see below).
1098 1098
1099 1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 1100 history up to that point and then continues logging.
1101 1101
1102 1102 %logstart takes a second optional parameter: logging mode. This can be one
1103 1103 of (note that the modes are given unquoted):\\
1104 1104 append: well, that says it.\\
1105 1105 backup: rename (if exists) to name~ and start name.\\
1106 1106 global: single logfile in your home dir, appended to.\\
1107 1107 over : overwrite existing log.\\
1108 1108 rotate: create rotating logs name.1~, name.2~, etc.
1109 1109
1110 1110 Options:
1111 1111
1112 1112 -o: log also IPython's output. In this mode, all commands which
1113 1113 generate an Out[NN] prompt are recorded to the logfile, right after
1114 1114 their corresponding input line. The output lines are always
1115 1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 1116 Python code.
1117 1117
1118 1118 Since this marker is always the same, filtering only the output from
1119 1119 a log is very easy, using for example a simple awk call:
1120 1120
1121 1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122 1122
1123 1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 1124 input, so that user lines are logged in their final form, converted
1125 1125 into valid Python. For example, %Exit is logged as
1126 1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 1127 exactly as typed, with no transformations applied.
1128 1128
1129 1129 -t: put timestamps before each input line logged (these are put in
1130 1130 comments)."""
1131 1131
1132 1132 opts,par = self.parse_options(parameter_s,'ort')
1133 1133 log_output = 'o' in opts
1134 1134 log_raw_input = 'r' in opts
1135 1135 timestamp = 't' in opts
1136 1136
1137 1137 logger = self.shell.logger
1138 1138
1139 1139 # if no args are given, the defaults set in the logger constructor by
1140 1140 # ipytohn remain valid
1141 1141 if par:
1142 1142 try:
1143 1143 logfname,logmode = par.split()
1144 1144 except:
1145 1145 logfname = par
1146 1146 logmode = 'backup'
1147 1147 else:
1148 1148 logfname = logger.logfname
1149 1149 logmode = logger.logmode
1150 1150 # put logfname into rc struct as if it had been called on the command
1151 1151 # line, so it ends up saved in the log header Save it in case we need
1152 1152 # to restore it...
1153 1153 old_logfile = self.shell.logfile
1154 1154 if logfname:
1155 1155 logfname = os.path.expanduser(logfname)
1156 1156 self.shell.logfile = logfname
1157 1157
1158 1158 loghead = '# IPython log file\n\n'
1159 1159 try:
1160 1160 started = logger.logstart(logfname,loghead,logmode,
1161 1161 log_output,timestamp,log_raw_input)
1162 1162 except:
1163 1163 self.shell.logfile = old_logfile
1164 1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 1165 else:
1166 1166 # log input history up to this point, optionally interleaving
1167 1167 # output if requested
1168 1168
1169 1169 if timestamp:
1170 1170 # disable timestamping for the previous history, since we've
1171 1171 # lost those already (no time machine here).
1172 1172 logger.timestamp = False
1173 1173
1174 1174 if log_raw_input:
1175 1175 input_hist = self.shell.history_manager.input_hist_raw
1176 1176 else:
1177 1177 input_hist = self.shell.history_manager.input_hist_parsed
1178 1178
1179 1179 if log_output:
1180 1180 log_write = logger.log_write
1181 1181 output_hist = self.shell.history_manager.output_hist
1182 1182 for n in range(1,len(input_hist)-1):
1183 1183 log_write(input_hist[n].rstrip() + '\n')
1184 1184 if n in output_hist:
1185 1185 log_write(repr(output_hist[n]),'output')
1186 1186 else:
1187 1187 logger.log_write('\n'.join(input_hist[1:]))
1188 1188 logger.log_write('\n')
1189 1189 if timestamp:
1190 1190 # re-enable timestamping
1191 1191 logger.timestamp = True
1192 1192
1193 1193 print ('Activating auto-logging. '
1194 1194 'Current session state plus future input saved.')
1195 1195 logger.logstate()
1196 1196
1197 1197 def magic_logstop(self,parameter_s=''):
1198 1198 """Fully stop logging and close log file.
1199 1199
1200 1200 In order to start logging again, a new %logstart call needs to be made,
1201 1201 possibly (though not necessarily) with a new filename, mode and other
1202 1202 options."""
1203 1203 self.logger.logstop()
1204 1204
1205 1205 def magic_logoff(self,parameter_s=''):
1206 1206 """Temporarily stop logging.
1207 1207
1208 1208 You must have previously started logging."""
1209 1209 self.shell.logger.switch_log(0)
1210 1210
1211 1211 def magic_logon(self,parameter_s=''):
1212 1212 """Restart logging.
1213 1213
1214 1214 This function is for restarting logging which you've temporarily
1215 1215 stopped with %logoff. For starting logging for the first time, you
1216 1216 must use the %logstart function, which allows you to specify an
1217 1217 optional log filename."""
1218 1218
1219 1219 self.shell.logger.switch_log(1)
1220 1220
1221 1221 def magic_logstate(self,parameter_s=''):
1222 1222 """Print the status of the logging system."""
1223 1223
1224 1224 self.shell.logger.logstate()
1225 1225
1226 1226 def magic_pdb(self, parameter_s=''):
1227 1227 """Control the automatic calling of the pdb interactive debugger.
1228 1228
1229 1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1230 1230 argument it works as a toggle.
1231 1231
1232 1232 When an exception is triggered, IPython can optionally call the
1233 1233 interactive pdb debugger after the traceback printout. %pdb toggles
1234 1234 this feature on and off.
1235 1235
1236 1236 The initial state of this feature is set in your configuration
1237 1237 file (the option is ``InteractiveShell.pdb``).
1238 1238
1239 1239 If you want to just activate the debugger AFTER an exception has fired,
1240 1240 without having to type '%pdb on' and rerunning your code, you can use
1241 1241 the %debug magic."""
1242 1242
1243 1243 par = parameter_s.strip().lower()
1244 1244
1245 1245 if par:
1246 1246 try:
1247 1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1248 1248 except KeyError:
1249 1249 print ('Incorrect argument. Use on/1, off/0, '
1250 1250 'or nothing for a toggle.')
1251 1251 return
1252 1252 else:
1253 1253 # toggle
1254 1254 new_pdb = not self.shell.call_pdb
1255 1255
1256 1256 # set on the shell
1257 1257 self.shell.call_pdb = new_pdb
1258 1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1259 1259
1260 1260 def magic_debug(self, parameter_s=''):
1261 1261 """Activate the interactive debugger in post-mortem mode.
1262 1262
1263 1263 If an exception has just occurred, this lets you inspect its stack
1264 1264 frames interactively. Note that this will always work only on the last
1265 1265 traceback that occurred, so you must call this quickly after an
1266 1266 exception that you wish to inspect has fired, because if another one
1267 1267 occurs, it clobbers the previous one.
1268 1268
1269 1269 If you want IPython to automatically do this on every exception, see
1270 1270 the %pdb magic for more details.
1271 1271 """
1272 1272 self.shell.debugger(force=True)
1273 1273
1274 1274 @skip_doctest
1275 1275 def magic_prun(self, parameter_s ='',user_mode=1,
1276 1276 opts=None,arg_lst=None,prog_ns=None):
1277 1277
1278 1278 """Run a statement through the python code profiler.
1279 1279
1280 1280 Usage:
1281 1281 %prun [options] statement
1282 1282
1283 1283 The given statement (which doesn't require quote marks) is run via the
1284 1284 python profiler in a manner similar to the profile.run() function.
1285 1285 Namespaces are internally managed to work correctly; profile.run
1286 1286 cannot be used in IPython because it makes certain assumptions about
1287 1287 namespaces which do not hold under IPython.
1288 1288
1289 1289 Options:
1290 1290
1291 1291 -l <limit>: you can place restrictions on what or how much of the
1292 1292 profile gets printed. The limit value can be:
1293 1293
1294 1294 * A string: only information for function names containing this string
1295 1295 is printed.
1296 1296
1297 1297 * An integer: only these many lines are printed.
1298 1298
1299 1299 * A float (between 0 and 1): this fraction of the report is printed
1300 1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1301 1301
1302 1302 You can combine several limits with repeated use of the option. For
1303 1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1304 1304 information about class constructors.
1305 1305
1306 1306 -r: return the pstats.Stats object generated by the profiling. This
1307 1307 object has all the information about the profile in it, and you can
1308 1308 later use it for further analysis or in other functions.
1309 1309
1310 1310 -s <key>: sort profile by given key. You can provide more than one key
1311 1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1312 1312 default sorting key is 'time'.
1313 1313
1314 1314 The following is copied verbatim from the profile documentation
1315 1315 referenced below:
1316 1316
1317 1317 When more than one key is provided, additional keys are used as
1318 1318 secondary criteria when the there is equality in all keys selected
1319 1319 before them.
1320 1320
1321 1321 Abbreviations can be used for any key names, as long as the
1322 1322 abbreviation is unambiguous. The following are the keys currently
1323 1323 defined:
1324 1324
1325 1325 Valid Arg Meaning
1326 1326 "calls" call count
1327 1327 "cumulative" cumulative time
1328 1328 "file" file name
1329 1329 "module" file name
1330 1330 "pcalls" primitive call count
1331 1331 "line" line number
1332 1332 "name" function name
1333 1333 "nfl" name/file/line
1334 1334 "stdname" standard name
1335 1335 "time" internal time
1336 1336
1337 1337 Note that all sorts on statistics are in descending order (placing
1338 1338 most time consuming items first), where as name, file, and line number
1339 1339 searches are in ascending order (i.e., alphabetical). The subtle
1340 1340 distinction between "nfl" and "stdname" is that the standard name is a
1341 1341 sort of the name as printed, which means that the embedded line
1342 1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1343 1343 would (if the file names were the same) appear in the string order
1344 1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1345 1345 line numbers. In fact, sort_stats("nfl") is the same as
1346 1346 sort_stats("name", "file", "line").
1347 1347
1348 1348 -T <filename>: save profile results as shown on screen to a text
1349 1349 file. The profile is still shown on screen.
1350 1350
1351 1351 -D <filename>: save (via dump_stats) profile statistics to given
1352 1352 filename. This data is in a format understod by the pstats module, and
1353 1353 is generated by a call to the dump_stats() method of profile
1354 1354 objects. The profile is still shown on screen.
1355 1355
1356 1356 If you want to run complete programs under the profiler's control, use
1357 1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1358 1358 contains profiler specific options as described here.
1359 1359
1360 1360 You can read the complete documentation for the profile module with::
1361 1361
1362 1362 In [1]: import profile; profile.help()
1363 1363 """
1364 1364
1365 1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1366 1366 # protect user quote marks
1367 1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1368 1368
1369 1369 if user_mode: # regular user call
1370 1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1371 1371 list_all=1)
1372 1372 namespace = self.shell.user_ns
1373 1373 else: # called to run a program by %run -p
1374 1374 try:
1375 1375 filename = get_py_filename(arg_lst[0])
1376 1376 except IOError as e:
1377 1377 try:
1378 1378 msg = str(e)
1379 1379 except UnicodeError:
1380 1380 msg = e.message
1381 1381 error(msg)
1382 1382 return
1383 1383
1384 1384 arg_str = 'execfile(filename,prog_ns)'
1385 1385 namespace = locals()
1386 1386
1387 1387 opts.merge(opts_def)
1388 1388
1389 1389 prof = profile.Profile()
1390 1390 try:
1391 1391 prof = prof.runctx(arg_str,namespace,namespace)
1392 1392 sys_exit = ''
1393 1393 except SystemExit:
1394 1394 sys_exit = """*** SystemExit exception caught in code being profiled."""
1395 1395
1396 1396 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1397 1397
1398 1398 lims = opts.l
1399 1399 if lims:
1400 1400 lims = [] # rebuild lims with ints/floats/strings
1401 1401 for lim in opts.l:
1402 1402 try:
1403 1403 lims.append(int(lim))
1404 1404 except ValueError:
1405 1405 try:
1406 1406 lims.append(float(lim))
1407 1407 except ValueError:
1408 1408 lims.append(lim)
1409 1409
1410 1410 # Trap output.
1411 1411 stdout_trap = StringIO()
1412 1412
1413 1413 if hasattr(stats,'stream'):
1414 1414 # In newer versions of python, the stats object has a 'stream'
1415 1415 # attribute to write into.
1416 1416 stats.stream = stdout_trap
1417 1417 stats.print_stats(*lims)
1418 1418 else:
1419 1419 # For older versions, we manually redirect stdout during printing
1420 1420 sys_stdout = sys.stdout
1421 1421 try:
1422 1422 sys.stdout = stdout_trap
1423 1423 stats.print_stats(*lims)
1424 1424 finally:
1425 1425 sys.stdout = sys_stdout
1426 1426
1427 1427 output = stdout_trap.getvalue()
1428 1428 output = output.rstrip()
1429 1429
1430 1430 page.page(output)
1431 1431 print sys_exit,
1432 1432
1433 1433 dump_file = opts.D[0]
1434 1434 text_file = opts.T[0]
1435 1435 if dump_file:
1436 1436 dump_file = unquote_filename(dump_file)
1437 1437 prof.dump_stats(dump_file)
1438 1438 print '\n*** Profile stats marshalled to file',\
1439 1439 `dump_file`+'.',sys_exit
1440 1440 if text_file:
1441 1441 text_file = unquote_filename(text_file)
1442 1442 pfile = file(text_file,'w')
1443 1443 pfile.write(output)
1444 1444 pfile.close()
1445 1445 print '\n*** Profile printout saved to text file',\
1446 1446 `text_file`+'.',sys_exit
1447 1447
1448 1448 if opts.has_key('r'):
1449 1449 return stats
1450 1450 else:
1451 1451 return None
1452 1452
1453 1453 @skip_doctest
1454 1454 def magic_run(self, parameter_s ='', runner=None,
1455 1455 file_finder=get_py_filename):
1456 1456 """Run the named file inside IPython as a program.
1457 1457
1458 1458 Usage:\\
1459 1459 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1460 1460
1461 1461 Parameters after the filename are passed as command-line arguments to
1462 1462 the program (put in sys.argv). Then, control returns to IPython's
1463 1463 prompt.
1464 1464
1465 1465 This is similar to running at a system prompt:\\
1466 1466 $ python file args\\
1467 1467 but with the advantage of giving you IPython's tracebacks, and of
1468 1468 loading all variables into your interactive namespace for further use
1469 1469 (unless -p is used, see below).
1470 1470
1471 1471 The file is executed in a namespace initially consisting only of
1472 1472 __name__=='__main__' and sys.argv constructed as indicated. It thus
1473 1473 sees its environment as if it were being run as a stand-alone program
1474 1474 (except for sharing global objects such as previously imported
1475 1475 modules). But after execution, the IPython interactive namespace gets
1476 1476 updated with all variables defined in the program (except for __name__
1477 1477 and sys.argv). This allows for very convenient loading of code for
1478 1478 interactive work, while giving each program a 'clean sheet' to run in.
1479 1479
1480 1480 Options:
1481 1481
1482 1482 -n: __name__ is NOT set to '__main__', but to the running file's name
1483 1483 without extension (as python does under import). This allows running
1484 1484 scripts and reloading the definitions in them without calling code
1485 1485 protected by an ' if __name__ == "__main__" ' clause.
1486 1486
1487 1487 -i: run the file in IPython's namespace instead of an empty one. This
1488 1488 is useful if you are experimenting with code written in a text editor
1489 1489 which depends on variables defined interactively.
1490 1490
1491 1491 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1492 1492 being run. This is particularly useful if IPython is being used to
1493 1493 run unittests, which always exit with a sys.exit() call. In such
1494 1494 cases you are interested in the output of the test results, not in
1495 1495 seeing a traceback of the unittest module.
1496 1496
1497 1497 -t: print timing information at the end of the run. IPython will give
1498 1498 you an estimated CPU time consumption for your script, which under
1499 1499 Unix uses the resource module to avoid the wraparound problems of
1500 1500 time.clock(). Under Unix, an estimate of time spent on system tasks
1501 1501 is also given (for Windows platforms this is reported as 0.0).
1502 1502
1503 1503 If -t is given, an additional -N<N> option can be given, where <N>
1504 1504 must be an integer indicating how many times you want the script to
1505 1505 run. The final timing report will include total and per run results.
1506 1506
1507 1507 For example (testing the script uniq_stable.py):
1508 1508
1509 1509 In [1]: run -t uniq_stable
1510 1510
1511 1511 IPython CPU timings (estimated):\\
1512 1512 User : 0.19597 s.\\
1513 1513 System: 0.0 s.\\
1514 1514
1515 1515 In [2]: run -t -N5 uniq_stable
1516 1516
1517 1517 IPython CPU timings (estimated):\\
1518 1518 Total runs performed: 5\\
1519 1519 Times : Total Per run\\
1520 1520 User : 0.910862 s, 0.1821724 s.\\
1521 1521 System: 0.0 s, 0.0 s.
1522 1522
1523 1523 -d: run your program under the control of pdb, the Python debugger.
1524 1524 This allows you to execute your program step by step, watch variables,
1525 1525 etc. Internally, what IPython does is similar to calling:
1526 1526
1527 1527 pdb.run('execfile("YOURFILENAME")')
1528 1528
1529 1529 with a breakpoint set on line 1 of your file. You can change the line
1530 1530 number for this automatic breakpoint to be <N> by using the -bN option
1531 1531 (where N must be an integer). For example:
1532 1532
1533 1533 %run -d -b40 myscript
1534 1534
1535 1535 will set the first breakpoint at line 40 in myscript.py. Note that
1536 1536 the first breakpoint must be set on a line which actually does
1537 1537 something (not a comment or docstring) for it to stop execution.
1538 1538
1539 1539 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1540 1540 first enter 'c' (without qoutes) to start execution up to the first
1541 1541 breakpoint.
1542 1542
1543 1543 Entering 'help' gives information about the use of the debugger. You
1544 1544 can easily see pdb's full documentation with "import pdb;pdb.help()"
1545 1545 at a prompt.
1546 1546
1547 1547 -p: run program under the control of the Python profiler module (which
1548 1548 prints a detailed report of execution times, function calls, etc).
1549 1549
1550 1550 You can pass other options after -p which affect the behavior of the
1551 1551 profiler itself. See the docs for %prun for details.
1552 1552
1553 1553 In this mode, the program's variables do NOT propagate back to the
1554 1554 IPython interactive namespace (because they remain in the namespace
1555 1555 where the profiler executes them).
1556 1556
1557 1557 Internally this triggers a call to %prun, see its documentation for
1558 1558 details on the options available specifically for profiling.
1559 1559
1560 1560 There is one special usage for which the text above doesn't apply:
1561 1561 if the filename ends with .ipy, the file is run as ipython script,
1562 1562 just as if the commands were written on IPython prompt.
1563 1563
1564 1564 -m: specify module name to load instead of script path. Similar to
1565 1565 the -m option for the python interpreter. Use this option last if you
1566 1566 want to combine with other %run options. Unlike the python interpreter
1567 1567 only source modules are allowed no .pyc or .pyo files.
1568 1568 For example:
1569 1569
1570 1570 %run -m example
1571 1571
1572 1572 will run the example module.
1573 1573
1574 1574 """
1575 1575
1576 1576 # get arguments and set sys.argv for program to be run.
1577 1577 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
1578 1578 mode='list', list_all=1)
1579 1579 if "m" in opts:
1580 1580 modulename = opts["m"][0]
1581 1581 modpath = find_mod(modulename)
1582 1582 if modpath is None:
1583 1583 warn('%r is not a valid modulename on sys.path'%modulename)
1584 1584 return
1585 1585 arg_lst = [modpath] + arg_lst
1586 1586 try:
1587 1587 filename = file_finder(arg_lst[0])
1588 1588 except IndexError:
1589 1589 warn('you must provide at least a filename.')
1590 1590 print '\n%run:\n', oinspect.getdoc(self.magic_run)
1591 1591 return
1592 1592 except IOError as e:
1593 1593 try:
1594 1594 msg = str(e)
1595 1595 except UnicodeError:
1596 1596 msg = e.message
1597 1597 error(msg)
1598 1598 return
1599 1599
1600 1600 if filename.lower().endswith('.ipy'):
1601 1601 self.shell.safe_execfile_ipy(filename)
1602 1602 return
1603 1603
1604 1604 # Control the response to exit() calls made by the script being run
1605 1605 exit_ignore = 'e' in opts
1606 1606
1607 1607 # Make sure that the running script gets a proper sys.argv as if it
1608 1608 # were run from a system shell.
1609 1609 save_argv = sys.argv # save it for later restoring
1610 1610
1611 1611 # simulate shell expansion on arguments, at least tilde expansion
1612 1612 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1613 1613
1614 1614 sys.argv = [filename] + args # put in the proper filename
1615 1615 # protect sys.argv from potential unicode strings on Python 2:
1616 1616 if not py3compat.PY3:
1617 1617 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
1618 1618
1619 1619 if 'i' in opts:
1620 1620 # Run in user's interactive namespace
1621 1621 prog_ns = self.shell.user_ns
1622 1622 __name__save = self.shell.user_ns['__name__']
1623 1623 prog_ns['__name__'] = '__main__'
1624 1624 main_mod = self.shell.new_main_mod(prog_ns)
1625 1625 else:
1626 1626 # Run in a fresh, empty namespace
1627 1627 if 'n' in opts:
1628 1628 name = os.path.splitext(os.path.basename(filename))[0]
1629 1629 else:
1630 1630 name = '__main__'
1631 1631
1632 1632 main_mod = self.shell.new_main_mod()
1633 1633 prog_ns = main_mod.__dict__
1634 1634 prog_ns['__name__'] = name
1635 1635
1636 1636 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1637 1637 # set the __file__ global in the script's namespace
1638 1638 prog_ns['__file__'] = filename
1639 1639
1640 1640 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1641 1641 # that, if we overwrite __main__, we replace it at the end
1642 1642 main_mod_name = prog_ns['__name__']
1643 1643
1644 1644 if main_mod_name == '__main__':
1645 1645 restore_main = sys.modules['__main__']
1646 1646 else:
1647 1647 restore_main = False
1648 1648
1649 1649 # This needs to be undone at the end to prevent holding references to
1650 1650 # every single object ever created.
1651 1651 sys.modules[main_mod_name] = main_mod
1652 1652
1653 1653 try:
1654 1654 stats = None
1655 1655 with self.readline_no_record:
1656 1656 if 'p' in opts:
1657 1657 stats = self.magic_prun('', 0, opts, arg_lst, prog_ns)
1658 1658 else:
1659 1659 if 'd' in opts:
1660 1660 deb = debugger.Pdb(self.shell.colors)
1661 1661 # reset Breakpoint state, which is moronically kept
1662 1662 # in a class
1663 1663 bdb.Breakpoint.next = 1
1664 1664 bdb.Breakpoint.bplist = {}
1665 1665 bdb.Breakpoint.bpbynumber = [None]
1666 1666 # Set an initial breakpoint to stop execution
1667 1667 maxtries = 10
1668 1668 bp = int(opts.get('b', [1])[0])
1669 1669 checkline = deb.checkline(filename, bp)
1670 1670 if not checkline:
1671 1671 for bp in range(bp + 1, bp + maxtries + 1):
1672 1672 if deb.checkline(filename, bp):
1673 1673 break
1674 1674 else:
1675 1675 msg = ("\nI failed to find a valid line to set "
1676 1676 "a breakpoint\n"
1677 1677 "after trying up to line: %s.\n"
1678 1678 "Please set a valid breakpoint manually "
1679 1679 "with the -b option." % bp)
1680 1680 error(msg)
1681 1681 return
1682 1682 # if we find a good linenumber, set the breakpoint
1683 1683 deb.do_break('%s:%s' % (filename, bp))
1684 1684 # Start file run
1685 1685 print "NOTE: Enter 'c' at the",
1686 1686 print "%s prompt to start your script." % deb.prompt
1687 1687 try:
1688 1688 deb.run('execfile("%s")' % filename, prog_ns)
1689 1689
1690 1690 except:
1691 1691 etype, value, tb = sys.exc_info()
1692 1692 # Skip three frames in the traceback: the %run one,
1693 1693 # one inside bdb.py, and the command-line typed by the
1694 1694 # user (run by exec in pdb itself).
1695 1695 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
1696 1696 else:
1697 1697 if runner is None:
1698 1698 runner = self.shell.safe_execfile
1699 1699 if 't' in opts:
1700 1700 # timed execution
1701 1701 try:
1702 1702 nruns = int(opts['N'][0])
1703 1703 if nruns < 1:
1704 1704 error('Number of runs must be >=1')
1705 1705 return
1706 1706 except (KeyError):
1707 1707 nruns = 1
1708 1708 twall0 = time.time()
1709 1709 if nruns == 1:
1710 1710 t0 = clock2()
1711 1711 runner(filename, prog_ns, prog_ns,
1712 1712 exit_ignore=exit_ignore)
1713 1713 t1 = clock2()
1714 1714 t_usr = t1[0] - t0[0]
1715 1715 t_sys = t1[1] - t0[1]
1716 1716 print "\nIPython CPU timings (estimated):"
1717 1717 print " User : %10.2f s." % t_usr
1718 1718 print " System : %10.2f s." % t_sys
1719 1719 else:
1720 1720 runs = range(nruns)
1721 1721 t0 = clock2()
1722 1722 for nr in runs:
1723 1723 runner(filename, prog_ns, prog_ns,
1724 1724 exit_ignore=exit_ignore)
1725 1725 t1 = clock2()
1726 1726 t_usr = t1[0] - t0[0]
1727 1727 t_sys = t1[1] - t0[1]
1728 1728 print "\nIPython CPU timings (estimated):"
1729 1729 print "Total runs performed:", nruns
1730 1730 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
1731 1731 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
1732 1732 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
1733 1733 twall1 = time.time()
1734 1734 print "Wall time: %10.2f s." % (twall1 - twall0)
1735 1735
1736 1736 else:
1737 1737 # regular execution
1738 1738 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
1739 1739
1740 1740 if 'i' in opts:
1741 1741 self.shell.user_ns['__name__'] = __name__save
1742 1742 else:
1743 1743 # The shell MUST hold a reference to prog_ns so after %run
1744 1744 # exits, the python deletion mechanism doesn't zero it out
1745 1745 # (leaving dangling references).
1746 1746 self.shell.cache_main_mod(prog_ns, filename)
1747 1747 # update IPython interactive namespace
1748 1748
1749 1749 # Some forms of read errors on the file may mean the
1750 1750 # __name__ key was never set; using pop we don't have to
1751 1751 # worry about a possible KeyError.
1752 1752 prog_ns.pop('__name__', None)
1753 1753
1754 1754 self.shell.user_ns.update(prog_ns)
1755 1755 finally:
1756 1756 # It's a bit of a mystery why, but __builtins__ can change from
1757 1757 # being a module to becoming a dict missing some key data after
1758 1758 # %run. As best I can see, this is NOT something IPython is doing
1759 1759 # at all, and similar problems have been reported before:
1760 1760 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1761 1761 # Since this seems to be done by the interpreter itself, the best
1762 1762 # we can do is to at least restore __builtins__ for the user on
1763 1763 # exit.
1764 1764 self.shell.user_ns['__builtins__'] = builtin_mod
1765 1765
1766 1766 # Ensure key global structures are restored
1767 1767 sys.argv = save_argv
1768 1768 if restore_main:
1769 1769 sys.modules['__main__'] = restore_main
1770 1770 else:
1771 1771 # Remove from sys.modules the reference to main_mod we'd
1772 1772 # added. Otherwise it will trap references to objects
1773 1773 # contained therein.
1774 1774 del sys.modules[main_mod_name]
1775 1775
1776 1776 return stats
1777 1777
1778 1778 @skip_doctest
1779 1779 def magic_timeit(self, parameter_s =''):
1780 1780 """Time execution of a Python statement or expression
1781 1781
1782 1782 Usage:\\
1783 1783 %timeit [-n<N> -r<R> [-t|-c]] statement
1784 1784
1785 1785 Time execution of a Python statement or expression using the timeit
1786 1786 module.
1787 1787
1788 1788 Options:
1789 1789 -n<N>: execute the given statement <N> times in a loop. If this value
1790 1790 is not given, a fitting value is chosen.
1791 1791
1792 1792 -r<R>: repeat the loop iteration <R> times and take the best result.
1793 1793 Default: 3
1794 1794
1795 1795 -t: use time.time to measure the time, which is the default on Unix.
1796 1796 This function measures wall time.
1797 1797
1798 1798 -c: use time.clock to measure the time, which is the default on
1799 1799 Windows and measures wall time. On Unix, resource.getrusage is used
1800 1800 instead and returns the CPU user time.
1801 1801
1802 1802 -p<P>: use a precision of <P> digits to display the timing result.
1803 1803 Default: 3
1804 1804
1805 1805
1806 1806 Examples:
1807 1807
1808 1808 In [1]: %timeit pass
1809 1809 10000000 loops, best of 3: 53.3 ns per loop
1810 1810
1811 1811 In [2]: u = None
1812 1812
1813 1813 In [3]: %timeit u is None
1814 1814 10000000 loops, best of 3: 184 ns per loop
1815 1815
1816 1816 In [4]: %timeit -r 4 u == None
1817 1817 1000000 loops, best of 4: 242 ns per loop
1818 1818
1819 1819 In [5]: import time
1820 1820
1821 1821 In [6]: %timeit -n1 time.sleep(2)
1822 1822 1 loops, best of 3: 2 s per loop
1823 1823
1824 1824
1825 1825 The times reported by %timeit will be slightly higher than those
1826 1826 reported by the timeit.py script when variables are accessed. This is
1827 1827 due to the fact that %timeit executes the statement in the namespace
1828 1828 of the shell, compared with timeit.py, which uses a single setup
1829 1829 statement to import function or create variables. Generally, the bias
1830 1830 does not matter as long as results from timeit.py are not mixed with
1831 1831 those from %timeit."""
1832 1832
1833 1833 import timeit
1834 1834 import math
1835 1835
1836 1836 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1837 1837 # certain terminals. Until we figure out a robust way of
1838 1838 # auto-detecting if the terminal can deal with it, use plain 'us' for
1839 1839 # microseconds. I am really NOT happy about disabling the proper
1840 1840 # 'micro' prefix, but crashing is worse... If anyone knows what the
1841 1841 # right solution for this is, I'm all ears...
1842 1842 #
1843 1843 # Note: using
1844 1844 #
1845 1845 # s = u'\xb5'
1846 1846 # s.encode(sys.getdefaultencoding())
1847 1847 #
1848 1848 # is not sufficient, as I've seen terminals where that fails but
1849 1849 # print s
1850 1850 #
1851 1851 # succeeds
1852 1852 #
1853 1853 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1854 1854
1855 1855 #units = [u"s", u"ms",u'\xb5',"ns"]
1856 1856 units = [u"s", u"ms",u'us',"ns"]
1857 1857
1858 1858 scaling = [1, 1e3, 1e6, 1e9]
1859 1859
1860 1860 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1861 1861 posix=False)
1862 1862 if stmt == "":
1863 1863 return
1864 1864 timefunc = timeit.default_timer
1865 1865 number = int(getattr(opts, "n", 0))
1866 1866 repeat = int(getattr(opts, "r", timeit.default_repeat))
1867 1867 precision = int(getattr(opts, "p", 3))
1868 1868 if hasattr(opts, "t"):
1869 1869 timefunc = time.time
1870 1870 if hasattr(opts, "c"):
1871 1871 timefunc = clock
1872 1872
1873 1873 timer = timeit.Timer(timer=timefunc)
1874 1874 # this code has tight coupling to the inner workings of timeit.Timer,
1875 1875 # but is there a better way to achieve that the code stmt has access
1876 1876 # to the shell namespace?
1877 1877
1878 1878 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1879 1879 'setup': "pass"}
1880 1880 # Track compilation time so it can be reported if too long
1881 1881 # Minimum time above which compilation time will be reported
1882 1882 tc_min = 0.1
1883 1883
1884 1884 t0 = clock()
1885 1885 code = compile(src, "<magic-timeit>", "exec")
1886 1886 tc = clock()-t0
1887 1887
1888 1888 ns = {}
1889 1889 exec code in self.shell.user_ns, ns
1890 1890 timer.inner = ns["inner"]
1891 1891
1892 1892 if number == 0:
1893 1893 # determine number so that 0.2 <= total time < 2.0
1894 1894 number = 1
1895 1895 for i in range(1, 10):
1896 1896 if timer.timeit(number) >= 0.2:
1897 1897 break
1898 1898 number *= 10
1899 1899
1900 1900 best = min(timer.repeat(repeat, number)) / number
1901 1901
1902 1902 if best > 0.0 and best < 1000.0:
1903 1903 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1904 1904 elif best >= 1000.0:
1905 1905 order = 0
1906 1906 else:
1907 1907 order = 3
1908 1908 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1909 1909 precision,
1910 1910 best * scaling[order],
1911 1911 units[order])
1912 1912 if tc > tc_min:
1913 1913 print "Compiler time: %.2f s" % tc
1914 1914
1915 1915 @skip_doctest
1916 1916 @needs_local_scope
1917 1917 def magic_time(self,parameter_s = ''):
1918 1918 """Time execution of a Python statement or expression.
1919 1919
1920 1920 The CPU and wall clock times are printed, and the value of the
1921 1921 expression (if any) is returned. Note that under Win32, system time
1922 1922 is always reported as 0, since it can not be measured.
1923 1923
1924 1924 This function provides very basic timing functionality. In Python
1925 1925 2.3, the timeit module offers more control and sophistication, so this
1926 1926 could be rewritten to use it (patches welcome).
1927 1927
1928 1928 Some examples:
1929 1929
1930 1930 In [1]: time 2**128
1931 1931 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1932 1932 Wall time: 0.00
1933 1933 Out[1]: 340282366920938463463374607431768211456L
1934 1934
1935 1935 In [2]: n = 1000000
1936 1936
1937 1937 In [3]: time sum(range(n))
1938 1938 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1939 1939 Wall time: 1.37
1940 1940 Out[3]: 499999500000L
1941 1941
1942 1942 In [4]: time print 'hello world'
1943 1943 hello world
1944 1944 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1945 1945 Wall time: 0.00
1946 1946
1947 1947 Note that the time needed by Python to compile the given expression
1948 1948 will be reported if it is more than 0.1s. In this example, the
1949 1949 actual exponentiation is done by Python at compilation time, so while
1950 1950 the expression can take a noticeable amount of time to compute, that
1951 1951 time is purely due to the compilation:
1952 1952
1953 1953 In [5]: time 3**9999;
1954 1954 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1955 1955 Wall time: 0.00 s
1956 1956
1957 1957 In [6]: time 3**999999;
1958 1958 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1959 1959 Wall time: 0.00 s
1960 1960 Compiler : 0.78 s
1961 1961 """
1962 1962
1963 1963 # fail immediately if the given expression can't be compiled
1964 1964
1965 1965 expr = self.shell.prefilter(parameter_s,False)
1966 1966
1967 1967 # Minimum time above which compilation time will be reported
1968 1968 tc_min = 0.1
1969 1969
1970 1970 try:
1971 1971 mode = 'eval'
1972 1972 t0 = clock()
1973 1973 code = compile(expr,'<timed eval>',mode)
1974 1974 tc = clock()-t0
1975 1975 except SyntaxError:
1976 1976 mode = 'exec'
1977 1977 t0 = clock()
1978 1978 code = compile(expr,'<timed exec>',mode)
1979 1979 tc = clock()-t0
1980 1980 # skew measurement as little as possible
1981 1981 glob = self.shell.user_ns
1982 1982 locs = self._magic_locals
1983 1983 clk = clock2
1984 1984 wtime = time.time
1985 1985 # time execution
1986 1986 wall_st = wtime()
1987 1987 if mode=='eval':
1988 1988 st = clk()
1989 1989 out = eval(code, glob, locs)
1990 1990 end = clk()
1991 1991 else:
1992 1992 st = clk()
1993 1993 exec code in glob, locs
1994 1994 end = clk()
1995 1995 out = None
1996 1996 wall_end = wtime()
1997 1997 # Compute actual times and report
1998 1998 wall_time = wall_end-wall_st
1999 1999 cpu_user = end[0]-st[0]
2000 2000 cpu_sys = end[1]-st[1]
2001 2001 cpu_tot = cpu_user+cpu_sys
2002 2002 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2003 2003 (cpu_user,cpu_sys,cpu_tot)
2004 2004 print "Wall time: %.2f s" % wall_time
2005 2005 if tc > tc_min:
2006 2006 print "Compiler : %.2f s" % tc
2007 2007 return out
2008 2008
2009 2009 @skip_doctest
2010 2010 def magic_macro(self,parameter_s = ''):
2011 2011 """Define a macro for future re-execution. It accepts ranges of history,
2012 2012 filenames or string objects.
2013 2013
2014 2014 Usage:\\
2015 2015 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2016 2016
2017 2017 Options:
2018 2018
2019 2019 -r: use 'raw' input. By default, the 'processed' history is used,
2020 2020 so that magics are loaded in their transformed version to valid
2021 2021 Python. If this option is given, the raw input as typed as the
2022 2022 command line is used instead.
2023 2023
2024 2024 This will define a global variable called `name` which is a string
2025 2025 made of joining the slices and lines you specify (n1,n2,... numbers
2026 2026 above) from your input history into a single string. This variable
2027 2027 acts like an automatic function which re-executes those lines as if
2028 2028 you had typed them. You just type 'name' at the prompt and the code
2029 2029 executes.
2030 2030
2031 2031 The syntax for indicating input ranges is described in %history.
2032 2032
2033 2033 Note: as a 'hidden' feature, you can also use traditional python slice
2034 2034 notation, where N:M means numbers N through M-1.
2035 2035
2036 2036 For example, if your history contains (%hist prints it):
2037 2037
2038 2038 44: x=1
2039 2039 45: y=3
2040 2040 46: z=x+y
2041 2041 47: print x
2042 2042 48: a=5
2043 2043 49: print 'x',x,'y',y
2044 2044
2045 2045 you can create a macro with lines 44 through 47 (included) and line 49
2046 2046 called my_macro with:
2047 2047
2048 2048 In [55]: %macro my_macro 44-47 49
2049 2049
2050 2050 Now, typing `my_macro` (without quotes) will re-execute all this code
2051 2051 in one pass.
2052 2052
2053 2053 You don't need to give the line-numbers in order, and any given line
2054 2054 number can appear multiple times. You can assemble macros with any
2055 2055 lines from your input history in any order.
2056 2056
2057 2057 The macro is a simple object which holds its value in an attribute,
2058 2058 but IPython's display system checks for macros and executes them as
2059 2059 code instead of printing them when you type their name.
2060 2060
2061 2061 You can view a macro's contents by explicitly printing it with:
2062 2062
2063 2063 'print macro_name'.
2064 2064
2065 2065 """
2066 2066 opts,args = self.parse_options(parameter_s,'r',mode='list')
2067 2067 if not args: # List existing macros
2068 2068 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2069 2069 isinstance(v, Macro))
2070 2070 if len(args) == 1:
2071 2071 raise UsageError(
2072 2072 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2073 2073 name, codefrom = args[0], " ".join(args[1:])
2074 2074
2075 2075 #print 'rng',ranges # dbg
2076 2076 try:
2077 2077 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2078 2078 except (ValueError, TypeError) as e:
2079 2079 print e.args[0]
2080 2080 return
2081 2081 macro = Macro(lines)
2082 2082 self.shell.define_macro(name, macro)
2083 2083 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2084 2084 print '=== Macro contents: ==='
2085 2085 print macro,
2086 2086
2087 2087 def magic_save(self,parameter_s = ''):
2088 2088 """Save a set of lines or a macro to a given filename.
2089 2089
2090 2090 Usage:\\
2091 2091 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2092 2092
2093 2093 Options:
2094 2094
2095 2095 -r: use 'raw' input. By default, the 'processed' history is used,
2096 2096 so that magics are loaded in their transformed version to valid
2097 2097 Python. If this option is given, the raw input as typed as the
2098 2098 command line is used instead.
2099 2099
2100 2100 This function uses the same syntax as %history for input ranges,
2101 2101 then saves the lines to the filename you specify.
2102 2102
2103 2103 It adds a '.py' extension to the file if you don't do so yourself, and
2104 2104 it asks for confirmation before overwriting existing files."""
2105 2105
2106 2106 opts,args = self.parse_options(parameter_s,'r',mode='list')
2107 2107 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
2108 2108 if not fname.endswith('.py'):
2109 2109 fname += '.py'
2110 2110 if os.path.isfile(fname):
2111 2111 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2112 2112 if ans.lower() not in ['y','yes']:
2113 2113 print 'Operation cancelled.'
2114 2114 return
2115 2115 try:
2116 2116 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2117 2117 except (TypeError, ValueError) as e:
2118 2118 print e.args[0]
2119 2119 return
2120 2120 with py3compat.open(fname,'w', encoding="utf-8") as f:
2121 2121 f.write(u"# coding: utf-8\n")
2122 2122 f.write(py3compat.cast_unicode(cmds))
2123 2123 print 'The following commands were written to file `%s`:' % fname
2124 2124 print cmds
2125 2125
2126 2126 def magic_pastebin(self, parameter_s = ''):
2127 2127 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2128 2128 try:
2129 2129 code = self.shell.find_user_code(parameter_s)
2130 2130 except (ValueError, TypeError) as e:
2131 2131 print e.args[0]
2132 2132 return
2133 2133 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2134 2134 id = pbserver.pastes.newPaste("python", code)
2135 2135 return "http://paste.pocoo.org/show/" + id
2136 2136
2137 2137 def magic_loadpy(self, arg_s):
2138 2138 """Load a .py python script into the GUI console.
2139 2139
2140 2140 This magic command can either take a local filename or a url::
2141 2141
2142 2142 %loadpy myscript.py
2143 2143 %loadpy http://www.example.com/myscript.py
2144 2144 """
2145 2145 arg_s = unquote_filename(arg_s)
2146 2146 if not arg_s.endswith('.py'):
2147 2147 raise ValueError('%%load only works with .py files: %s' % arg_s)
2148 2148 if arg_s.startswith('http'):
2149 2149 import urllib2
2150 2150 response = urllib2.urlopen(arg_s)
2151 2151 content = response.read()
2152 2152 else:
2153 2153 with open(arg_s) as f:
2154 2154 content = f.read()
2155 2155 self.set_next_input(content)
2156 2156
2157 2157 def _find_edit_target(self, args, opts, last_call):
2158 2158 """Utility method used by magic_edit to find what to edit."""
2159 2159
2160 2160 def make_filename(arg):
2161 2161 "Make a filename from the given args"
2162 2162 arg = unquote_filename(arg)
2163 2163 try:
2164 2164 filename = get_py_filename(arg)
2165 2165 except IOError:
2166 2166 # If it ends with .py but doesn't already exist, assume we want
2167 2167 # a new file.
2168 2168 if arg.endswith('.py'):
2169 2169 filename = arg
2170 2170 else:
2171 2171 filename = None
2172 2172 return filename
2173 2173
2174 2174 # Set a few locals from the options for convenience:
2175 2175 opts_prev = 'p' in opts
2176 2176 opts_raw = 'r' in opts
2177 2177
2178 2178 # custom exceptions
2179 2179 class DataIsObject(Exception): pass
2180 2180
2181 2181 # Default line number value
2182 2182 lineno = opts.get('n',None)
2183 2183
2184 2184 if opts_prev:
2185 2185 args = '_%s' % last_call[0]
2186 2186 if not self.shell.user_ns.has_key(args):
2187 2187 args = last_call[1]
2188 2188
2189 2189 # use last_call to remember the state of the previous call, but don't
2190 2190 # let it be clobbered by successive '-p' calls.
2191 2191 try:
2192 2192 last_call[0] = self.shell.displayhook.prompt_count
2193 2193 if not opts_prev:
2194 2194 last_call[1] = parameter_s
2195 2195 except:
2196 2196 pass
2197 2197
2198 2198 # by default this is done with temp files, except when the given
2199 2199 # arg is a filename
2200 2200 use_temp = True
2201 2201
2202 2202 data = ''
2203 2203
2204 2204 # First, see if the arguments should be a filename.
2205 2205 filename = make_filename(args)
2206 2206 if filename:
2207 2207 use_temp = False
2208 2208 elif args:
2209 2209 # Mode where user specifies ranges of lines, like in %macro.
2210 2210 data = self.extract_input_lines(args, opts_raw)
2211 2211 if not data:
2212 2212 try:
2213 2213 # Load the parameter given as a variable. If not a string,
2214 2214 # process it as an object instead (below)
2215 2215
2216 2216 #print '*** args',args,'type',type(args) # dbg
2217 2217 data = eval(args, self.shell.user_ns)
2218 2218 if not isinstance(data, basestring):
2219 2219 raise DataIsObject
2220 2220
2221 2221 except (NameError,SyntaxError):
2222 2222 # given argument is not a variable, try as a filename
2223 2223 filename = make_filename(args)
2224 2224 if filename is None:
2225 2225 warn("Argument given (%s) can't be found as a variable "
2226 2226 "or as a filename." % args)
2227 2227 return
2228 2228 use_temp = False
2229 2229
2230 2230 except DataIsObject:
2231 2231 # macros have a special edit function
2232 2232 if isinstance(data, Macro):
2233 2233 raise MacroToEdit(data)
2234 2234
2235 2235 # For objects, try to edit the file where they are defined
2236 2236 try:
2237 2237 filename = inspect.getabsfile(data)
2238 2238 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2239 2239 # class created by %edit? Try to find source
2240 2240 # by looking for method definitions instead, the
2241 2241 # __module__ in those classes is FakeModule.
2242 2242 attrs = [getattr(data, aname) for aname in dir(data)]
2243 2243 for attr in attrs:
2244 2244 if not inspect.ismethod(attr):
2245 2245 continue
2246 2246 filename = inspect.getabsfile(attr)
2247 2247 if filename and 'fakemodule' not in filename.lower():
2248 2248 # change the attribute to be the edit target instead
2249 2249 data = attr
2250 2250 break
2251 2251
2252 2252 datafile = 1
2253 2253 except TypeError:
2254 2254 filename = make_filename(args)
2255 2255 datafile = 1
2256 2256 warn('Could not find file where `%s` is defined.\n'
2257 2257 'Opening a file named `%s`' % (args,filename))
2258 2258 # Now, make sure we can actually read the source (if it was in
2259 2259 # a temp file it's gone by now).
2260 2260 if datafile:
2261 2261 try:
2262 2262 if lineno is None:
2263 2263 lineno = inspect.getsourcelines(data)[1]
2264 2264 except IOError:
2265 2265 filename = make_filename(args)
2266 2266 if filename is None:
2267 2267 warn('The file `%s` where `%s` was defined cannot '
2268 2268 'be read.' % (filename,data))
2269 2269 return
2270 2270 use_temp = False
2271 2271
2272 2272 if use_temp:
2273 2273 filename = self.shell.mktempfile(data)
2274 2274 print 'IPython will make a temporary file named:',filename
2275 2275
2276 2276 return filename, lineno, use_temp
2277 2277
2278 2278 def _edit_macro(self,mname,macro):
2279 2279 """open an editor with the macro data in a file"""
2280 2280 filename = self.shell.mktempfile(macro.value)
2281 2281 self.shell.hooks.editor(filename)
2282 2282
2283 2283 # and make a new macro object, to replace the old one
2284 2284 mfile = open(filename)
2285 2285 mvalue = mfile.read()
2286 2286 mfile.close()
2287 2287 self.shell.user_ns[mname] = Macro(mvalue)
2288 2288
2289 2289 def magic_ed(self,parameter_s=''):
2290 2290 """Alias to %edit."""
2291 2291 return self.magic_edit(parameter_s)
2292 2292
2293 2293 @skip_doctest
2294 2294 def magic_edit(self,parameter_s='',last_call=['','']):
2295 2295 """Bring up an editor and execute the resulting code.
2296 2296
2297 2297 Usage:
2298 2298 %edit [options] [args]
2299 2299
2300 2300 %edit runs IPython's editor hook. The default version of this hook is
2301 2301 set to call the editor specified by your $EDITOR environment variable.
2302 2302 If this isn't found, it will default to vi under Linux/Unix and to
2303 2303 notepad under Windows. See the end of this docstring for how to change
2304 2304 the editor hook.
2305 2305
2306 2306 You can also set the value of this editor via the
2307 2307 ``TerminalInteractiveShell.editor`` option in your configuration file.
2308 2308 This is useful if you wish to use a different editor from your typical
2309 2309 default with IPython (and for Windows users who typically don't set
2310 2310 environment variables).
2311 2311
2312 2312 This command allows you to conveniently edit multi-line code right in
2313 2313 your IPython session.
2314 2314
2315 2315 If called without arguments, %edit opens up an empty editor with a
2316 2316 temporary file and will execute the contents of this file when you
2317 2317 close it (don't forget to save it!).
2318 2318
2319 2319
2320 2320 Options:
2321 2321
2322 2322 -n <number>: open the editor at a specified line number. By default,
2323 2323 the IPython editor hook uses the unix syntax 'editor +N filename', but
2324 2324 you can configure this by providing your own modified hook if your
2325 2325 favorite editor supports line-number specifications with a different
2326 2326 syntax.
2327 2327
2328 2328 -p: this will call the editor with the same data as the previous time
2329 2329 it was used, regardless of how long ago (in your current session) it
2330 2330 was.
2331 2331
2332 2332 -r: use 'raw' input. This option only applies to input taken from the
2333 2333 user's history. By default, the 'processed' history is used, so that
2334 2334 magics are loaded in their transformed version to valid Python. If
2335 2335 this option is given, the raw input as typed as the command line is
2336 2336 used instead. When you exit the editor, it will be executed by
2337 2337 IPython's own processor.
2338 2338
2339 2339 -x: do not execute the edited code immediately upon exit. This is
2340 2340 mainly useful if you are editing programs which need to be called with
2341 2341 command line arguments, which you can then do using %run.
2342 2342
2343 2343
2344 2344 Arguments:
2345 2345
2346 2346 If arguments are given, the following possibilites exist:
2347 2347
2348 2348 - If the argument is a filename, IPython will load that into the
2349 2349 editor. It will execute its contents with execfile() when you exit,
2350 2350 loading any code in the file into your interactive namespace.
2351 2351
2352 2352 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2353 2353 The syntax is the same as in the %history magic.
2354 2354
2355 2355 - If the argument is a string variable, its contents are loaded
2356 2356 into the editor. You can thus edit any string which contains
2357 2357 python code (including the result of previous edits).
2358 2358
2359 2359 - If the argument is the name of an object (other than a string),
2360 2360 IPython will try to locate the file where it was defined and open the
2361 2361 editor at the point where it is defined. You can use `%edit function`
2362 2362 to load an editor exactly at the point where 'function' is defined,
2363 2363 edit it and have the file be executed automatically.
2364 2364
2365 2365 - If the object is a macro (see %macro for details), this opens up your
2366 2366 specified editor with a temporary file containing the macro's data.
2367 2367 Upon exit, the macro is reloaded with the contents of the file.
2368 2368
2369 2369 Note: opening at an exact line is only supported under Unix, and some
2370 2370 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2371 2371 '+NUMBER' parameter necessary for this feature. Good editors like
2372 2372 (X)Emacs, vi, jed, pico and joe all do.
2373 2373
2374 2374 After executing your code, %edit will return as output the code you
2375 2375 typed in the editor (except when it was an existing file). This way
2376 2376 you can reload the code in further invocations of %edit as a variable,
2377 2377 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2378 2378 the output.
2379 2379
2380 2380 Note that %edit is also available through the alias %ed.
2381 2381
2382 2382 This is an example of creating a simple function inside the editor and
2383 2383 then modifying it. First, start up the editor:
2384 2384
2385 2385 In [1]: ed
2386 2386 Editing... done. Executing edited code...
2387 2387 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2388 2388
2389 2389 We can then call the function foo():
2390 2390
2391 2391 In [2]: foo()
2392 2392 foo() was defined in an editing session
2393 2393
2394 2394 Now we edit foo. IPython automatically loads the editor with the
2395 2395 (temporary) file where foo() was previously defined:
2396 2396
2397 2397 In [3]: ed foo
2398 2398 Editing... done. Executing edited code...
2399 2399
2400 2400 And if we call foo() again we get the modified version:
2401 2401
2402 2402 In [4]: foo()
2403 2403 foo() has now been changed!
2404 2404
2405 2405 Here is an example of how to edit a code snippet successive
2406 2406 times. First we call the editor:
2407 2407
2408 2408 In [5]: ed
2409 2409 Editing... done. Executing edited code...
2410 2410 hello
2411 2411 Out[5]: "print 'hello'n"
2412 2412
2413 2413 Now we call it again with the previous output (stored in _):
2414 2414
2415 2415 In [6]: ed _
2416 2416 Editing... done. Executing edited code...
2417 2417 hello world
2418 2418 Out[6]: "print 'hello world'n"
2419 2419
2420 2420 Now we call it with the output #8 (stored in _8, also as Out[8]):
2421 2421
2422 2422 In [7]: ed _8
2423 2423 Editing... done. Executing edited code...
2424 2424 hello again
2425 2425 Out[7]: "print 'hello again'n"
2426 2426
2427 2427
2428 2428 Changing the default editor hook:
2429 2429
2430 2430 If you wish to write your own editor hook, you can put it in a
2431 2431 configuration file which you load at startup time. The default hook
2432 2432 is defined in the IPython.core.hooks module, and you can use that as a
2433 2433 starting example for further modifications. That file also has
2434 2434 general instructions on how to set a new hook for use once you've
2435 2435 defined it."""
2436 2436 opts,args = self.parse_options(parameter_s,'prxn:')
2437 2437
2438 2438 try:
2439 2439 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2440 2440 except MacroToEdit as e:
2441 2441 self._edit_macro(args, e.args[0])
2442 2442 return
2443 2443
2444 2444 # do actual editing here
2445 2445 print 'Editing...',
2446 2446 sys.stdout.flush()
2447 2447 try:
2448 2448 # Quote filenames that may have spaces in them
2449 2449 if ' ' in filename:
2450 2450 filename = "'%s'" % filename
2451 2451 self.shell.hooks.editor(filename,lineno)
2452 2452 except TryNext:
2453 2453 warn('Could not open editor')
2454 2454 return
2455 2455
2456 2456 # XXX TODO: should this be generalized for all string vars?
2457 2457 # For now, this is special-cased to blocks created by cpaste
2458 2458 if args.strip() == 'pasted_block':
2459 2459 self.shell.user_ns['pasted_block'] = file_read(filename)
2460 2460
2461 2461 if 'x' in opts: # -x prevents actual execution
2462 2462 print
2463 2463 else:
2464 2464 print 'done. Executing edited code...'
2465 2465 if 'r' in opts: # Untranslated IPython code
2466 2466 self.shell.run_cell(file_read(filename),
2467 2467 store_history=False)
2468 2468 else:
2469 2469 self.shell.safe_execfile(filename,self.shell.user_ns,
2470 2470 self.shell.user_ns)
2471 2471
2472 2472 if is_temp:
2473 2473 try:
2474 2474 return open(filename).read()
2475 2475 except IOError,msg:
2476 2476 if msg.filename == filename:
2477 2477 warn('File not found. Did you forget to save?')
2478 2478 return
2479 2479 else:
2480 2480 self.shell.showtraceback()
2481 2481
2482 2482 def magic_xmode(self,parameter_s = ''):
2483 2483 """Switch modes for the exception handlers.
2484 2484
2485 2485 Valid modes: Plain, Context and Verbose.
2486 2486
2487 2487 If called without arguments, acts as a toggle."""
2488 2488
2489 2489 def xmode_switch_err(name):
2490 2490 warn('Error changing %s exception modes.\n%s' %
2491 2491 (name,sys.exc_info()[1]))
2492 2492
2493 2493 shell = self.shell
2494 2494 new_mode = parameter_s.strip().capitalize()
2495 2495 try:
2496 2496 shell.InteractiveTB.set_mode(mode=new_mode)
2497 2497 print 'Exception reporting mode:',shell.InteractiveTB.mode
2498 2498 except:
2499 2499 xmode_switch_err('user')
2500 2500
2501 2501 def magic_colors(self,parameter_s = ''):
2502 2502 """Switch color scheme for prompts, info system and exception handlers.
2503 2503
2504 2504 Currently implemented schemes: NoColor, Linux, LightBG.
2505 2505
2506 2506 Color scheme names are not case-sensitive.
2507 2507
2508 2508 Examples
2509 2509 --------
2510 2510 To get a plain black and white terminal::
2511 2511
2512 2512 %colors nocolor
2513 2513 """
2514 2514
2515 2515 def color_switch_err(name):
2516 2516 warn('Error changing %s color schemes.\n%s' %
2517 2517 (name,sys.exc_info()[1]))
2518 2518
2519 2519
2520 2520 new_scheme = parameter_s.strip()
2521 2521 if not new_scheme:
2522 2522 raise UsageError(
2523 2523 "%colors: you must specify a color scheme. See '%colors?'")
2524 2524 return
2525 2525 # local shortcut
2526 2526 shell = self.shell
2527 2527
2528 2528 import IPython.utils.rlineimpl as readline
2529 2529
2530 2530 if not shell.colors_force and \
2531 2531 not readline.have_readline and sys.platform == "win32":
2532 2532 msg = """\
2533 2533 Proper color support under MS Windows requires the pyreadline library.
2534 2534 You can find it at:
2535 2535 http://ipython.org/pyreadline.html
2536 2536 Gary's readline needs the ctypes module, from:
2537 2537 http://starship.python.net/crew/theller/ctypes
2538 2538 (Note that ctypes is already part of Python versions 2.5 and newer).
2539 2539
2540 2540 Defaulting color scheme to 'NoColor'"""
2541 2541 new_scheme = 'NoColor'
2542 2542 warn(msg)
2543 2543
2544 2544 # readline option is 0
2545 2545 if not shell.colors_force and not shell.has_readline:
2546 2546 new_scheme = 'NoColor'
2547 2547
2548 2548 # Set prompt colors
2549 2549 try:
2550 2550 shell.displayhook.set_colors(new_scheme)
2551 2551 except:
2552 2552 color_switch_err('prompt')
2553 2553 else:
2554 2554 shell.colors = \
2555 2555 shell.displayhook.color_table.active_scheme_name
2556 2556 # Set exception colors
2557 2557 try:
2558 2558 shell.InteractiveTB.set_colors(scheme = new_scheme)
2559 2559 shell.SyntaxTB.set_colors(scheme = new_scheme)
2560 2560 except:
2561 2561 color_switch_err('exception')
2562 2562
2563 2563 # Set info (for 'object?') colors
2564 2564 if shell.color_info:
2565 2565 try:
2566 2566 shell.inspector.set_active_scheme(new_scheme)
2567 2567 except:
2568 2568 color_switch_err('object inspector')
2569 2569 else:
2570 2570 shell.inspector.set_active_scheme('NoColor')
2571 2571
2572 2572 def magic_pprint(self, parameter_s=''):
2573 2573 """Toggle pretty printing on/off."""
2574 2574 ptformatter = self.shell.display_formatter.formatters['text/plain']
2575 2575 ptformatter.pprint = bool(1 - ptformatter.pprint)
2576 2576 print 'Pretty printing has been turned', \
2577 2577 ['OFF','ON'][ptformatter.pprint]
2578 2578
2579 2579 #......................................................................
2580 2580 # Functions to implement unix shell-type things
2581 2581
2582 2582 @skip_doctest
2583 2583 def magic_alias(self, parameter_s = ''):
2584 2584 """Define an alias for a system command.
2585 2585
2586 2586 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2587 2587
2588 2588 Then, typing 'alias_name params' will execute the system command 'cmd
2589 2589 params' (from your underlying operating system).
2590 2590
2591 2591 Aliases have lower precedence than magic functions and Python normal
2592 2592 variables, so if 'foo' is both a Python variable and an alias, the
2593 2593 alias can not be executed until 'del foo' removes the Python variable.
2594 2594
2595 2595 You can use the %l specifier in an alias definition to represent the
2596 2596 whole line when the alias is called. For example:
2597 2597
2598 2598 In [2]: alias bracket echo "Input in brackets: <%l>"
2599 2599 In [3]: bracket hello world
2600 2600 Input in brackets: <hello world>
2601 2601
2602 2602 You can also define aliases with parameters using %s specifiers (one
2603 2603 per parameter):
2604 2604
2605 2605 In [1]: alias parts echo first %s second %s
2606 2606 In [2]: %parts A B
2607 2607 first A second B
2608 2608 In [3]: %parts A
2609 2609 Incorrect number of arguments: 2 expected.
2610 2610 parts is an alias to: 'echo first %s second %s'
2611 2611
2612 2612 Note that %l and %s are mutually exclusive. You can only use one or
2613 2613 the other in your aliases.
2614 2614
2615 2615 Aliases expand Python variables just like system calls using ! or !!
2616 2616 do: all expressions prefixed with '$' get expanded. For details of
2617 2617 the semantic rules, see PEP-215:
2618 2618 http://www.python.org/peps/pep-0215.html. This is the library used by
2619 2619 IPython for variable expansion. If you want to access a true shell
2620 2620 variable, an extra $ is necessary to prevent its expansion by IPython:
2621 2621
2622 2622 In [6]: alias show echo
2623 2623 In [7]: PATH='A Python string'
2624 2624 In [8]: show $PATH
2625 2625 A Python string
2626 2626 In [9]: show $$PATH
2627 2627 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2628 2628
2629 2629 You can use the alias facility to acess all of $PATH. See the %rehash
2630 2630 and %rehashx functions, which automatically create aliases for the
2631 2631 contents of your $PATH.
2632 2632
2633 2633 If called with no parameters, %alias prints the current alias table."""
2634 2634
2635 2635 par = parameter_s.strip()
2636 2636 if not par:
2637 2637 stored = self.db.get('stored_aliases', {} )
2638 2638 aliases = sorted(self.shell.alias_manager.aliases)
2639 2639 # for k, v in stored:
2640 2640 # atab.append(k, v[0])
2641 2641
2642 2642 print "Total number of aliases:", len(aliases)
2643 2643 sys.stdout.flush()
2644 2644 return aliases
2645 2645
2646 2646 # Now try to define a new one
2647 2647 try:
2648 2648 alias,cmd = par.split(None, 1)
2649 2649 except:
2650 2650 print oinspect.getdoc(self.magic_alias)
2651 2651 else:
2652 2652 self.shell.alias_manager.soft_define_alias(alias, cmd)
2653 2653 # end magic_alias
2654 2654
2655 2655 def magic_unalias(self, parameter_s = ''):
2656 2656 """Remove an alias"""
2657 2657
2658 2658 aname = parameter_s.strip()
2659 2659 self.shell.alias_manager.undefine_alias(aname)
2660 2660 stored = self.db.get('stored_aliases', {} )
2661 2661 if aname in stored:
2662 2662 print "Removing %stored alias",aname
2663 2663 del stored[aname]
2664 2664 self.db['stored_aliases'] = stored
2665 2665
2666 2666 def magic_rehashx(self, parameter_s = ''):
2667 2667 """Update the alias table with all executable files in $PATH.
2668 2668
2669 2669 This version explicitly checks that every entry in $PATH is a file
2670 2670 with execute access (os.X_OK), so it is much slower than %rehash.
2671 2671
2672 2672 Under Windows, it checks executability as a match agains a
2673 2673 '|'-separated string of extensions, stored in the IPython config
2674 2674 variable win_exec_ext. This defaults to 'exe|com|bat'.
2675 2675
2676 2676 This function also resets the root module cache of module completer,
2677 2677 used on slow filesystems.
2678 2678 """
2679 2679 from IPython.core.alias import InvalidAliasError
2680 2680
2681 2681 # for the benefit of module completer in ipy_completers.py
2682 2682 del self.db['rootmodules']
2683 2683
2684 2684 path = [os.path.abspath(os.path.expanduser(p)) for p in
2685 2685 os.environ.get('PATH','').split(os.pathsep)]
2686 2686 path = filter(os.path.isdir,path)
2687 2687
2688 2688 syscmdlist = []
2689 2689 # Now define isexec in a cross platform manner.
2690 2690 if os.name == 'posix':
2691 2691 isexec = lambda fname:os.path.isfile(fname) and \
2692 2692 os.access(fname,os.X_OK)
2693 2693 else:
2694 2694 try:
2695 2695 winext = os.environ['pathext'].replace(';','|').replace('.','')
2696 2696 except KeyError:
2697 2697 winext = 'exe|com|bat|py'
2698 2698 if 'py' not in winext:
2699 2699 winext += '|py'
2700 2700 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2701 2701 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2702 2702 savedir = os.getcwdu()
2703 2703
2704 2704 # Now walk the paths looking for executables to alias.
2705 2705 try:
2706 2706 # write the whole loop for posix/Windows so we don't have an if in
2707 2707 # the innermost part
2708 2708 if os.name == 'posix':
2709 2709 for pdir in path:
2710 2710 os.chdir(pdir)
2711 2711 for ff in os.listdir(pdir):
2712 2712 if isexec(ff):
2713 2713 try:
2714 2714 # Removes dots from the name since ipython
2715 2715 # will assume names with dots to be python.
2716 2716 self.shell.alias_manager.define_alias(
2717 2717 ff.replace('.',''), ff)
2718 2718 except InvalidAliasError:
2719 2719 pass
2720 2720 else:
2721 2721 syscmdlist.append(ff)
2722 2722 else:
2723 2723 no_alias = self.shell.alias_manager.no_alias
2724 2724 for pdir in path:
2725 2725 os.chdir(pdir)
2726 2726 for ff in os.listdir(pdir):
2727 2727 base, ext = os.path.splitext(ff)
2728 2728 if isexec(ff) and base.lower() not in no_alias:
2729 2729 if ext.lower() == '.exe':
2730 2730 ff = base
2731 2731 try:
2732 2732 # Removes dots from the name since ipython
2733 2733 # will assume names with dots to be python.
2734 2734 self.shell.alias_manager.define_alias(
2735 2735 base.lower().replace('.',''), ff)
2736 2736 except InvalidAliasError:
2737 2737 pass
2738 2738 syscmdlist.append(ff)
2739 2739 db = self.db
2740 2740 db['syscmdlist'] = syscmdlist
2741 2741 finally:
2742 2742 os.chdir(savedir)
2743 2743
2744 2744 @skip_doctest
2745 2745 def magic_pwd(self, parameter_s = ''):
2746 2746 """Return the current working directory path.
2747 2747
2748 2748 Examples
2749 2749 --------
2750 2750 ::
2751 2751
2752 2752 In [9]: pwd
2753 2753 Out[9]: '/home/tsuser/sprint/ipython'
2754 2754 """
2755 2755 return os.getcwdu()
2756 2756
2757 2757 @skip_doctest
2758 2758 def magic_cd(self, parameter_s=''):
2759 2759 """Change the current working directory.
2760 2760
2761 2761 This command automatically maintains an internal list of directories
2762 2762 you visit during your IPython session, in the variable _dh. The
2763 2763 command %dhist shows this history nicely formatted. You can also
2764 2764 do 'cd -<tab>' to see directory history conveniently.
2765 2765
2766 2766 Usage:
2767 2767
2768 2768 cd 'dir': changes to directory 'dir'.
2769 2769
2770 2770 cd -: changes to the last visited directory.
2771 2771
2772 2772 cd -<n>: changes to the n-th directory in the directory history.
2773 2773
2774 2774 cd --foo: change to directory that matches 'foo' in history
2775 2775
2776 2776 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2777 2777 (note: cd <bookmark_name> is enough if there is no
2778 2778 directory <bookmark_name>, but a bookmark with the name exists.)
2779 2779 'cd -b <tab>' allows you to tab-complete bookmark names.
2780 2780
2781 2781 Options:
2782 2782
2783 2783 -q: quiet. Do not print the working directory after the cd command is
2784 2784 executed. By default IPython's cd command does print this directory,
2785 2785 since the default prompts do not display path information.
2786 2786
2787 2787 Note that !cd doesn't work for this purpose because the shell where
2788 2788 !command runs is immediately discarded after executing 'command'.
2789 2789
2790 2790 Examples
2791 2791 --------
2792 2792 ::
2793 2793
2794 2794 In [10]: cd parent/child
2795 2795 /home/tsuser/parent/child
2796 2796 """
2797 2797
2798 2798 parameter_s = parameter_s.strip()
2799 2799 #bkms = self.shell.persist.get("bookmarks",{})
2800 2800
2801 2801 oldcwd = os.getcwdu()
2802 2802 numcd = re.match(r'(-)(\d+)$',parameter_s)
2803 2803 # jump in directory history by number
2804 2804 if numcd:
2805 2805 nn = int(numcd.group(2))
2806 2806 try:
2807 2807 ps = self.shell.user_ns['_dh'][nn]
2808 2808 except IndexError:
2809 2809 print 'The requested directory does not exist in history.'
2810 2810 return
2811 2811 else:
2812 2812 opts = {}
2813 2813 elif parameter_s.startswith('--'):
2814 2814 ps = None
2815 2815 fallback = None
2816 2816 pat = parameter_s[2:]
2817 2817 dh = self.shell.user_ns['_dh']
2818 2818 # first search only by basename (last component)
2819 2819 for ent in reversed(dh):
2820 2820 if pat in os.path.basename(ent) and os.path.isdir(ent):
2821 2821 ps = ent
2822 2822 break
2823 2823
2824 2824 if fallback is None and pat in ent and os.path.isdir(ent):
2825 2825 fallback = ent
2826 2826
2827 2827 # if we have no last part match, pick the first full path match
2828 2828 if ps is None:
2829 2829 ps = fallback
2830 2830
2831 2831 if ps is None:
2832 2832 print "No matching entry in directory history"
2833 2833 return
2834 2834 else:
2835 2835 opts = {}
2836 2836
2837 2837
2838 2838 else:
2839 2839 #turn all non-space-escaping backslashes to slashes,
2840 2840 # for c:\windows\directory\names\
2841 2841 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2842 2842 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2843 2843 # jump to previous
2844 2844 if ps == '-':
2845 2845 try:
2846 2846 ps = self.shell.user_ns['_dh'][-2]
2847 2847 except IndexError:
2848 2848 raise UsageError('%cd -: No previous directory to change to.')
2849 2849 # jump to bookmark if needed
2850 2850 else:
2851 2851 if not os.path.isdir(ps) or opts.has_key('b'):
2852 2852 bkms = self.db.get('bookmarks', {})
2853 2853
2854 2854 if bkms.has_key(ps):
2855 2855 target = bkms[ps]
2856 2856 print '(bookmark:%s) -> %s' % (ps,target)
2857 2857 ps = target
2858 2858 else:
2859 2859 if opts.has_key('b'):
2860 2860 raise UsageError("Bookmark '%s' not found. "
2861 2861 "Use '%%bookmark -l' to see your bookmarks." % ps)
2862 2862
2863 2863 # strip extra quotes on Windows, because os.chdir doesn't like them
2864 2864 ps = unquote_filename(ps)
2865 2865 # at this point ps should point to the target dir
2866 2866 if ps:
2867 2867 try:
2868 2868 os.chdir(os.path.expanduser(ps))
2869 2869 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2870 2870 set_term_title('IPython: ' + abbrev_cwd())
2871 2871 except OSError:
2872 2872 print sys.exc_info()[1]
2873 2873 else:
2874 2874 cwd = os.getcwdu()
2875 2875 dhist = self.shell.user_ns['_dh']
2876 2876 if oldcwd != cwd:
2877 2877 dhist.append(cwd)
2878 2878 self.db['dhist'] = compress_dhist(dhist)[-100:]
2879 2879
2880 2880 else:
2881 2881 os.chdir(self.shell.home_dir)
2882 2882 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2883 2883 set_term_title('IPython: ' + '~')
2884 2884 cwd = os.getcwdu()
2885 2885 dhist = self.shell.user_ns['_dh']
2886 2886
2887 2887 if oldcwd != cwd:
2888 2888 dhist.append(cwd)
2889 2889 self.db['dhist'] = compress_dhist(dhist)[-100:]
2890 2890 if not 'q' in opts and self.shell.user_ns['_dh']:
2891 2891 print self.shell.user_ns['_dh'][-1]
2892 2892
2893 2893
2894 2894 def magic_env(self, parameter_s=''):
2895 2895 """List environment variables."""
2896 2896
2897 2897 return os.environ.data
2898 2898
2899 2899 def magic_pushd(self, parameter_s=''):
2900 2900 """Place the current dir on stack and change directory.
2901 2901
2902 2902 Usage:\\
2903 2903 %pushd ['dirname']
2904 2904 """
2905 2905
2906 2906 dir_s = self.shell.dir_stack
2907 2907 tgt = os.path.expanduser(unquote_filename(parameter_s))
2908 2908 cwd = os.getcwdu().replace(self.home_dir,'~')
2909 2909 if tgt:
2910 2910 self.magic_cd(parameter_s)
2911 2911 dir_s.insert(0,cwd)
2912 2912 return self.magic_dirs()
2913 2913
2914 2914 def magic_popd(self, parameter_s=''):
2915 2915 """Change to directory popped off the top of the stack.
2916 2916 """
2917 2917 if not self.shell.dir_stack:
2918 2918 raise UsageError("%popd on empty stack")
2919 2919 top = self.shell.dir_stack.pop(0)
2920 2920 self.magic_cd(top)
2921 2921 print "popd ->",top
2922 2922
2923 2923 def magic_dirs(self, parameter_s=''):
2924 2924 """Return the current directory stack."""
2925 2925
2926 2926 return self.shell.dir_stack
2927 2927
2928 2928 def magic_dhist(self, parameter_s=''):
2929 2929 """Print your history of visited directories.
2930 2930
2931 2931 %dhist -> print full history\\
2932 2932 %dhist n -> print last n entries only\\
2933 2933 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2934 2934
2935 2935 This history is automatically maintained by the %cd command, and
2936 2936 always available as the global list variable _dh. You can use %cd -<n>
2937 2937 to go to directory number <n>.
2938 2938
2939 2939 Note that most of time, you should view directory history by entering
2940 2940 cd -<TAB>.
2941 2941
2942 2942 """
2943 2943
2944 2944 dh = self.shell.user_ns['_dh']
2945 2945 if parameter_s:
2946 2946 try:
2947 2947 args = map(int,parameter_s.split())
2948 2948 except:
2949 2949 self.arg_err(Magic.magic_dhist)
2950 2950 return
2951 2951 if len(args) == 1:
2952 2952 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2953 2953 elif len(args) == 2:
2954 2954 ini,fin = args
2955 2955 else:
2956 2956 self.arg_err(Magic.magic_dhist)
2957 2957 return
2958 2958 else:
2959 2959 ini,fin = 0,len(dh)
2960 2960 nlprint(dh,
2961 2961 header = 'Directory history (kept in _dh)',
2962 2962 start=ini,stop=fin)
2963 2963
2964 2964 @skip_doctest
2965 2965 def magic_sc(self, parameter_s=''):
2966 2966 """Shell capture - execute a shell command and capture its output.
2967 2967
2968 2968 DEPRECATED. Suboptimal, retained for backwards compatibility.
2969 2969
2970 2970 You should use the form 'var = !command' instead. Example:
2971 2971
2972 2972 "%sc -l myfiles = ls ~" should now be written as
2973 2973
2974 2974 "myfiles = !ls ~"
2975 2975
2976 2976 myfiles.s, myfiles.l and myfiles.n still apply as documented
2977 2977 below.
2978 2978
2979 2979 --
2980 2980 %sc [options] varname=command
2981 2981
2982 2982 IPython will run the given command using commands.getoutput(), and
2983 2983 will then update the user's interactive namespace with a variable
2984 2984 called varname, containing the value of the call. Your command can
2985 2985 contain shell wildcards, pipes, etc.
2986 2986
2987 2987 The '=' sign in the syntax is mandatory, and the variable name you
2988 2988 supply must follow Python's standard conventions for valid names.
2989 2989
2990 2990 (A special format without variable name exists for internal use)
2991 2991
2992 2992 Options:
2993 2993
2994 2994 -l: list output. Split the output on newlines into a list before
2995 2995 assigning it to the given variable. By default the output is stored
2996 2996 as a single string.
2997 2997
2998 2998 -v: verbose. Print the contents of the variable.
2999 2999
3000 3000 In most cases you should not need to split as a list, because the
3001 3001 returned value is a special type of string which can automatically
3002 3002 provide its contents either as a list (split on newlines) or as a
3003 3003 space-separated string. These are convenient, respectively, either
3004 3004 for sequential processing or to be passed to a shell command.
3005 3005
3006 3006 For example:
3007 3007
3008 3008 # all-random
3009 3009
3010 3010 # Capture into variable a
3011 3011 In [1]: sc a=ls *py
3012 3012
3013 3013 # a is a string with embedded newlines
3014 3014 In [2]: a
3015 3015 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3016 3016
3017 3017 # which can be seen as a list:
3018 3018 In [3]: a.l
3019 3019 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3020 3020
3021 3021 # or as a whitespace-separated string:
3022 3022 In [4]: a.s
3023 3023 Out[4]: 'setup.py win32_manual_post_install.py'
3024 3024
3025 3025 # a.s is useful to pass as a single command line:
3026 3026 In [5]: !wc -l $a.s
3027 3027 146 setup.py
3028 3028 130 win32_manual_post_install.py
3029 3029 276 total
3030 3030
3031 3031 # while the list form is useful to loop over:
3032 3032 In [6]: for f in a.l:
3033 3033 ...: !wc -l $f
3034 3034 ...:
3035 3035 146 setup.py
3036 3036 130 win32_manual_post_install.py
3037 3037
3038 3038 Similiarly, the lists returned by the -l option are also special, in
3039 3039 the sense that you can equally invoke the .s attribute on them to
3040 3040 automatically get a whitespace-separated string from their contents:
3041 3041
3042 3042 In [7]: sc -l b=ls *py
3043 3043
3044 3044 In [8]: b
3045 3045 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3046 3046
3047 3047 In [9]: b.s
3048 3048 Out[9]: 'setup.py win32_manual_post_install.py'
3049 3049
3050 3050 In summary, both the lists and strings used for ouptut capture have
3051 3051 the following special attributes:
3052 3052
3053 3053 .l (or .list) : value as list.
3054 3054 .n (or .nlstr): value as newline-separated string.
3055 3055 .s (or .spstr): value as space-separated string.
3056 3056 """
3057 3057
3058 3058 opts,args = self.parse_options(parameter_s,'lv')
3059 3059 # Try to get a variable name and command to run
3060 3060 try:
3061 3061 # the variable name must be obtained from the parse_options
3062 3062 # output, which uses shlex.split to strip options out.
3063 3063 var,_ = args.split('=',1)
3064 3064 var = var.strip()
3065 3065 # But the the command has to be extracted from the original input
3066 3066 # parameter_s, not on what parse_options returns, to avoid the
3067 3067 # quote stripping which shlex.split performs on it.
3068 3068 _,cmd = parameter_s.split('=',1)
3069 3069 except ValueError:
3070 3070 var,cmd = '',''
3071 3071 # If all looks ok, proceed
3072 3072 split = 'l' in opts
3073 3073 out = self.shell.getoutput(cmd, split=split)
3074 3074 if opts.has_key('v'):
3075 3075 print '%s ==\n%s' % (var,pformat(out))
3076 3076 if var:
3077 3077 self.shell.user_ns.update({var:out})
3078 3078 else:
3079 3079 return out
3080 3080
3081 3081 def magic_sx(self, parameter_s=''):
3082 3082 """Shell execute - run a shell command and capture its output.
3083 3083
3084 3084 %sx command
3085 3085
3086 3086 IPython will run the given command using commands.getoutput(), and
3087 3087 return the result formatted as a list (split on '\\n'). Since the
3088 3088 output is _returned_, it will be stored in ipython's regular output
3089 3089 cache Out[N] and in the '_N' automatic variables.
3090 3090
3091 3091 Notes:
3092 3092
3093 3093 1) If an input line begins with '!!', then %sx is automatically
3094 3094 invoked. That is, while:
3095 3095 !ls
3096 3096 causes ipython to simply issue system('ls'), typing
3097 3097 !!ls
3098 3098 is a shorthand equivalent to:
3099 3099 %sx ls
3100 3100
3101 3101 2) %sx differs from %sc in that %sx automatically splits into a list,
3102 3102 like '%sc -l'. The reason for this is to make it as easy as possible
3103 3103 to process line-oriented shell output via further python commands.
3104 3104 %sc is meant to provide much finer control, but requires more
3105 3105 typing.
3106 3106
3107 3107 3) Just like %sc -l, this is a list with special attributes:
3108 3108
3109 3109 .l (or .list) : value as list.
3110 3110 .n (or .nlstr): value as newline-separated string.
3111 3111 .s (or .spstr): value as whitespace-separated string.
3112 3112
3113 3113 This is very useful when trying to use such lists as arguments to
3114 3114 system commands."""
3115 3115
3116 3116 if parameter_s:
3117 3117 return self.shell.getoutput(parameter_s)
3118 3118
3119 3119
3120 3120 def magic_bookmark(self, parameter_s=''):
3121 3121 """Manage IPython's bookmark system.
3122 3122
3123 3123 %bookmark <name> - set bookmark to current dir
3124 3124 %bookmark <name> <dir> - set bookmark to <dir>
3125 3125 %bookmark -l - list all bookmarks
3126 3126 %bookmark -d <name> - remove bookmark
3127 3127 %bookmark -r - remove all bookmarks
3128 3128
3129 3129 You can later on access a bookmarked folder with:
3130 3130 %cd -b <name>
3131 3131 or simply '%cd <name>' if there is no directory called <name> AND
3132 3132 there is such a bookmark defined.
3133 3133
3134 3134 Your bookmarks persist through IPython sessions, but they are
3135 3135 associated with each profile."""
3136 3136
3137 3137 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3138 3138 if len(args) > 2:
3139 3139 raise UsageError("%bookmark: too many arguments")
3140 3140
3141 3141 bkms = self.db.get('bookmarks',{})
3142 3142
3143 3143 if opts.has_key('d'):
3144 3144 try:
3145 3145 todel = args[0]
3146 3146 except IndexError:
3147 3147 raise UsageError(
3148 3148 "%bookmark -d: must provide a bookmark to delete")
3149 3149 else:
3150 3150 try:
3151 3151 del bkms[todel]
3152 3152 except KeyError:
3153 3153 raise UsageError(
3154 3154 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3155 3155
3156 3156 elif opts.has_key('r'):
3157 3157 bkms = {}
3158 3158 elif opts.has_key('l'):
3159 3159 bks = bkms.keys()
3160 3160 bks.sort()
3161 3161 if bks:
3162 3162 size = max(map(len,bks))
3163 3163 else:
3164 3164 size = 0
3165 3165 fmt = '%-'+str(size)+'s -> %s'
3166 3166 print 'Current bookmarks:'
3167 3167 for bk in bks:
3168 3168 print fmt % (bk,bkms[bk])
3169 3169 else:
3170 3170 if not args:
3171 3171 raise UsageError("%bookmark: You must specify the bookmark name")
3172 3172 elif len(args)==1:
3173 3173 bkms[args[0]] = os.getcwdu()
3174 3174 elif len(args)==2:
3175 3175 bkms[args[0]] = args[1]
3176 3176 self.db['bookmarks'] = bkms
3177 3177
3178 3178 def magic_pycat(self, parameter_s=''):
3179 3179 """Show a syntax-highlighted file through a pager.
3180 3180
3181 3181 This magic is similar to the cat utility, but it will assume the file
3182 3182 to be Python source and will show it with syntax highlighting. """
3183 3183
3184 3184 try:
3185 3185 filename = get_py_filename(parameter_s)
3186 3186 cont = file_read(filename)
3187 3187 except IOError:
3188 3188 try:
3189 3189 cont = eval(parameter_s,self.user_ns)
3190 3190 except NameError:
3191 3191 cont = None
3192 3192 if cont is None:
3193 3193 print "Error: no such file or variable"
3194 3194 return
3195 3195
3196 3196 page.page(self.shell.pycolorize(cont))
3197 3197
3198 3198 def _rerun_pasted(self):
3199 3199 """ Rerun a previously pasted command.
3200 3200 """
3201 3201 b = self.user_ns.get('pasted_block', None)
3202 3202 if b is None:
3203 3203 raise UsageError('No previous pasted block available')
3204 3204 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3205 3205 exec b in self.user_ns
3206 3206
3207 3207 def _get_pasted_lines(self, sentinel):
3208 3208 """ Yield pasted lines until the user enters the given sentinel value.
3209 3209 """
3210 3210 from IPython.core import interactiveshell
3211 3211 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3212 3212 while True:
3213 3213 try:
3214 3214 l = self.shell.raw_input_original(':')
3215 3215 if l == sentinel:
3216 3216 return
3217 3217 else:
3218 3218 yield l
3219 3219 except EOFError:
3220 3220 print '<EOF>'
3221 3221 return
3222 3222
3223 3223 def _strip_pasted_lines_for_code(self, raw_lines):
3224 3224 """ Strip non-code parts of a sequence of lines to return a block of
3225 3225 code.
3226 3226 """
3227 3227 # Regular expressions that declare text we strip from the input:
3228 3228 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3229 3229 r'^\s*(\s?>)+', # Python input prompt
3230 3230 r'^\s*\.{3,}', # Continuation prompts
3231 3231 r'^\++',
3232 3232 ]
3233 3233
3234 3234 strip_from_start = map(re.compile,strip_re)
3235 3235
3236 3236 lines = []
3237 3237 for l in raw_lines:
3238 3238 for pat in strip_from_start:
3239 3239 l = pat.sub('',l)
3240 3240 lines.append(l)
3241 3241
3242 3242 block = "\n".join(lines) + '\n'
3243 3243 #print "block:\n",block
3244 3244 return block
3245 3245
3246 3246 def _execute_block(self, block, par):
3247 3247 """ Execute a block, or store it in a variable, per the user's request.
3248 3248 """
3249 3249 if not par:
3250 3250 b = textwrap.dedent(block)
3251 3251 self.user_ns['pasted_block'] = b
3252 3252 self.run_cell(b)
3253 3253 else:
3254 3254 self.user_ns[par] = SList(block.splitlines())
3255 3255 print "Block assigned to '%s'" % par
3256 3256
3257 3257 def magic_quickref(self,arg):
3258 3258 """ Show a quick reference sheet """
3259 3259 import IPython.core.usage
3260 3260 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3261 3261
3262 3262 page.page(qr)
3263 3263
3264 3264 def magic_doctest_mode(self,parameter_s=''):
3265 3265 """Toggle doctest mode on and off.
3266 3266
3267 3267 This mode is intended to make IPython behave as much as possible like a
3268 3268 plain Python shell, from the perspective of how its prompts, exceptions
3269 3269 and output look. This makes it easy to copy and paste parts of a
3270 3270 session into doctests. It does so by:
3271 3271
3272 3272 - Changing the prompts to the classic ``>>>`` ones.
3273 3273 - Changing the exception reporting mode to 'Plain'.
3274 3274 - Disabling pretty-printing of output.
3275 3275
3276 3276 Note that IPython also supports the pasting of code snippets that have
3277 3277 leading '>>>' and '...' prompts in them. This means that you can paste
3278 3278 doctests from files or docstrings (even if they have leading
3279 3279 whitespace), and the code will execute correctly. You can then use
3280 3280 '%history -t' to see the translated history; this will give you the
3281 3281 input after removal of all the leading prompts and whitespace, which
3282 3282 can be pasted back into an editor.
3283 3283
3284 3284 With these features, you can switch into this mode easily whenever you
3285 3285 need to do testing and changes to doctests, without having to leave
3286 3286 your existing IPython session.
3287 3287 """
3288 3288
3289 3289 from IPython.utils.ipstruct import Struct
3290 3290
3291 3291 # Shorthands
3292 3292 shell = self.shell
3293 3293 oc = shell.displayhook
3294 3294 meta = shell.meta
3295 3295 disp_formatter = self.shell.display_formatter
3296 3296 ptformatter = disp_formatter.formatters['text/plain']
3297 3297 # dstore is a data store kept in the instance metadata bag to track any
3298 3298 # changes we make, so we can undo them later.
3299 3299 dstore = meta.setdefault('doctest_mode',Struct())
3300 3300 save_dstore = dstore.setdefault
3301 3301
3302 3302 # save a few values we'll need to recover later
3303 3303 mode = save_dstore('mode',False)
3304 3304 save_dstore('rc_pprint',ptformatter.pprint)
3305 3305 save_dstore('xmode',shell.InteractiveTB.mode)
3306 3306 save_dstore('rc_separate_out',shell.separate_out)
3307 3307 save_dstore('rc_separate_out2',shell.separate_out2)
3308 3308 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3309 3309 save_dstore('rc_separate_in',shell.separate_in)
3310 3310 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3311 3311
3312 3312 if mode == False:
3313 3313 # turn on
3314 3314 oc.prompt1.p_template = '>>> '
3315 3315 oc.prompt2.p_template = '... '
3316 3316 oc.prompt_out.p_template = ''
3317 3317
3318 3318 # Prompt separators like plain python
3319 3319 oc.input_sep = oc.prompt1.sep = ''
3320 3320 oc.output_sep = ''
3321 3321 oc.output_sep2 = ''
3322 3322
3323 3323 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3324 3324 oc.prompt_out.pad_left = False
3325 3325
3326 3326 ptformatter.pprint = False
3327 3327 disp_formatter.plain_text_only = True
3328 3328
3329 3329 shell.magic_xmode('Plain')
3330 3330 else:
3331 3331 # turn off
3332 3332 oc.prompt1.p_template = shell.prompt_in1
3333 3333 oc.prompt2.p_template = shell.prompt_in2
3334 3334 oc.prompt_out.p_template = shell.prompt_out
3335 3335
3336 3336 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3337 3337
3338 3338 oc.output_sep = dstore.rc_separate_out
3339 3339 oc.output_sep2 = dstore.rc_separate_out2
3340 3340
3341 3341 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3342 3342 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3343 3343
3344 3344 ptformatter.pprint = dstore.rc_pprint
3345 3345 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3346 3346
3347 3347 shell.magic_xmode(dstore.xmode)
3348 3348
3349 3349 # Store new mode and inform
3350 3350 dstore.mode = bool(1-int(mode))
3351 3351 mode_label = ['OFF','ON'][dstore.mode]
3352 3352 print 'Doctest mode is:', mode_label
3353 3353
3354 3354 def magic_gui(self, parameter_s=''):
3355 3355 """Enable or disable IPython GUI event loop integration.
3356 3356
3357 3357 %gui [GUINAME]
3358 3358
3359 3359 This magic replaces IPython's threaded shells that were activated
3360 3360 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3361 3361 can now be enabled, disabled and changed at runtime and keyboard
3362 3362 interrupts should work without any problems. The following toolkits
3363 3363 are supported: wxPython, PyQt4, PyGTK, and Tk::
3364 3364
3365 3365 %gui wx # enable wxPython event loop integration
3366 3366 %gui qt4|qt # enable PyQt4 event loop integration
3367 3367 %gui gtk # enable PyGTK event loop integration
3368 3368 %gui tk # enable Tk event loop integration
3369 3369 %gui # disable all event loop integration
3370 3370
3371 3371 WARNING: after any of these has been called you can simply create
3372 3372 an application object, but DO NOT start the event loop yourself, as
3373 3373 we have already handled that.
3374 3374 """
3375 3375 from IPython.lib.inputhook import enable_gui
3376 3376 opts, arg = self.parse_options(parameter_s, '')
3377 3377 if arg=='': arg = None
3378 3378 return enable_gui(arg)
3379 3379
3380 3380 def magic_load_ext(self, module_str):
3381 3381 """Load an IPython extension by its module name."""
3382 3382 return self.extension_manager.load_extension(module_str)
3383 3383
3384 3384 def magic_unload_ext(self, module_str):
3385 3385 """Unload an IPython extension by its module name."""
3386 3386 self.extension_manager.unload_extension(module_str)
3387 3387
3388 3388 def magic_reload_ext(self, module_str):
3389 3389 """Reload an IPython extension by its module name."""
3390 3390 self.extension_manager.reload_extension(module_str)
3391 3391
3392 3392 @skip_doctest
3393 3393 def magic_install_profiles(self, s):
3394 3394 """Install the default IPython profiles into the .ipython dir.
3395 3395
3396 3396 If the default profiles have already been installed, they will not
3397 3397 be overwritten. You can force overwriting them by using the ``-o``
3398 3398 option::
3399 3399
3400 3400 In [1]: %install_profiles -o
3401 3401 """
3402 3402 if '-o' in s:
3403 3403 overwrite = True
3404 3404 else:
3405 3405 overwrite = False
3406 3406 from IPython.config import profile
3407 3407 profile_dir = os.path.dirname(profile.__file__)
3408 3408 ipython_dir = self.ipython_dir
3409 3409 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3410 3410 for src in os.listdir(profile_dir):
3411 3411 if src.startswith('profile_'):
3412 3412 name = src.replace('profile_', '')
3413 3413 print " %s"%name
3414 3414 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3415 3415 pd.copy_config_file('ipython_config.py', path=src,
3416 3416 overwrite=overwrite)
3417 3417
3418 3418 @skip_doctest
3419 3419 def magic_install_default_config(self, s):
3420 3420 """Install IPython's default config file into the .ipython dir.
3421 3421
3422 3422 If the default config file (:file:`ipython_config.py`) is already
3423 3423 installed, it will not be overwritten. You can force overwriting
3424 3424 by using the ``-o`` option::
3425 3425
3426 3426 In [1]: %install_default_config
3427 3427 """
3428 3428 if '-o' in s:
3429 3429 overwrite = True
3430 3430 else:
3431 3431 overwrite = False
3432 3432 pd = self.shell.profile_dir
3433 3433 print "Installing default config file in: %s" % pd.location
3434 3434 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3435 3435
3436 3436 # Pylab support: simple wrappers that activate pylab, load gui input
3437 3437 # handling and modify slightly %run
3438 3438
3439 3439 @skip_doctest
3440 3440 def _pylab_magic_run(self, parameter_s=''):
3441 3441 Magic.magic_run(self, parameter_s,
3442 3442 runner=mpl_runner(self.shell.safe_execfile))
3443 3443
3444 3444 _pylab_magic_run.__doc__ = magic_run.__doc__
3445 3445
3446 3446 @skip_doctest
3447 3447 def magic_pylab(self, s):
3448 3448 """Load numpy and matplotlib to work interactively.
3449 3449
3450 3450 %pylab [GUINAME]
3451 3451
3452 3452 This function lets you activate pylab (matplotlib, numpy and
3453 3453 interactive support) at any point during an IPython session.
3454 3454
3455 3455 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3456 3456 pylab and mlab, as well as all names from numpy and pylab.
3457 3457
3458 3458 If you are using the inline matplotlib backend for embedded figures,
3459 3459 you can adjust its behavior via the %config magic::
3460 3460
3461 3461 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3462 3462 In [1]: %config InlineBackend.figure_format = 'svg'
3463 3463
3464 3464 # change the behavior of closing all figures at the end of each
3465 3465 # execution (cell), or allowing reuse of active figures across
3466 3466 # cells:
3467 3467 In [2]: %config InlineBackend.close_figures = False
3468 3468
3469 3469 Parameters
3470 3470 ----------
3471 3471 guiname : optional
3472 3472 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3473 3473 'tk'). If given, the corresponding Matplotlib backend is used,
3474 3474 otherwise matplotlib's default (which you can override in your
3475 3475 matplotlib config file) is used.
3476 3476
3477 3477 Examples
3478 3478 --------
3479 3479 In this case, where the MPL default is TkAgg::
3480 3480
3481 3481 In [2]: %pylab
3482 3482
3483 3483 Welcome to pylab, a matplotlib-based Python environment.
3484 3484 Backend in use: TkAgg
3485 3485 For more information, type 'help(pylab)'.
3486 3486
3487 3487 But you can explicitly request a different backend::
3488 3488
3489 3489 In [3]: %pylab qt
3490 3490
3491 3491 Welcome to pylab, a matplotlib-based Python environment.
3492 3492 Backend in use: Qt4Agg
3493 3493 For more information, type 'help(pylab)'.
3494 3494 """
3495 3495
3496 3496 if Application.initialized():
3497 3497 app = Application.instance()
3498 3498 try:
3499 3499 import_all_status = app.pylab_import_all
3500 3500 except AttributeError:
3501 3501 import_all_status = True
3502 3502 else:
3503 3503 import_all_status = True
3504 3504
3505 3505 self.shell.enable_pylab(s,import_all=import_all_status)
3506 3506
3507 3507 def magic_tb(self, s):
3508 3508 """Print the last traceback with the currently active exception mode.
3509 3509
3510 3510 See %xmode for changing exception reporting modes."""
3511 3511 self.shell.showtraceback()
3512 3512
3513 3513 @skip_doctest
3514 3514 def magic_precision(self, s=''):
3515 3515 """Set floating point precision for pretty printing.
3516 3516
3517 3517 Can set either integer precision or a format string.
3518 3518
3519 3519 If numpy has been imported and precision is an int,
3520 3520 numpy display precision will also be set, via ``numpy.set_printoptions``.
3521 3521
3522 3522 If no argument is given, defaults will be restored.
3523 3523
3524 3524 Examples
3525 3525 --------
3526 3526 ::
3527 3527
3528 3528 In [1]: from math import pi
3529 3529
3530 3530 In [2]: %precision 3
3531 3531 Out[2]: u'%.3f'
3532 3532
3533 3533 In [3]: pi
3534 3534 Out[3]: 3.142
3535 3535
3536 3536 In [4]: %precision %i
3537 3537 Out[4]: u'%i'
3538 3538
3539 3539 In [5]: pi
3540 3540 Out[5]: 3
3541 3541
3542 3542 In [6]: %precision %e
3543 3543 Out[6]: u'%e'
3544 3544
3545 3545 In [7]: pi**10
3546 3546 Out[7]: 9.364805e+04
3547 3547
3548 3548 In [8]: %precision
3549 3549 Out[8]: u'%r'
3550 3550
3551 3551 In [9]: pi**10
3552 3552 Out[9]: 93648.047476082982
3553 3553
3554 3554 """
3555 3555
3556 3556 ptformatter = self.shell.display_formatter.formatters['text/plain']
3557 3557 ptformatter.float_precision = s
3558 3558 return ptformatter.float_format
3559 3559
3560 3560
3561 3561 @magic_arguments.magic_arguments()
3562 3562 @magic_arguments.argument(
3563 3563 '-e', '--export', action='store_true', default=False,
3564 3564 help='Export IPython history as a notebook. The filename argument '
3565 3565 'is used to specify the notebook name and format. For example '
3566 3566 'a filename of notebook.ipynb will result in a notebook name '
3567 3567 'of "notebook" and a format of "xml". Likewise using a ".json" '
3568 3568 'or ".py" file extension will write the notebook in the json '
3569 3569 'or py formats.'
3570 3570 )
3571 3571 @magic_arguments.argument(
3572 3572 '-f', '--format',
3573 3573 help='Convert an existing IPython notebook to a new format. This option '
3574 3574 'specifies the new format and can have the values: xml, json, py. '
3575 3575 'The target filename is choosen automatically based on the new '
3576 3576 'format. The filename argument gives the name of the source file.'
3577 3577 )
3578 3578 @magic_arguments.argument(
3579 3579 'filename', type=unicode,
3580 3580 help='Notebook name or filename'
3581 3581 )
3582 3582 def magic_notebook(self, s):
3583 3583 """Export and convert IPython notebooks.
3584 3584
3585 3585 This function can export the current IPython history to a notebook file
3586 3586 or can convert an existing notebook file into a different format. For
3587 3587 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3588 3588 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3589 3589 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3590 3590 formats include (json/ipynb, py).
3591 3591 """
3592 3592 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3593 3593
3594 3594 from IPython.nbformat import current
3595 3595 args.filename = unquote_filename(args.filename)
3596 3596 if args.export:
3597 3597 fname, name, format = current.parse_filename(args.filename)
3598 3598 cells = []
3599 3599 hist = list(self.history_manager.get_range())
3600 3600 for session, prompt_number, input in hist[:-1]:
3601 3601 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3602 3602 worksheet = current.new_worksheet(cells=cells)
3603 3603 nb = current.new_notebook(name=name,worksheets=[worksheet])
3604 3604 with open(fname, 'w') as f:
3605 3605 current.write(nb, f, format);
3606 3606 elif args.format is not None:
3607 3607 old_fname, old_name, old_format = current.parse_filename(args.filename)
3608 3608 new_format = args.format
3609 3609 if new_format == u'xml':
3610 3610 raise ValueError('Notebooks cannot be written as xml.')
3611 3611 elif new_format == u'ipynb' or new_format == u'json':
3612 3612 new_fname = old_name + u'.ipynb'
3613 3613 new_format = u'json'
3614 3614 elif new_format == u'py':
3615 3615 new_fname = old_name + u'.py'
3616 3616 else:
3617 3617 raise ValueError('Invalid notebook format: %s' % new_format)
3618 3618 with open(old_fname, 'r') as f:
3619 3619 s = f.read()
3620 3620 try:
3621 3621 nb = current.reads(s, old_format)
3622 3622 except:
3623 3623 nb = current.reads(s, u'xml')
3624 3624 with open(new_fname, 'w') as f:
3625 3625 current.write(nb, f, new_format)
3626 3626
3627 3627 def magic_config(self, s):
3628 3628 """configure IPython
3629 3629
3630 3630 %config Class[.trait=value]
3631 3631
3632 3632 This magic exposes most of the IPython config system. Any
3633 3633 Configurable class should be able to be configured with the simple
3634 3634 line::
3635 3635
3636 3636 %config Class.trait=value
3637 3637
3638 3638 Where `value` will be resolved in the user's namespace, if it is an
3639 3639 expression or variable name.
3640 3640
3641 3641 Examples
3642 3642 --------
3643 3643
3644 3644 To see what classes are availabe for config, pass no arguments::
3645 3645
3646 3646 In [1]: %config
3647 3647 Available objects for config:
3648 3648 TerminalInteractiveShell
3649 3649 HistoryManager
3650 3650 PrefilterManager
3651 3651 AliasManager
3652 3652 IPCompleter
3653 3653 DisplayFormatter
3654 3654
3655 3655 To view what is configurable on a given class, just pass the class name::
3656 3656
3657 3657 In [2]: %config IPCompleter
3658 3658 IPCompleter options
3659 3659 -----------------
3660 IPCompleter.omit__names=<Enum>
3661 Current: 2
3662 Choices: (0, 1, 2)
3663 Instruct the completer to omit private method names
3664 Specifically, when completing on ``object.<tab>``.
3665 When 2 [default]: all names that start with '_' will be excluded.
3666 When 1: all 'magic' names (``__foo__``) will be excluded.
3667 When 0: nothing will be excluded.
3668 IPCompleter.merge_completions=<CBool>
3669 Current: True
3670 Whether to merge completion results into a single list
3671 If False, only the completion results from the first non-empty completer
3672 will be returned.
3660 3673 IPCompleter.greedy=<CBool>
3661 3674 Current: False
3662 3675 Activate greedy completion
3663 3676 This will enable completion on elements of lists, results of function calls,
3664 3677 etc., but can be unsafe because the code is actually evaluated on TAB.
3665 3678
3666 3679 but the real use is in setting values::
3667 3680
3668 3681 In [3]: %config IPCompleter.greedy = True
3669 3682
3670 3683 and these values are read from the user_ns if they are variables::
3671 3684
3672 3685 In [4]: feeling_greedy=False
3673 3686
3674 3687 In [5]: %config IPCompleter.greedy = feeling_greedy
3675 3688
3676 3689 """
3677 3690 from IPython.config.loader import Config
3678 3691 # get list of class names for configurables that have someting to configure:
3679 3692 classnames = [ c.__class__.__name__ for c in self.configurables if c.__class__.class_traits(config=True) ]
3680 3693 line = s.strip()
3681 3694 if not line:
3682 3695 # print available configurable names
3683 3696 print "Available objects for config:"
3684 3697 for name in classnames:
3685 3698 print " ", name
3686 3699 return
3687 3700 elif line in classnames:
3688 3701 # `%config TerminalInteractiveShell` will print trait info for
3689 3702 # TerminalInteractiveShell
3690 3703 c = self.configurables[classnames.index(line)]
3691 3704 cls = c.__class__
3692 3705 help = cls.class_get_help(c)
3693 3706 # strip leading '--' from cl-args:
3694 3707 help = re.sub(r'^\-\-', '', help, flags=re.MULTILINE)
3695 3708 print help
3696 3709 return
3697 3710 elif '=' not in line:
3698 3711 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
3699 3712
3700 3713
3701 3714 # otherwise, assume we are setting configurables.
3702 3715 # leave quotes on args when splitting, because we want
3703 3716 # unquoted args to eval in user_ns
3704 3717 cfg = Config()
3705 3718 exec "cfg."+line in locals(), self.user_ns
3706 3719
3707 3720 for configurable in self.configurables:
3708 3721 try:
3709 3722 configurable.update_config(cfg)
3710 3723 except Exception as e:
3711 3724 error(e)
3712 3725
3713 3726 # end Magic
@@ -1,207 +1,232 b''
1 1 """Tests for the IPython tab-completion machinery.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Module imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # stdlib
8 8 import os
9 9 import sys
10 10 import unittest
11 11
12 12 # third party
13 13 import nose.tools as nt
14 14
15 15 # our own packages
16 from IPython.config.loader import Config
16 17 from IPython.core import completer
17 18 from IPython.external.decorators import knownfailureif
18 19 from IPython.utils.tempdir import TemporaryDirectory
19 20 from IPython.utils.generics import complete_object
20 21
21 22 #-----------------------------------------------------------------------------
22 23 # Test functions
23 24 #-----------------------------------------------------------------------------
24 25 def test_protect_filename():
25 26 pairs = [ ('abc','abc'),
26 27 (' abc',r'\ abc'),
27 28 ('a bc',r'a\ bc'),
28 29 ('a bc',r'a\ \ bc'),
29 30 (' bc',r'\ \ bc'),
30 31 ]
31 32 # On posix, we also protect parens and other special characters
32 33 if sys.platform != 'win32':
33 34 pairs.extend( [('a(bc',r'a\(bc'),
34 35 ('a)bc',r'a\)bc'),
35 36 ('a( )bc',r'a\(\ \)bc'),
36 37 ('a[1]bc', r'a\[1\]bc'),
37 38 ('a{1}bc', r'a\{1\}bc'),
38 39 ('a#bc', r'a\#bc'),
39 40 ('a?bc', r'a\?bc'),
40 41 ('a=bc', r'a\=bc'),
41 42 ('a\\bc', r'a\\bc'),
42 43 ('a|bc', r'a\|bc'),
43 44 ('a;bc', r'a\;bc'),
44 45 ('a:bc', r'a\:bc'),
45 46 ("a'bc", r"a\'bc"),
46 47 ('a*bc', r'a\*bc'),
47 48 ('a"bc', r'a\"bc'),
48 49 ('a^bc', r'a\^bc'),
49 50 ('a&bc', r'a\&bc'),
50 51 ] )
51 52 # run the actual tests
52 53 for s1, s2 in pairs:
53 54 s1p = completer.protect_filename(s1)
54 55 nt.assert_equals(s1p, s2)
55 56
56 57
57 58 def check_line_split(splitter, test_specs):
58 59 for part1, part2, split in test_specs:
59 60 cursor_pos = len(part1)
60 61 line = part1+part2
61 62 out = splitter.split_line(line, cursor_pos)
62 63 nt.assert_equal(out, split)
63 64
64 65
65 66 def test_line_split():
66 67 """Basice line splitter test with default specs."""
67 68 sp = completer.CompletionSplitter()
68 69 # The format of the test specs is: part1, part2, expected answer. Parts 1
69 70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
70 71 # was at the end of part1. So an empty part2 represents someone hitting
71 72 # tab at the end of the line, the most common case.
72 73 t = [('run some/scrip', '', 'some/scrip'),
73 74 ('run scripts/er', 'ror.py foo', 'scripts/er'),
74 75 ('echo $HOM', '', 'HOM'),
75 76 ('print sys.pa', '', 'sys.pa'),
76 77 ('print(sys.pa', '', 'sys.pa'),
77 78 ("execfile('scripts/er", '', 'scripts/er'),
78 79 ('a[x.', '', 'x.'),
79 80 ('a[x.', 'y', 'x.'),
80 81 ('cd "some_file/', '', 'some_file/'),
81 82 ]
82 83 check_line_split(sp, t)
83 84 # Ensure splitting works OK with unicode by re-running the tests with
84 85 # all inputs turned into unicode
85 86 check_line_split(sp, [ map(unicode, p) for p in t] )
86 87
87 88 def test_custom_completion_error():
88 89 """Test that errors from custom attribute completers are silenced."""
89 90 ip = get_ipython()
90 91 class A(object): pass
91 92 ip.user_ns['a'] = A()
92 93
93 94 @complete_object.when_type(A)
94 95 def complete_A(a, existing_completions):
95 96 raise TypeError("this should be silenced")
96 97
97 98 ip.complete("a.")
98 99
99 100
100 101 def test_unicode_completions():
101 102 ip = get_ipython()
102 103 # Some strings that trigger different types of completion. Check them both
103 104 # in str and unicode forms
104 105 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
105 106 for t in s + map(unicode, s):
106 107 # We don't need to check exact completion values (they may change
107 108 # depending on the state of the namespace, but at least no exceptions
108 109 # should be thrown and the return value should be a pair of text, list
109 110 # values.
110 111 text, matches = ip.complete(t)
111 112 nt.assert_true(isinstance(text, basestring))
112 113 nt.assert_true(isinstance(matches, list))
113 114
114 115
115 116 class CompletionSplitterTestCase(unittest.TestCase):
116 117 def setUp(self):
117 118 self.sp = completer.CompletionSplitter()
118 119
119 120 def test_delim_setting(self):
120 121 self.sp.set_delims(' ')
121 122 nt.assert_equal(self.sp.get_delims(), ' ')
122 123 nt.assert_equal(self.sp._delim_expr, '[\ ]')
123 124
124 125 def test_spaces(self):
125 126 """Test with only spaces as split chars."""
126 127 self.sp.delims = ' '
127 128 t = [('foo', '', 'foo'),
128 129 ('run foo', '', 'foo'),
129 130 ('run foo', 'bar', 'foo'),
130 131 ]
131 132 check_line_split(self.sp, t)
132 133
133 134
134 135 def test_has_open_quotes1():
135 136 for s in ["'", "'''", "'hi' '"]:
136 137 nt.assert_equal(completer.has_open_quotes(s), "'")
137 138
138 139
139 140 def test_has_open_quotes2():
140 141 for s in ['"', '"""', '"hi" "']:
141 142 nt.assert_equal(completer.has_open_quotes(s), '"')
142 143
143 144
144 145 def test_has_open_quotes3():
145 146 for s in ["''", "''' '''", "'hi' 'ipython'"]:
146 147 nt.assert_false(completer.has_open_quotes(s))
147 148
148 149
149 150 def test_has_open_quotes4():
150 151 for s in ['""', '""" """', '"hi" "ipython"']:
151 152 nt.assert_false(completer.has_open_quotes(s))
152 153
153 154 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
154 155 def test_abspath_file_completions():
155 156 ip = get_ipython()
156 157 with TemporaryDirectory() as tmpdir:
157 158 prefix = os.path.join(tmpdir, 'foo')
158 159 suffixes = map(str, [1,2])
159 160 names = [prefix+s for s in suffixes]
160 161 for n in names:
161 162 open(n, 'w').close()
162 163
163 164 # Check simple completion
164 165 c = ip.complete(prefix)[1]
165 166 nt.assert_equal(c, names)
166 167
167 168 # Now check with a function call
168 169 cmd = 'a = f("%s' % prefix
169 170 c = ip.complete(prefix, cmd)[1]
170 171 comp = [prefix+s for s in suffixes]
171 172 nt.assert_equal(c, comp)
172 173
173 174 def test_local_file_completions():
174 175 ip = get_ipython()
175 176 cwd = os.getcwdu()
176 177 try:
177 178 with TemporaryDirectory() as tmpdir:
178 179 os.chdir(tmpdir)
179 180 prefix = './foo'
180 181 suffixes = map(str, [1,2])
181 182 names = [prefix+s for s in suffixes]
182 183 for n in names:
183 184 open(n, 'w').close()
184 185
185 186 # Check simple completion
186 187 c = ip.complete(prefix)[1]
187 188 nt.assert_equal(c, names)
188 189
189 190 # Now check with a function call
190 191 cmd = 'a = f("%s' % prefix
191 192 c = ip.complete(prefix, cmd)[1]
192 193 comp = [prefix+s for s in suffixes]
193 194 nt.assert_equal(c, comp)
194 195 finally:
195 196 # prevent failures from making chdir stick
196 197 os.chdir(cwd)
197 198
198 199 def test_greedy_completions():
199 200 ip = get_ipython()
200 201 ip.Completer.greedy = False
201 202 ip.ex('a=range(5)')
202 203 _,c = ip.complete('.',line='a[0].')
203 204 nt.assert_false('a[0].real' in c, "Shouldn't have completed on a[0]: %s"%c)
204 205 ip.Completer.greedy = True
205 206 _,c = ip.complete('.',line='a[0].')
206 207 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
207 208
209 def test_omit__names():
210 # also happens to test IPCompleter as a configurable
211 ip = get_ipython()
212 ip._hidden_attr = 1
213 c = ip.Completer
214 ip.ex('ip=get_ipython()')
215 cfg = Config()
216 cfg.IPCompleter.omit__names = 0
217 c.update_config(cfg)
218 s,matches = c.complete('ip.')
219 nt.assert_true('ip.__str__' in matches)
220 nt.assert_true('ip._hidden_attr' in matches)
221 cfg.IPCompleter.omit__names = 1
222 c.update_config(cfg)
223 s,matches = c.complete('ip.')
224 nt.assert_false('ip.__str__' in matches)
225 nt.assert_true('ip._hidden_attr' in matches)
226 cfg.IPCompleter.omit__names = 2
227 c.update_config(cfg)
228 s,matches = c.complete('ip.')
229 nt.assert_false('ip.__str__' in matches)
230 nt.assert_false('ip._hidden_attr' in matches)
231 del ip._hidden_attr
232 No newline at end of file
@@ -1,396 +1,396 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 7 Authors
8 8 -------
9 9
10 10 * Brian Granger
11 11 * Fernando Perez
12 12 * Min Ragan-Kelley
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2010 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 from __future__ import absolute_import
27 27
28 28 import logging
29 29 import os
30 30 import sys
31 31
32 32 from IPython.config.loader import (
33 33 Config, PyFileConfigLoader, ConfigFileNotFound
34 34 )
35 35 from IPython.config.application import boolean_flag, catch_config_error
36 36 from IPython.core import release
37 37 from IPython.core import usage
38 from IPython.core.completer import Completer
38 from IPython.core.completer import IPCompleter
39 39 from IPython.core.crashhandler import CrashHandler
40 40 from IPython.core.formatters import PlainTextFormatter
41 41 from IPython.core.application import (
42 42 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
43 43 )
44 44 from IPython.core.shellapp import (
45 45 InteractiveShellApp, shell_flags, shell_aliases
46 46 )
47 47 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
48 48 from IPython.lib import inputhook
49 49 from IPython.utils import warn
50 50 from IPython.utils.path import get_ipython_dir, check_for_old_config
51 51 from IPython.utils.traitlets import (
52 52 Bool, List, Dict, CaselessStrEnum
53 53 )
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Globals, utilities and helpers
57 57 #-----------------------------------------------------------------------------
58 58
59 59 #: The default config file name for this application.
60 60 default_config_file_name = u'ipython_config.py'
61 61
62 62 _examples = """
63 63 ipython --pylab # start in pylab mode
64 64 ipython --pylab=qt # start in pylab mode with the qt4 backend
65 65 ipython --log-level=DEBUG # set logging to DEBUG
66 66 ipython --profile=foo # start with profile foo
67 67
68 68 ipython qtconsole # start the qtconsole GUI application
69 69 ipython qtconsole -h # show the help string for the qtconsole subcmd
70 70
71 71 ipython profile create foo # create profile foo w/ default config files
72 72 ipython profile -h # show the help string for the profile subcmd
73 73 """
74 74
75 75 #-----------------------------------------------------------------------------
76 76 # Crash handler for this application
77 77 #-----------------------------------------------------------------------------
78 78
79 79 class IPAppCrashHandler(CrashHandler):
80 80 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
81 81
82 82 def __init__(self, app):
83 83 contact_name = release.authors['Fernando'][0]
84 84 contact_email = release.authors['Fernando'][1]
85 85 bug_tracker = 'http://github.com/ipython/ipython/issues'
86 86 super(IPAppCrashHandler,self).__init__(
87 87 app, contact_name, contact_email, bug_tracker
88 88 )
89 89
90 90 def make_report(self,traceback):
91 91 """Return a string containing a crash report."""
92 92
93 93 sec_sep = self.section_sep
94 94 # Start with parent report
95 95 report = [super(IPAppCrashHandler, self).make_report(traceback)]
96 96 # Add interactive-specific info we may have
97 97 rpt_add = report.append
98 98 try:
99 99 rpt_add(sec_sep+"History of session input:")
100 100 for line in self.app.shell.user_ns['_ih']:
101 101 rpt_add(line)
102 102 rpt_add('\n*** Last line of input (may not be in above history):\n')
103 103 rpt_add(self.app.shell._last_input_line+'\n')
104 104 except:
105 105 pass
106 106
107 107 return ''.join(report)
108 108
109 109 #-----------------------------------------------------------------------------
110 110 # Aliases and Flags
111 111 #-----------------------------------------------------------------------------
112 112 flags = dict(base_flags)
113 113 flags.update(shell_flags)
114 114 addflag = lambda *args: flags.update(boolean_flag(*args))
115 115 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
116 116 'Turn on auto editing of files with syntax errors.',
117 117 'Turn off auto editing of files with syntax errors.'
118 118 )
119 119 addflag('banner', 'TerminalIPythonApp.display_banner',
120 120 "Display a banner upon starting IPython.",
121 121 "Don't display a banner upon starting IPython."
122 122 )
123 123 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
124 124 """Set to confirm when you try to exit IPython with an EOF (Control-D
125 125 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
126 126 you can force a direct exit without any confirmation.""",
127 127 "Don't prompt the user when exiting."
128 128 )
129 129 addflag('term-title', 'TerminalInteractiveShell.term_title',
130 130 "Enable auto setting the terminal title.",
131 131 "Disable auto setting the terminal title."
132 132 )
133 133 classic_config = Config()
134 134 classic_config.InteractiveShell.cache_size = 0
135 135 classic_config.PlainTextFormatter.pprint = False
136 136 classic_config.InteractiveShell.prompt_in1 = '>>> '
137 137 classic_config.InteractiveShell.prompt_in2 = '... '
138 138 classic_config.InteractiveShell.prompt_out = ''
139 139 classic_config.InteractiveShell.separate_in = ''
140 140 classic_config.InteractiveShell.separate_out = ''
141 141 classic_config.InteractiveShell.separate_out2 = ''
142 142 classic_config.InteractiveShell.colors = 'NoColor'
143 143 classic_config.InteractiveShell.xmode = 'Plain'
144 144
145 145 flags['classic']=(
146 146 classic_config,
147 147 "Gives IPython a similar feel to the classic Python prompt."
148 148 )
149 149 # # log doesn't make so much sense this way anymore
150 150 # paa('--log','-l',
151 151 # action='store_true', dest='InteractiveShell.logstart',
152 152 # help="Start logging to the default log file (./ipython_log.py).")
153 153 #
154 154 # # quick is harder to implement
155 155 flags['quick']=(
156 156 {'TerminalIPythonApp' : {'quick' : True}},
157 157 "Enable quick startup with no config files."
158 158 )
159 159
160 160 flags['i'] = (
161 161 {'TerminalIPythonApp' : {'force_interact' : True}},
162 162 """If running code from the command line, become interactive afterwards.
163 163 Note: can also be given simply as '-i.'"""
164 164 )
165 165 flags['pylab'] = (
166 166 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
167 167 """Pre-load matplotlib and numpy for interactive use with
168 168 the default matplotlib backend."""
169 169 )
170 170
171 171 aliases = dict(base_aliases)
172 172 aliases.update(shell_aliases)
173 173
174 174 # it's possible we don't want short aliases for *all* of these:
175 175 aliases.update(dict(
176 176 gui='TerminalIPythonApp.gui',
177 177 pylab='TerminalIPythonApp.pylab',
178 178 ))
179 179
180 180 #-----------------------------------------------------------------------------
181 181 # Main classes and functions
182 182 #-----------------------------------------------------------------------------
183 183
184 184 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
185 185 name = u'ipython'
186 186 description = usage.cl_usage
187 187 default_config_file_name = default_config_file_name
188 188 crash_handler_class = IPAppCrashHandler
189 189 examples = _examples
190 190
191 191 flags = Dict(flags)
192 192 aliases = Dict(aliases)
193 193 classes = List()
194 194 def _classes_default(self):
195 195 """This has to be in a method, for TerminalIPythonApp to be available."""
196 196 return [
197 197 InteractiveShellApp, # ShellApp comes before TerminalApp, because
198 198 self.__class__, # it will also affect subclasses (e.g. QtConsole)
199 199 TerminalInteractiveShell,
200 200 ProfileDir,
201 201 PlainTextFormatter,
202 Completer,
202 IPCompleter,
203 203 ]
204 204
205 205 subcommands = Dict(dict(
206 206 qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp',
207 207 """Launch the IPython Qt Console."""
208 208 ),
209 209 notebook=('IPython.frontend.html.notebook.notebookapp.NotebookApp',
210 210 """Launch the IPython HTML Notebook Server"""
211 211 ),
212 212 profile = ("IPython.core.profileapp.ProfileApp",
213 213 "Create and manage IPython profiles."
214 214 ),
215 215 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
216 216 "Start a kernel without an attached frontend."
217 217 ),
218 218 ))
219 219
220 220 # *do* autocreate requested profile, but don't create the config file.
221 221 auto_create=Bool(True)
222 222 # configurables
223 223 ignore_old_config=Bool(False, config=True,
224 224 help="Suppress warning messages about legacy config files"
225 225 )
226 226 quick = Bool(False, config=True,
227 227 help="""Start IPython quickly by skipping the loading of config files."""
228 228 )
229 229 def _quick_changed(self, name, old, new):
230 230 if new:
231 231 self.load_config_file = lambda *a, **kw: None
232 232 self.ignore_old_config=True
233 233
234 234 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet'), config=True,
235 235 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet')."
236 236 )
237 237 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'],
238 238 config=True,
239 239 help="""Pre-load matplotlib and numpy for interactive use,
240 240 selecting a particular matplotlib backend and loop integration.
241 241 """
242 242 )
243 243 display_banner = Bool(True, config=True,
244 244 help="Whether to display a banner upon starting IPython."
245 245 )
246 246
247 247 # if there is code of files to run from the cmd line, don't interact
248 248 # unless the --i flag (App.force_interact) is true.
249 249 force_interact = Bool(False, config=True,
250 250 help="""If a command or file is given via the command-line,
251 251 e.g. 'ipython foo.py"""
252 252 )
253 253 def _force_interact_changed(self, name, old, new):
254 254 if new:
255 255 self.interact = True
256 256
257 257 def _file_to_run_changed(self, name, old, new):
258 258 if new and not self.force_interact:
259 259 self.interact = False
260 260 _code_to_run_changed = _file_to_run_changed
261 261
262 262 # internal, not-configurable
263 263 interact=Bool(True)
264 264
265 265
266 266 def parse_command_line(self, argv=None):
267 267 """override to allow old '-pylab' flag with deprecation warning"""
268 268
269 269 argv = sys.argv[1:] if argv is None else argv
270 270
271 271 if '-pylab' in argv:
272 272 # deprecated `-pylab` given,
273 273 # warn and transform into current syntax
274 274 argv = argv[:] # copy, don't clobber
275 275 idx = argv.index('-pylab')
276 276 warn.warn("`-pylab` flag has been deprecated.\n"
277 277 " Use `--pylab` instead, or `--pylab=foo` to specify a backend.")
278 278 sub = '--pylab'
279 279 if len(argv) > idx+1:
280 280 # check for gui arg, as in '-pylab qt'
281 281 gui = argv[idx+1]
282 282 if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'):
283 283 sub = '--pylab='+gui
284 284 argv.pop(idx+1)
285 285 argv[idx] = sub
286 286
287 287 return super(TerminalIPythonApp, self).parse_command_line(argv)
288 288
289 289 @catch_config_error
290 290 def initialize(self, argv=None):
291 291 """Do actions after construct, but before starting the app."""
292 292 super(TerminalIPythonApp, self).initialize(argv)
293 293 if self.subapp is not None:
294 294 # don't bother initializing further, starting subapp
295 295 return
296 296 if not self.ignore_old_config:
297 297 check_for_old_config(self.ipython_dir)
298 298 # print self.extra_args
299 299 if self.extra_args:
300 300 self.file_to_run = self.extra_args[0]
301 301 # create the shell
302 302 self.init_shell()
303 303 # and draw the banner
304 304 self.init_banner()
305 305 # Now a variety of things that happen after the banner is printed.
306 306 self.init_gui_pylab()
307 307 self.init_extensions()
308 308 self.init_code()
309 309
310 310 def init_shell(self):
311 311 """initialize the InteractiveShell instance"""
312 312 # I am a little hesitant to put these into InteractiveShell itself.
313 313 # But that might be the place for them
314 314 sys.path.insert(0, '')
315 315
316 316 # Create an InteractiveShell instance.
317 317 # shell.display_banner should always be False for the terminal
318 318 # based app, because we call shell.show_banner() by hand below
319 319 # so the banner shows *before* all extension loading stuff.
320 320 self.shell = TerminalInteractiveShell.instance(config=self.config,
321 321 display_banner=False, profile_dir=self.profile_dir,
322 322 ipython_dir=self.ipython_dir)
323 323
324 324 def init_banner(self):
325 325 """optionally display the banner"""
326 326 if self.display_banner and self.interact:
327 327 self.shell.show_banner()
328 328 # Make sure there is a space below the banner.
329 329 if self.log_level <= logging.INFO: print
330 330
331 331
332 332 def init_gui_pylab(self):
333 333 """Enable GUI event loop integration, taking pylab into account."""
334 334 gui = self.gui
335 335
336 336 # Using `pylab` will also require gui activation, though which toolkit
337 337 # to use may be chosen automatically based on mpl configuration.
338 338 if self.pylab:
339 339 activate = self.shell.enable_pylab
340 340 if self.pylab == 'auto':
341 341 gui = None
342 342 else:
343 343 gui = self.pylab
344 344 else:
345 345 # Enable only GUI integration, no pylab
346 346 activate = inputhook.enable_gui
347 347
348 348 if gui or self.pylab:
349 349 try:
350 350 self.log.info("Enabling GUI event loop integration, "
351 351 "toolkit=%s, pylab=%s" % (gui, self.pylab) )
352 352 if self.pylab:
353 353 activate(gui, import_all=self.pylab_import_all)
354 354 else:
355 355 activate(gui)
356 356 except:
357 357 self.log.warn("Error in enabling GUI event loop integration:")
358 358 self.shell.showtraceback()
359 359
360 360 def start(self):
361 361 if self.subapp is not None:
362 362 return self.subapp.start()
363 363 # perform any prexec steps:
364 364 if self.interact:
365 365 self.log.debug("Starting IPython's mainloop...")
366 366 self.shell.mainloop()
367 367 else:
368 368 self.log.debug("IPython not interactive...")
369 369
370 370
371 371 def load_default_config(ipython_dir=None):
372 372 """Load the default config file from the default ipython_dir.
373 373
374 374 This is useful for embedded shells.
375 375 """
376 376 if ipython_dir is None:
377 377 ipython_dir = get_ipython_dir()
378 378 profile_dir = os.path.join(ipython_dir, 'profile_default')
379 379 cl = PyFileConfigLoader(default_config_file_name, profile_dir)
380 380 try:
381 381 config = cl.load_config()
382 382 except ConfigFileNotFound:
383 383 # no config found
384 384 config = Config()
385 385 return config
386 386
387 387
388 388 def launch_new_instance():
389 389 """Create and run a full blown IPython instance"""
390 390 app = TerminalIPythonApp.instance()
391 391 app.initialize()
392 392 app.start()
393 393
394 394
395 395 if __name__ == '__main__':
396 396 launch_new_instance()
General Comments 0
You need to be logged in to leave comments. Login now