##// END OF EJS Templates
Improvements to docs formatting.
Thomas Kluyver -
Show More
@@ -1,979 +1,979 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 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
31 31
32 32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
34 __getattr__ hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
33 application defined code to be executed if an object with a
34 ``__getattr__`` hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
38 38
39 39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
43 its input.
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
43 its input.
44 44
45 45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
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 IPython Development Team
57 57 # Copyright (C) 2001 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
65 65 #-----------------------------------------------------------------------------
66 66 # Imports
67 67 #-----------------------------------------------------------------------------
68 68
69 69 import __builtin__
70 70 import __main__
71 71 import glob
72 72 import inspect
73 73 import itertools
74 74 import keyword
75 75 import os
76 76 import re
77 77 import sys
78 78
79 79 from IPython.config.configurable import Configurable
80 80 from IPython.core.error import TryNext
81 81 from IPython.core.inputsplitter import ESC_MAGIC
82 82 from IPython.utils import generics
83 83 from IPython.utils import io
84 84 from IPython.utils.dir2 import dir2
85 85 from IPython.utils.process import arg_split
86 86 from IPython.utils.traitlets import CBool, Enum
87 87
88 88 #-----------------------------------------------------------------------------
89 89 # Globals
90 90 #-----------------------------------------------------------------------------
91 91
92 92 # Public API
93 93 __all__ = ['Completer','IPCompleter']
94 94
95 95 if sys.platform == 'win32':
96 96 PROTECTABLES = ' '
97 97 else:
98 98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
99 99
100 100 #-----------------------------------------------------------------------------
101 101 # Main functions and classes
102 102 #-----------------------------------------------------------------------------
103 103
104 104 def has_open_quotes(s):
105 105 """Return whether a string has open quotes.
106 106
107 107 This simply counts whether the number of quote characters of either type in
108 108 the string is odd.
109 109
110 110 Returns
111 111 -------
112 112 If there is an open quote, the quote character is returned. Else, return
113 113 False.
114 114 """
115 115 # We check " first, then ', so complex cases with nested quotes will get
116 116 # the " to take precedence.
117 117 if s.count('"') % 2:
118 118 return '"'
119 119 elif s.count("'") % 2:
120 120 return "'"
121 121 else:
122 122 return False
123 123
124 124
125 125 def protect_filename(s):
126 126 """Escape a string to protect certain characters."""
127 127
128 128 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
129 129 for ch in s])
130 130
131 131 def expand_user(path):
132 132 """Expand '~'-style usernames in strings.
133 133
134 134 This is similar to :func:`os.path.expanduser`, but it computes and returns
135 135 extra information that will be useful if the input was being used in
136 136 computing completions, and you wish to return the completions with the
137 137 original '~' instead of its expanded value.
138 138
139 139 Parameters
140 140 ----------
141 141 path : str
142 142 String to be expanded. If no ~ is present, the output is the same as the
143 143 input.
144 144
145 145 Returns
146 146 -------
147 147 newpath : str
148 148 Result of ~ expansion in the input path.
149 149 tilde_expand : bool
150 150 Whether any expansion was performed or not.
151 151 tilde_val : str
152 152 The value that ~ was replaced with.
153 153 """
154 154 # Default values
155 155 tilde_expand = False
156 156 tilde_val = ''
157 157 newpath = path
158 158
159 159 if path.startswith('~'):
160 160 tilde_expand = True
161 161 rest = len(path)-1
162 162 newpath = os.path.expanduser(path)
163 163 if rest:
164 164 tilde_val = newpath[:-rest]
165 165 else:
166 166 tilde_val = newpath
167 167
168 168 return newpath, tilde_expand, tilde_val
169 169
170 170
171 171 def compress_user(path, tilde_expand, tilde_val):
172 172 """Does the opposite of expand_user, with its outputs.
173 173 """
174 174 if tilde_expand:
175 175 return path.replace(tilde_val, '~')
176 176 else:
177 177 return path
178 178
179 179
180 180 class Bunch(object): pass
181 181
182 182
183 183 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
184 184 GREEDY_DELIMS = ' =\r\n'
185 185
186 186
187 187 class CompletionSplitter(object):
188 188 """An object to split an input line in a manner similar to readline.
189 189
190 190 By having our own implementation, we can expose readline-like completion in
191 191 a uniform manner to all frontends. This object only needs to be given the
192 192 line of text to be split and the cursor position on said line, and it
193 193 returns the 'word' to be completed on at the cursor after splitting the
194 194 entire line.
195 195
196 196 What characters are used as splitting delimiters can be controlled by
197 197 setting the `delims` attribute (this is a property that internally
198 198 automatically builds the necessary regular expression)"""
199 199
200 200 # Private interface
201 201
202 202 # A string of delimiter characters. The default value makes sense for
203 203 # IPython's most typical usage patterns.
204 204 _delims = DELIMS
205 205
206 206 # The expression (a normal string) to be compiled into a regular expression
207 207 # for actual splitting. We store it as an attribute mostly for ease of
208 208 # debugging, since this type of code can be so tricky to debug.
209 209 _delim_expr = None
210 210
211 211 # The regular expression that does the actual splitting
212 212 _delim_re = None
213 213
214 214 def __init__(self, delims=None):
215 215 delims = CompletionSplitter._delims if delims is None else delims
216 216 self.delims = delims
217 217
218 218 @property
219 219 def delims(self):
220 220 """Return the string of delimiter characters."""
221 221 return self._delims
222 222
223 223 @delims.setter
224 224 def delims(self, delims):
225 225 """Set the delimiters for line splitting."""
226 226 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
227 227 self._delim_re = re.compile(expr)
228 228 self._delims = delims
229 229 self._delim_expr = expr
230 230
231 231 def split_line(self, line, cursor_pos=None):
232 232 """Split a line of text with a cursor at the given position.
233 233 """
234 234 l = line if cursor_pos is None else line[:cursor_pos]
235 235 return self._delim_re.split(l)[-1]
236 236
237 237
238 238 class Completer(Configurable):
239 239
240 240 greedy = CBool(False, config=True,
241 241 help="""Activate greedy completion
242 242
243 243 This will enable completion on elements of lists, results of function calls, etc.,
244 244 but can be unsafe because the code is actually evaluated on TAB.
245 245 """
246 246 )
247 247
248 248
249 249 def __init__(self, namespace=None, global_namespace=None, **kwargs):
250 250 """Create a new completer for the command line.
251 251
252 252 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
253 253
254 254 If unspecified, the default namespace where completions are performed
255 255 is __main__ (technically, __main__.__dict__). Namespaces should be
256 256 given as dictionaries.
257 257
258 258 An optional second namespace can be given. This allows the completer
259 259 to handle cases where both the local and global scopes need to be
260 260 distinguished.
261 261
262 262 Completer instances should be used as the completion mechanism of
263 263 readline via the set_completer() call:
264 264
265 265 readline.set_completer(Completer(my_namespace).complete)
266 266 """
267 267
268 268 # Don't bind to namespace quite yet, but flag whether the user wants a
269 269 # specific namespace or to use __main__.__dict__. This will allow us
270 270 # to bind to __main__.__dict__ at completion time, not now.
271 271 if namespace is None:
272 272 self.use_main_ns = 1
273 273 else:
274 274 self.use_main_ns = 0
275 275 self.namespace = namespace
276 276
277 277 # The global namespace, if given, can be bound directly
278 278 if global_namespace is None:
279 279 self.global_namespace = {}
280 280 else:
281 281 self.global_namespace = global_namespace
282 282
283 283 super(Completer, self).__init__(**kwargs)
284 284
285 285 def complete(self, text, state):
286 286 """Return the next possible completion for 'text'.
287 287
288 288 This is called successively with state == 0, 1, 2, ... until it
289 289 returns None. The completion should begin with 'text'.
290 290
291 291 """
292 292 if self.use_main_ns:
293 293 self.namespace = __main__.__dict__
294 294
295 295 if state == 0:
296 296 if "." in text:
297 297 self.matches = self.attr_matches(text)
298 298 else:
299 299 self.matches = self.global_matches(text)
300 300 try:
301 301 return self.matches[state]
302 302 except IndexError:
303 303 return None
304 304
305 305 def global_matches(self, text):
306 306 """Compute matches when text is a simple name.
307 307
308 308 Return a list of all keywords, built-in functions and names currently
309 309 defined in self.namespace or self.global_namespace that match.
310 310
311 311 """
312 312 #print 'Completer->global_matches, txt=%r' % text # dbg
313 313 matches = []
314 314 match_append = matches.append
315 315 n = len(text)
316 316 for lst in [keyword.kwlist,
317 317 __builtin__.__dict__.keys(),
318 318 self.namespace.keys(),
319 319 self.global_namespace.keys()]:
320 320 for word in lst:
321 321 if word[:n] == text and word != "__builtins__":
322 322 match_append(word)
323 323 return matches
324 324
325 325 def attr_matches(self, text):
326 326 """Compute matches when text contains a dot.
327 327
328 328 Assuming the text is of the form NAME.NAME....[NAME], and is
329 329 evaluatable in self.namespace or self.global_namespace, it will be
330 330 evaluated and its attributes (as revealed by dir()) are used as
331 331 possible completions. (For class instances, class members are are
332 332 also considered.)
333 333
334 334 WARNING: this can still invoke arbitrary C code, if an object
335 335 with a __getattr__ hook is evaluated.
336 336
337 337 """
338 338
339 339 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
340 340 # Another option, seems to work great. Catches things like ''.<tab>
341 341 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
342 342
343 343 if m:
344 344 expr, attr = m.group(1, 3)
345 345 elif self.greedy:
346 346 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
347 347 if not m2:
348 348 return []
349 349 expr, attr = m2.group(1,2)
350 350 else:
351 351 return []
352 352
353 353 try:
354 354 obj = eval(expr, self.namespace)
355 355 except:
356 356 try:
357 357 obj = eval(expr, self.global_namespace)
358 358 except:
359 359 return []
360 360
361 361 if self.limit_to__all__ and hasattr(obj, '__all__'):
362 362 words = get__all__entries(obj)
363 363 else:
364 364 words = dir2(obj)
365 365
366 366 try:
367 367 words = generics.complete_object(obj, words)
368 368 except TryNext:
369 369 pass
370 370 except Exception:
371 371 # Silence errors from completion function
372 372 #raise # dbg
373 373 pass
374 374 # Build match list to return
375 375 n = len(attr)
376 376 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
377 377 return res
378 378
379 379
380 380 def get__all__entries(obj):
381 381 """returns the strings in the __all__ attribute"""
382 382 try:
383 383 words = getattr(obj, '__all__')
384 384 except:
385 385 return []
386 386
387 387 return [w for w in words if isinstance(w, basestring)]
388 388
389 389
390 390 class IPCompleter(Completer):
391 391 """Extension of the completer class with IPython-specific features"""
392 392
393 393 def _greedy_changed(self, name, old, new):
394 394 """update the splitter and readline delims when greedy is changed"""
395 395 if new:
396 396 self.splitter.delims = GREEDY_DELIMS
397 397 else:
398 398 self.splitter.delims = DELIMS
399 399
400 400 if self.readline:
401 401 self.readline.set_completer_delims(self.splitter.delims)
402 402
403 403 merge_completions = CBool(True, config=True,
404 404 help="""Whether to merge completion results into a single list
405 405
406 406 If False, only the completion results from the first non-empty
407 407 completer will be returned.
408 408 """
409 409 )
410 410 omit__names = Enum((0,1,2), default_value=2, config=True,
411 411 help="""Instruct the completer to omit private method names
412 412
413 413 Specifically, when completing on ``object.<tab>``.
414 414
415 415 When 2 [default]: all names that start with '_' will be excluded.
416 416
417 417 When 1: all 'magic' names (``__foo__``) will be excluded.
418 418
419 419 When 0: nothing will be excluded.
420 420 """
421 421 )
422 422 limit_to__all__ = CBool(default_value=False, config=True,
423 423 help="""Instruct the completer to use __all__ for the completion
424 424
425 425 Specifically, when completing on ``object.<tab>``.
426 426
427 427 When True: only those names in obj.__all__ will be included.
428 428
429 429 When False [default]: the __all__ attribute is ignored
430 430 """
431 431 )
432 432
433 433 def __init__(self, shell=None, namespace=None, global_namespace=None,
434 434 alias_table=None, use_readline=True,
435 435 config=None, **kwargs):
436 436 """IPCompleter() -> completer
437 437
438 438 Return a completer object suitable for use by the readline library
439 439 via readline.set_completer().
440 440
441 441 Inputs:
442 442
443 443 - shell: a pointer to the ipython shell itself. This is needed
444 because this completer knows about magic functions, and those can
445 only be accessed via the ipython instance.
444 because this completer knows about magic functions, and those can
445 only be accessed via the ipython instance.
446 446
447 447 - namespace: an optional dict where completions are performed.
448 448
449 449 - global_namespace: secondary optional dict for completions, to
450 handle cases (such as IPython embedded inside functions) where
451 both Python scopes are visible.
450 handle cases (such as IPython embedded inside functions) where
451 both Python scopes are visible.
452 452
453 453 - If alias_table is supplied, it should be a dictionary of aliases
454 to complete.
454 to complete.
455 455
456 456 use_readline : bool, optional
457 457 If true, use the readline library. This completer can still function
458 458 without readline, though in that case callers must provide some extra
459 459 information on each call about the current line."""
460 460
461 461 self.magic_escape = ESC_MAGIC
462 462 self.splitter = CompletionSplitter()
463 463
464 464 # Readline configuration, only used by the rlcompleter method.
465 465 if use_readline:
466 466 # We store the right version of readline so that later code
467 467 import IPython.utils.rlineimpl as readline
468 468 self.readline = readline
469 469 else:
470 470 self.readline = None
471 471
472 472 # _greedy_changed() depends on splitter and readline being defined:
473 473 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
474 474 config=config, **kwargs)
475 475
476 476 # List where completion matches will be stored
477 477 self.matches = []
478 478 self.shell = shell
479 479 if alias_table is None:
480 480 alias_table = {}
481 481 self.alias_table = alias_table
482 482 # Regexp to split filenames with spaces in them
483 483 self.space_name_re = re.compile(r'([^\\] )')
484 484 # Hold a local ref. to glob.glob for speed
485 485 self.glob = glob.glob
486 486
487 487 # Determine if we are running on 'dumb' terminals, like (X)Emacs
488 488 # buffers, to avoid completion problems.
489 489 term = os.environ.get('TERM','xterm')
490 490 self.dumb_terminal = term in ['dumb','emacs']
491 491
492 492 # Special handling of backslashes needed in win32 platforms
493 493 if sys.platform == "win32":
494 494 self.clean_glob = self._clean_glob_win32
495 495 else:
496 496 self.clean_glob = self._clean_glob
497 497
498 498 #regexp to parse docstring for function signature
499 499 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
500 500 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
501 501 #use this if positional argument name is also needed
502 502 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
503 503
504 504 # All active matcher routines for completion
505 505 self.matchers = [self.python_matches,
506 506 self.file_matches,
507 507 self.magic_matches,
508 508 self.alias_matches,
509 509 self.python_func_kw_matches,
510 510 ]
511 511
512 512 def all_completions(self, text):
513 513 """
514 514 Wrapper around the complete method for the benefit of emacs
515 515 and pydb.
516 516 """
517 517 return self.complete(text)[1]
518 518
519 519 def _clean_glob(self,text):
520 520 return self.glob("%s*" % text)
521 521
522 522 def _clean_glob_win32(self,text):
523 523 return [f.replace("\\","/")
524 524 for f in self.glob("%s*" % text)]
525 525
526 526 def file_matches(self, text):
527 527 """Match filenames, expanding ~USER type strings.
528 528
529 529 Most of the seemingly convoluted logic in this completer is an
530 530 attempt to handle filenames with spaces in them. And yet it's not
531 531 quite perfect, because Python's readline doesn't expose all of the
532 532 GNU readline details needed for this to be done correctly.
533 533
534 534 For a filename with a space in it, the printed completions will be
535 535 only the parts after what's already been typed (instead of the
536 536 full completions, as is normally done). I don't think with the
537 537 current (as of Python 2.3) Python readline it's possible to do
538 538 better."""
539 539
540 540 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
541 541
542 542 # chars that require escaping with backslash - i.e. chars
543 543 # that readline treats incorrectly as delimiters, but we
544 544 # don't want to treat as delimiters in filename matching
545 545 # when escaped with backslash
546 546 if text.startswith('!'):
547 547 text = text[1:]
548 548 text_prefix = '!'
549 549 else:
550 550 text_prefix = ''
551 551
552 552 text_until_cursor = self.text_until_cursor
553 553 # track strings with open quotes
554 554 open_quotes = has_open_quotes(text_until_cursor)
555 555
556 556 if '(' in text_until_cursor or '[' in text_until_cursor:
557 557 lsplit = text
558 558 else:
559 559 try:
560 560 # arg_split ~ shlex.split, but with unicode bugs fixed by us
561 561 lsplit = arg_split(text_until_cursor)[-1]
562 562 except ValueError:
563 563 # typically an unmatched ", or backslash without escaped char.
564 564 if open_quotes:
565 565 lsplit = text_until_cursor.split(open_quotes)[-1]
566 566 else:
567 567 return []
568 568 except IndexError:
569 569 # tab pressed on empty line
570 570 lsplit = ""
571 571
572 572 if not open_quotes and lsplit != protect_filename(lsplit):
573 573 # if protectables are found, do matching on the whole escaped name
574 574 has_protectables = True
575 575 text0,text = text,lsplit
576 576 else:
577 577 has_protectables = False
578 578 text = os.path.expanduser(text)
579 579
580 580 if text == "":
581 581 return [text_prefix + protect_filename(f) for f in self.glob("*")]
582 582
583 583 # Compute the matches from the filesystem
584 584 m0 = self.clean_glob(text.replace('\\',''))
585 585
586 586 if has_protectables:
587 587 # If we had protectables, we need to revert our changes to the
588 588 # beginning of filename so that we don't double-write the part
589 589 # of the filename we have so far
590 590 len_lsplit = len(lsplit)
591 591 matches = [text_prefix + text0 +
592 592 protect_filename(f[len_lsplit:]) for f in m0]
593 593 else:
594 594 if open_quotes:
595 595 # if we have a string with an open quote, we don't need to
596 596 # protect the names at all (and we _shouldn't_, as it
597 597 # would cause bugs when the filesystem call is made).
598 598 matches = m0
599 599 else:
600 600 matches = [text_prefix +
601 601 protect_filename(f) for f in m0]
602 602
603 603 #io.rprint('mm', matches) # dbg
604 604
605 605 # Mark directories in input list by appending '/' to their names.
606 606 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
607 607 return matches
608 608
609 609 def magic_matches(self, text):
610 610 """Match magics"""
611 611 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
612 612 # Get all shell magics now rather than statically, so magics loaded at
613 613 # runtime show up too.
614 614 lsm = self.shell.magics_manager.lsmagic()
615 615 line_magics = lsm['line']
616 616 cell_magics = lsm['cell']
617 617 pre = self.magic_escape
618 618 pre2 = pre+pre
619 619
620 620 # Completion logic:
621 621 # - user gives %%: only do cell magics
622 622 # - user gives %: do both line and cell magics
623 623 # - no prefix: do both
624 624 # In other words, line magics are skipped if the user gives %% explicitly
625 625 bare_text = text.lstrip(pre)
626 626 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
627 627 if not text.startswith(pre2):
628 628 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
629 629 return comp
630 630
631 631 def alias_matches(self, text):
632 632 """Match internal system aliases"""
633 633 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
634 634
635 635 # if we are not in the first 'item', alias matching
636 636 # doesn't make sense - unless we are starting with 'sudo' command.
637 637 main_text = self.text_until_cursor.lstrip()
638 638 if ' ' in main_text and not main_text.startswith('sudo'):
639 639 return []
640 640 text = os.path.expanduser(text)
641 641 aliases = self.alias_table.keys()
642 642 if text == '':
643 643 return aliases
644 644 else:
645 645 return [a for a in aliases if a.startswith(text)]
646 646
647 647 def python_matches(self,text):
648 648 """Match attributes or global python names"""
649 649
650 650 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
651 651 if "." in text:
652 652 try:
653 653 matches = self.attr_matches(text)
654 654 if text.endswith('.') and self.omit__names:
655 655 if self.omit__names == 1:
656 656 # true if txt is _not_ a __ name, false otherwise:
657 657 no__name = (lambda txt:
658 658 re.match(r'.*\.__.*?__',txt) is None)
659 659 else:
660 660 # true if txt is _not_ a _ name, false otherwise:
661 661 no__name = (lambda txt:
662 662 re.match(r'.*\._.*?',txt) is None)
663 663 matches = filter(no__name, matches)
664 664 except NameError:
665 665 # catches <undefined attributes>.<tab>
666 666 matches = []
667 667 else:
668 668 matches = self.global_matches(text)
669 669
670 670 return matches
671 671
672 672 def _default_arguments_from_docstring(self, doc):
673 673 """Parse the first line of docstring for call signature.
674 674
675 675 Docstring should be of the form 'min(iterable[, key=func])\n'.
676 676 It can also parse cython docstring of the form
677 677 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
678 678 """
679 679 if doc is None:
680 680 return []
681 681
682 682 #care only the firstline
683 683 line = doc.lstrip().splitlines()[0]
684 684
685 685 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
686 686 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
687 687 sig = self.docstring_sig_re.search(line)
688 688 if sig is None:
689 689 return []
690 690 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
691 691 sig = sig.groups()[0].split(',')
692 692 ret = []
693 693 for s in sig:
694 694 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
695 695 ret += self.docstring_kwd_re.findall(s)
696 696 return ret
697 697
698 698 def _default_arguments(self, obj):
699 699 """Return the list of default arguments of obj if it is callable,
700 700 or empty list otherwise."""
701 701 call_obj = obj
702 702 ret = []
703 703 if inspect.isbuiltin(obj):
704 704 pass
705 705 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
706 706 if inspect.isclass(obj):
707 707 #for cython embededsignature=True the constructor docstring
708 708 #belongs to the object itself not __init__
709 709 ret += self._default_arguments_from_docstring(
710 710 getattr(obj, '__doc__', ''))
711 711 # for classes, check for __init__,__new__
712 712 call_obj = (getattr(obj, '__init__', None) or
713 713 getattr(obj, '__new__', None))
714 714 # for all others, check if they are __call__able
715 715 elif hasattr(obj, '__call__'):
716 716 call_obj = obj.__call__
717 717
718 718 ret += self._default_arguments_from_docstring(
719 719 getattr(call_obj, '__doc__', ''))
720 720
721 721 try:
722 722 args,_,_1,defaults = inspect.getargspec(call_obj)
723 723 if defaults:
724 724 ret+=args[-len(defaults):]
725 725 except TypeError:
726 726 pass
727 727
728 728 return list(set(ret))
729 729
730 730 def python_func_kw_matches(self,text):
731 731 """Match named parameters (kwargs) of the last open function"""
732 732
733 733 if "." in text: # a parameter cannot be dotted
734 734 return []
735 735 try: regexp = self.__funcParamsRegex
736 736 except AttributeError:
737 737 regexp = self.__funcParamsRegex = re.compile(r'''
738 738 '.*?(?<!\\)' | # single quoted strings or
739 739 ".*?(?<!\\)" | # double quoted strings or
740 740 \w+ | # identifier
741 741 \S # other characters
742 742 ''', re.VERBOSE | re.DOTALL)
743 743 # 1. find the nearest identifier that comes before an unclosed
744 744 # parenthesis before the cursor
745 745 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
746 746 tokens = regexp.findall(self.text_until_cursor)
747 747 tokens.reverse()
748 748 iterTokens = iter(tokens); openPar = 0
749 749
750 750 for token in iterTokens:
751 751 if token == ')':
752 752 openPar -= 1
753 753 elif token == '(':
754 754 openPar += 1
755 755 if openPar > 0:
756 756 # found the last unclosed parenthesis
757 757 break
758 758 else:
759 759 return []
760 760 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
761 761 ids = []
762 762 isId = re.compile(r'\w+$').match
763 763
764 764 while True:
765 765 try:
766 766 ids.append(next(iterTokens))
767 767 if not isId(ids[-1]):
768 768 ids.pop(); break
769 769 if not next(iterTokens) == '.':
770 770 break
771 771 except StopIteration:
772 772 break
773 773 # lookup the candidate callable matches either using global_matches
774 774 # or attr_matches for dotted names
775 775 if len(ids) == 1:
776 776 callableMatches = self.global_matches(ids[0])
777 777 else:
778 778 callableMatches = self.attr_matches('.'.join(ids[::-1]))
779 779 argMatches = []
780 780 for callableMatch in callableMatches:
781 781 try:
782 782 namedArgs = self._default_arguments(eval(callableMatch,
783 783 self.namespace))
784 784 except:
785 785 continue
786 786
787 787 for namedArg in namedArgs:
788 788 if namedArg.startswith(text):
789 789 argMatches.append("%s=" %namedArg)
790 790 return argMatches
791 791
792 792 def dispatch_custom_completer(self, text):
793 793 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
794 794 line = self.line_buffer
795 795 if not line.strip():
796 796 return None
797 797
798 798 # Create a little structure to pass all the relevant information about
799 799 # the current completion to any custom completer.
800 800 event = Bunch()
801 801 event.line = line
802 802 event.symbol = text
803 803 cmd = line.split(None,1)[0]
804 804 event.command = cmd
805 805 event.text_until_cursor = self.text_until_cursor
806 806
807 807 #print "\ncustom:{%s]\n" % event # dbg
808 808
809 809 # for foo etc, try also to find completer for %foo
810 810 if not cmd.startswith(self.magic_escape):
811 811 try_magic = self.custom_completers.s_matches(
812 812 self.magic_escape + cmd)
813 813 else:
814 814 try_magic = []
815 815
816 816 for c in itertools.chain(self.custom_completers.s_matches(cmd),
817 817 try_magic,
818 818 self.custom_completers.flat_matches(self.text_until_cursor)):
819 819 #print "try",c # dbg
820 820 try:
821 821 res = c(event)
822 822 if res:
823 823 # first, try case sensitive match
824 824 withcase = [r for r in res if r.startswith(text)]
825 825 if withcase:
826 826 return withcase
827 827 # if none, then case insensitive ones are ok too
828 828 text_low = text.lower()
829 829 return [r for r in res if r.lower().startswith(text_low)]
830 830 except TryNext:
831 831 pass
832 832
833 833 return None
834 834
835 835 def complete(self, text=None, line_buffer=None, cursor_pos=None):
836 836 """Find completions for the given text and line context.
837 837
838 838 This is called successively with state == 0, 1, 2, ... until it
839 839 returns None. The completion should begin with 'text'.
840 840
841 841 Note that both the text and the line_buffer are optional, but at least
842 842 one of them must be given.
843 843
844 844 Parameters
845 845 ----------
846 846 text : string, optional
847 847 Text to perform the completion on. If not given, the line buffer
848 848 is split using the instance's CompletionSplitter object.
849 849
850 850 line_buffer : string, optional
851 851 If not given, the completer attempts to obtain the current line
852 852 buffer via readline. This keyword allows clients which are
853 853 requesting for text completions in non-readline contexts to inform
854 854 the completer of the entire text.
855 855
856 856 cursor_pos : int, optional
857 857 Index of the cursor in the full line buffer. Should be provided by
858 858 remote frontends where kernel has no access to frontend state.
859 859
860 860 Returns
861 861 -------
862 862 text : str
863 863 Text that was actually used in the completion.
864 864
865 865 matches : list
866 866 A list of completion matches.
867 867 """
868 868 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
869 869
870 870 # if the cursor position isn't given, the only sane assumption we can
871 871 # make is that it's at the end of the line (the common case)
872 872 if cursor_pos is None:
873 873 cursor_pos = len(line_buffer) if text is None else len(text)
874 874
875 875 # if text is either None or an empty string, rely on the line buffer
876 876 if not text:
877 877 text = self.splitter.split_line(line_buffer, cursor_pos)
878 878
879 879 # If no line buffer is given, assume the input text is all there was
880 880 if line_buffer is None:
881 881 line_buffer = text
882 882
883 883 self.line_buffer = line_buffer
884 884 self.text_until_cursor = self.line_buffer[:cursor_pos]
885 885 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
886 886
887 887 # Start with a clean slate of completions
888 888 self.matches[:] = []
889 889 custom_res = self.dispatch_custom_completer(text)
890 890 if custom_res is not None:
891 891 # did custom completers produce something?
892 892 self.matches = custom_res
893 893 else:
894 894 # Extend the list of completions with the results of each
895 895 # matcher, so we return results to the user from all
896 896 # namespaces.
897 897 if self.merge_completions:
898 898 self.matches = []
899 899 for matcher in self.matchers:
900 900 try:
901 901 self.matches.extend(matcher(text))
902 902 except:
903 903 # Show the ugly traceback if the matcher causes an
904 904 # exception, but do NOT crash the kernel!
905 905 sys.excepthook(*sys.exc_info())
906 906 else:
907 907 for matcher in self.matchers:
908 908 self.matches = matcher(text)
909 909 if self.matches:
910 910 break
911 911 # FIXME: we should extend our api to return a dict with completions for
912 912 # different types of objects. The rlcomplete() method could then
913 913 # simply collapse the dict into a list for readline, but we'd have
914 914 # richer completion semantics in other evironments.
915 915 self.matches = sorted(set(self.matches))
916 916 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
917 917 return text, self.matches
918 918
919 919 def rlcomplete(self, text, state):
920 920 """Return the state-th possible completion for 'text'.
921 921
922 922 This is called successively with state == 0, 1, 2, ... until it
923 923 returns None. The completion should begin with 'text'.
924 924
925 925 Parameters
926 926 ----------
927 927 text : string
928 928 Text to perform the completion on.
929 929
930 930 state : int
931 931 Counter used by readline.
932 932 """
933 933 if state==0:
934 934
935 935 self.line_buffer = line_buffer = self.readline.get_line_buffer()
936 936 cursor_pos = self.readline.get_endidx()
937 937
938 938 #io.rprint("\nRLCOMPLETE: %r %r %r" %
939 939 # (text, line_buffer, cursor_pos) ) # dbg
940 940
941 941 # if there is only a tab on a line with only whitespace, instead of
942 942 # the mostly useless 'do you want to see all million completions'
943 943 # message, just do the right thing and give the user his tab!
944 944 # Incidentally, this enables pasting of tabbed text from an editor
945 945 # (as long as autoindent is off).
946 946
947 947 # It should be noted that at least pyreadline still shows file
948 948 # completions - is there a way around it?
949 949
950 950 # don't apply this on 'dumb' terminals, such as emacs buffers, so
951 951 # we don't interfere with their own tab-completion mechanism.
952 952 if not (self.dumb_terminal or line_buffer.strip()):
953 953 self.readline.insert_text('\t')
954 954 sys.stdout.flush()
955 955 return None
956 956
957 957 # Note: debugging exceptions that may occur in completion is very
958 958 # tricky, because readline unconditionally silences them. So if
959 959 # during development you suspect a bug in the completion code, turn
960 960 # this flag on temporarily by uncommenting the second form (don't
961 961 # flip the value in the first line, as the '# dbg' marker can be
962 962 # automatically detected and is used elsewhere).
963 963 DEBUG = False
964 964 #DEBUG = True # dbg
965 965 if DEBUG:
966 966 try:
967 967 self.complete(text, line_buffer, cursor_pos)
968 968 except:
969 969 import traceback; traceback.print_exc()
970 970 else:
971 971 # The normal production version is here
972 972
973 973 # This method computes the self.matches array
974 974 self.complete(text, line_buffer, cursor_pos)
975 975
976 976 try:
977 977 return self.matches[state]
978 978 except IndexError:
979 979 return None
@@ -1,579 +1,584 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 http://www.python.org/2.2.3/license.html"""
17 17
18 18 #*****************************************************************************
19 19 #
20 20 # This file is licensed under the PSF license.
21 21 #
22 22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 24 #
25 25 #
26 26 #*****************************************************************************
27 27 from __future__ import print_function
28 28
29 29 import bdb
30 30 import functools
31 31 import linecache
32 32 import sys
33 33
34 34 from IPython import get_ipython
35 35 from IPython.utils import PyColorize, ulinecache
36 36 from IPython.utils import coloransi, io, py3compat
37 37 from IPython.core.excolors import exception_colors
38 38 from IPython.testing.skipdoctest import skip_doctest
39 39
40 40 # See if we can use pydb.
41 41 has_pydb = False
42 42 prompt = 'ipdb> '
43 43 #We have to check this directly from sys.argv, config struct not yet available
44 44 if '--pydb' in sys.argv:
45 45 try:
46 46 import pydb
47 47 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
48 48 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
49 49 # better protect against it.
50 50 has_pydb = True
51 51 except ImportError:
52 52 print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available")
53 53
54 54 if has_pydb:
55 55 from pydb import Pdb as OldPdb
56 56 #print "Using pydb for %run -d and post-mortem" #dbg
57 57 prompt = 'ipydb> '
58 58 else:
59 59 from pdb import Pdb as OldPdb
60 60
61 61 # Allow the set_trace code to operate outside of an ipython instance, even if
62 62 # it does so with some limitations. The rest of this support is implemented in
63 63 # the Tracer constructor.
64 64 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
65 65 """Exception hook which handles `BdbQuit` exceptions.
66 66
67 67 All other exceptions are processed using the `excepthook`
68 68 parameter.
69 69 """
70 70 if et==bdb.BdbQuit:
71 71 print('Exiting Debugger.')
72 72 elif excepthook is not None:
73 73 excepthook(et, ev, tb)
74 74 else:
75 75 # Backwards compatibility. Raise deprecation warning?
76 76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
77 77
78 78 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
79 79 print('Exiting Debugger.')
80 80
81 81
82 82 class Tracer(object):
83 83 """Class for local debugging, similar to pdb.set_trace.
84 84
85 85 Instances of this class, when called, behave like pdb.set_trace, but
86 86 providing IPython's enhanced capabilities.
87 87
88 88 This is implemented as a class which must be initialized in your own code
89 89 and not as a standalone function because we need to detect at runtime
90 90 whether IPython is already active or not. That detection is done in the
91 91 constructor, ensuring that this code plays nicely with a running IPython,
92 92 while functioning acceptably (though with limitations) if outside of it.
93 93 """
94 94
95 95 @skip_doctest
96 96 def __init__(self,colors=None):
97 97 """Create a local debugger instance.
98 98
99 :Parameters:
99 Parameters
100 ----------
100 101
101 - `colors` (None): a string containing the name of the color scheme to
102 use, it must be one of IPython's valid color schemes. If not given, the
103 function will default to the current IPython scheme when running inside
104 IPython, and to 'NoColor' otherwise.
102 colors : str, optional
103 The name of the color scheme to use, it must be one of IPython's
104 valid color schemes. If not given, the function will default to
105 the current IPython scheme when running inside IPython, and to
106 'NoColor' otherwise.
105 107
106 Usage example:
108 Examples
109 --------
110 ::
107 111
108 from IPython.core.debugger import Tracer; debug_here = Tracer()
112 from IPython.core.debugger import Tracer; debug_here = Tracer()
109 113
110 ... later in your code
111 debug_here() # -> will open up the debugger at that point.
114 Later in your code::
115
116 debug_here() # -> will open up the debugger at that point.
112 117
113 118 Once the debugger activates, you can use all of its regular commands to
114 119 step through code, set breakpoints, etc. See the pdb documentation
115 120 from the Python standard library for usage details.
116 121 """
117 122
118 123 ip = get_ipython()
119 124 if ip is None:
120 125 # Outside of ipython, we set our own exception hook manually
121 126 sys.excepthook = functools.partial(BdbQuit_excepthook,
122 127 excepthook=sys.excepthook)
123 128 def_colors = 'NoColor'
124 129 try:
125 130 # Limited tab completion support
126 131 import readline
127 132 readline.parse_and_bind('tab: complete')
128 133 except ImportError:
129 134 pass
130 135 else:
131 136 # In ipython, we use its custom exception handler mechanism
132 137 def_colors = ip.colors
133 138 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
134 139
135 140 if colors is None:
136 141 colors = def_colors
137 142
138 143 # The stdlib debugger internally uses a modified repr from the `repr`
139 144 # module, that limits the length of printed strings to a hardcoded
140 145 # limit of 30 characters. That much trimming is too aggressive, let's
141 146 # at least raise that limit to 80 chars, which should be enough for
142 147 # most interactive uses.
143 148 try:
144 149 from repr import aRepr
145 150 aRepr.maxstring = 80
146 151 except:
147 152 # This is only a user-facing convenience, so any error we encounter
148 153 # here can be warned about but can be otherwise ignored. These
149 154 # printouts will tell us about problems if this API changes
150 155 import traceback
151 156 traceback.print_exc()
152 157
153 158 self.debugger = Pdb(colors)
154 159
155 160 def __call__(self):
156 161 """Starts an interactive debugger at the point where called.
157 162
158 163 This is similar to the pdb.set_trace() function from the std lib, but
159 164 using IPython's enhanced debugger."""
160 165
161 166 self.debugger.set_trace(sys._getframe().f_back)
162 167
163 168
164 169 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
165 170 """Make new_fn have old_fn's doc string. This is particularly useful
166 171 for the ``do_...`` commands that hook into the help system.
167 172 Adapted from from a comp.lang.python posting
168 173 by Duncan Booth."""
169 174 def wrapper(*args, **kw):
170 175 return new_fn(*args, **kw)
171 176 if old_fn.__doc__:
172 177 wrapper.__doc__ = old_fn.__doc__ + additional_text
173 178 return wrapper
174 179
175 180
176 181 def _file_lines(fname):
177 182 """Return the contents of a named file as a list of lines.
178 183
179 184 This function never raises an IOError exception: if the file can't be
180 185 read, it simply returns an empty list."""
181 186
182 187 try:
183 188 outfile = open(fname)
184 189 except IOError:
185 190 return []
186 191 else:
187 192 out = outfile.readlines()
188 193 outfile.close()
189 194 return out
190 195
191 196
192 197 class Pdb(OldPdb):
193 198 """Modified Pdb class, does not load readline."""
194 199
195 200 def __init__(self,color_scheme='NoColor',completekey=None,
196 201 stdin=None, stdout=None):
197 202
198 203 # Parent constructor:
199 204 if has_pydb and completekey is None:
200 205 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
201 206 else:
202 207 OldPdb.__init__(self,completekey,stdin,stdout)
203 208
204 209 self.prompt = prompt # The default prompt is '(Pdb)'
205 210
206 211 # IPython changes...
207 212 self.is_pydb = has_pydb
208 213
209 214 self.shell = get_ipython()
210 215
211 216 if self.shell is None:
212 217 # No IPython instance running, we must create one
213 218 from IPython.terminal.interactiveshell import \
214 219 TerminalInteractiveShell
215 220 self.shell = TerminalInteractiveShell.instance()
216 221
217 222 if self.is_pydb:
218 223
219 224 # interactiveshell.py's ipalias seems to want pdb's checkline
220 225 # which located in pydb.fn
221 226 import pydb.fns
222 227 self.checkline = lambda filename, lineno: \
223 228 pydb.fns.checkline(self, filename, lineno)
224 229
225 230 self.curframe = None
226 231 self.do_restart = self.new_do_restart
227 232
228 233 self.old_all_completions = self.shell.Completer.all_completions
229 234 self.shell.Completer.all_completions=self.all_completions
230 235
231 236 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
232 237 OldPdb.do_list)
233 238 self.do_l = self.do_list
234 239 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
235 240 OldPdb.do_frame)
236 241
237 242 self.aliases = {}
238 243
239 244 # Create color table: we copy the default one from the traceback
240 245 # module and add a few attributes needed for debugging
241 246 self.color_scheme_table = exception_colors()
242 247
243 248 # shorthands
244 249 C = coloransi.TermColors
245 250 cst = self.color_scheme_table
246 251
247 252 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
248 253 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
249 254
250 255 cst['Linux'].colors.breakpoint_enabled = C.LightRed
251 256 cst['Linux'].colors.breakpoint_disabled = C.Red
252 257
253 258 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
254 259 cst['LightBG'].colors.breakpoint_disabled = C.Red
255 260
256 261 self.set_colors(color_scheme)
257 262
258 263 # Add a python parser so we can syntax highlight source while
259 264 # debugging.
260 265 self.parser = PyColorize.Parser()
261 266
262 267 def set_colors(self, scheme):
263 268 """Shorthand access to the color table scheme selector method."""
264 269 self.color_scheme_table.set_active_scheme(scheme)
265 270
266 271 def interaction(self, frame, traceback):
267 272 self.shell.set_completer_frame(frame)
268 273 while True:
269 274 try:
270 275 OldPdb.interaction(self, frame, traceback)
271 276 except KeyboardInterrupt:
272 277 self.shell.write("\nKeyboardInterrupt\n")
273 278 else:
274 279 break
275 280
276 281 def new_do_up(self, arg):
277 282 OldPdb.do_up(self, arg)
278 283 self.shell.set_completer_frame(self.curframe)
279 284 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
280 285
281 286 def new_do_down(self, arg):
282 287 OldPdb.do_down(self, arg)
283 288 self.shell.set_completer_frame(self.curframe)
284 289
285 290 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
286 291
287 292 def new_do_frame(self, arg):
288 293 OldPdb.do_frame(self, arg)
289 294 self.shell.set_completer_frame(self.curframe)
290 295
291 296 def new_do_quit(self, arg):
292 297
293 298 if hasattr(self, 'old_all_completions'):
294 299 self.shell.Completer.all_completions=self.old_all_completions
295 300
296 301
297 302 return OldPdb.do_quit(self, arg)
298 303
299 304 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
300 305
301 306 def new_do_restart(self, arg):
302 307 """Restart command. In the context of ipython this is exactly the same
303 308 thing as 'quit'."""
304 309 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
305 310 return self.do_quit(arg)
306 311
307 312 def postloop(self):
308 313 self.shell.set_completer_frame(None)
309 314
310 315 def print_stack_trace(self):
311 316 try:
312 317 for frame_lineno in self.stack:
313 318 self.print_stack_entry(frame_lineno, context = 5)
314 319 except KeyboardInterrupt:
315 320 pass
316 321
317 322 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
318 323 context = 3):
319 324 #frame, lineno = frame_lineno
320 325 print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout)
321 326
322 327 # vds: >>
323 328 frame, lineno = frame_lineno
324 329 filename = frame.f_code.co_filename
325 330 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
326 331 # vds: <<
327 332
328 333 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
329 334 import repr
330 335
331 336 ret = []
332 337
333 338 Colors = self.color_scheme_table.active_colors
334 339 ColorsNormal = Colors.Normal
335 340 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
336 341 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
337 342 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
338 343 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
339 344 ColorsNormal)
340 345
341 346 frame, lineno = frame_lineno
342 347
343 348 return_value = ''
344 349 if '__return__' in frame.f_locals:
345 350 rv = frame.f_locals['__return__']
346 351 #return_value += '->'
347 352 return_value += repr.repr(rv) + '\n'
348 353 ret.append(return_value)
349 354
350 355 #s = filename + '(' + `lineno` + ')'
351 356 filename = self.canonic(frame.f_code.co_filename)
352 357 link = tpl_link % py3compat.cast_unicode(filename)
353 358
354 359 if frame.f_code.co_name:
355 360 func = frame.f_code.co_name
356 361 else:
357 362 func = "<lambda>"
358 363
359 364 call = ''
360 365 if func != '?':
361 366 if '__args__' in frame.f_locals:
362 367 args = repr.repr(frame.f_locals['__args__'])
363 368 else:
364 369 args = '()'
365 370 call = tpl_call % (func, args)
366 371
367 372 # The level info should be generated in the same format pdb uses, to
368 373 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
369 374 if frame is self.curframe:
370 375 ret.append('> ')
371 376 else:
372 377 ret.append(' ')
373 378 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
374 379
375 380 start = lineno - 1 - context//2
376 381 lines = ulinecache.getlines(filename)
377 382 start = min(start, len(lines) - context)
378 383 start = max(start, 0)
379 384 lines = lines[start : start + context]
380 385
381 386 for i,line in enumerate(lines):
382 387 show_arrow = (start + 1 + i == lineno)
383 388 linetpl = (frame is self.curframe or show_arrow) \
384 389 and tpl_line_em \
385 390 or tpl_line
386 391 ret.append(self.__format_line(linetpl, filename,
387 392 start + 1 + i, line,
388 393 arrow = show_arrow) )
389 394 return ''.join(ret)
390 395
391 396 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
392 397 bp_mark = ""
393 398 bp_mark_color = ""
394 399
395 400 scheme = self.color_scheme_table.active_scheme_name
396 401 new_line, err = self.parser.format2(line, 'str', scheme)
397 402 if not err: line = new_line
398 403
399 404 bp = None
400 405 if lineno in self.get_file_breaks(filename):
401 406 bps = self.get_breaks(filename, lineno)
402 407 bp = bps[-1]
403 408
404 409 if bp:
405 410 Colors = self.color_scheme_table.active_colors
406 411 bp_mark = str(bp.number)
407 412 bp_mark_color = Colors.breakpoint_enabled
408 413 if not bp.enabled:
409 414 bp_mark_color = Colors.breakpoint_disabled
410 415
411 416 numbers_width = 7
412 417 if arrow:
413 418 # This is the line with the error
414 419 pad = numbers_width - len(str(lineno)) - len(bp_mark)
415 420 if pad >= 3:
416 421 marker = '-'*(pad-3) + '-> '
417 422 elif pad == 2:
418 423 marker = '> '
419 424 elif pad == 1:
420 425 marker = '>'
421 426 else:
422 427 marker = ''
423 428 num = '%s%s' % (marker, str(lineno))
424 429 line = tpl_line % (bp_mark_color + bp_mark, num, line)
425 430 else:
426 431 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
427 432 line = tpl_line % (bp_mark_color + bp_mark, num, line)
428 433
429 434 return line
430 435
431 436 def list_command_pydb(self, arg):
432 437 """List command to use if we have a newer pydb installed"""
433 438 filename, first, last = OldPdb.parse_list_cmd(self, arg)
434 439 if filename is not None:
435 440 self.print_list_lines(filename, first, last)
436 441
437 442 def print_list_lines(self, filename, first, last):
438 443 """The printing (as opposed to the parsing part of a 'list'
439 444 command."""
440 445 try:
441 446 Colors = self.color_scheme_table.active_colors
442 447 ColorsNormal = Colors.Normal
443 448 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
444 449 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
445 450 src = []
446 451 if filename == "<string>" and hasattr(self, "_exec_filename"):
447 452 filename = self._exec_filename
448 453
449 454 for lineno in range(first, last+1):
450 455 line = ulinecache.getline(filename, lineno)
451 456 if not line:
452 457 break
453 458
454 459 if lineno == self.curframe.f_lineno:
455 460 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
456 461 else:
457 462 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
458 463
459 464 src.append(line)
460 465 self.lineno = lineno
461 466
462 467 print(''.join(src), file=io.stdout)
463 468
464 469 except KeyboardInterrupt:
465 470 pass
466 471
467 472 def do_list(self, arg):
468 473 self.lastcmd = 'list'
469 474 last = None
470 475 if arg:
471 476 try:
472 477 x = eval(arg, {}, {})
473 478 if type(x) == type(()):
474 479 first, last = x
475 480 first = int(first)
476 481 last = int(last)
477 482 if last < first:
478 483 # Assume it's a count
479 484 last = first + last
480 485 else:
481 486 first = max(1, int(x) - 5)
482 487 except:
483 488 print('*** Error in argument:', repr(arg))
484 489 return
485 490 elif self.lineno is None:
486 491 first = max(1, self.curframe.f_lineno - 5)
487 492 else:
488 493 first = self.lineno + 1
489 494 if last is None:
490 495 last = first + 10
491 496 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
492 497
493 498 # vds: >>
494 499 lineno = first
495 500 filename = self.curframe.f_code.co_filename
496 501 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
497 502 # vds: <<
498 503
499 504 do_l = do_list
500 505
501 506 def do_pdef(self, arg):
502 507 """Print the call signature for any callable object.
503 508
504 509 The debugger interface to %pdef"""
505 510 namespaces = [('Locals', self.curframe.f_locals),
506 511 ('Globals', self.curframe.f_globals)]
507 512 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
508 513
509 514 def do_pdoc(self, arg):
510 515 """Print the docstring for an object.
511 516
512 517 The debugger interface to %pdoc."""
513 518 namespaces = [('Locals', self.curframe.f_locals),
514 519 ('Globals', self.curframe.f_globals)]
515 520 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
516 521
517 522 def do_pfile(self, arg):
518 523 """Print (or run through pager) the file where an object is defined.
519 524
520 525 The debugger interface to %pfile.
521 526 """
522 527 namespaces = [('Locals', self.curframe.f_locals),
523 528 ('Globals', self.curframe.f_globals)]
524 529 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
525 530
526 531 def do_pinfo(self, arg):
527 532 """Provide detailed information about an object.
528 533
529 534 The debugger interface to %pinfo, i.e., obj?."""
530 535 namespaces = [('Locals', self.curframe.f_locals),
531 536 ('Globals', self.curframe.f_globals)]
532 537 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
533 538
534 539 def do_pinfo2(self, arg):
535 540 """Provide extra detailed information about an object.
536 541
537 542 The debugger interface to %pinfo2, i.e., obj??."""
538 543 namespaces = [('Locals', self.curframe.f_locals),
539 544 ('Globals', self.curframe.f_globals)]
540 545 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
541 546
542 547 def do_psource(self, arg):
543 548 """Print (or run through pager) the source code for an object."""
544 549 namespaces = [('Locals', self.curframe.f_locals),
545 550 ('Globals', self.curframe.f_globals)]
546 551 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
547 552
548 553 def checkline(self, filename, lineno):
549 554 """Check whether specified line seems to be executable.
550 555
551 556 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
552 557 line or EOF). Warning: testing is not comprehensive.
553 558 """
554 559 #######################################################################
555 560 # XXX Hack! Use python-2.5 compatible code for this call, because with
556 561 # all of our changes, we've drifted from the pdb api in 2.6. For now,
557 562 # changing:
558 563 #
559 564 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
560 565 # to:
561 566 #
562 567 line = linecache.getline(filename, lineno)
563 568 #
564 569 # does the trick. But in reality, we need to fix this by reconciling
565 570 # our updates with the new Pdb APIs in Python 2.6.
566 571 #
567 572 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
568 573 #######################################################################
569 574
570 575 if not line:
571 576 print('End of file', file=self.stdout)
572 577 return 0
573 578 line = line.strip()
574 579 # Don't allow setting breakpoint at a blank line
575 580 if (not line or (line[0] == '#') or
576 581 (line[:3] == '"""') or line[:3] == "'''"):
577 582 print('*** Blank or comment', file=self.stdout)
578 583 return 0
579 584 return lineno
@@ -1,3150 +1,3151 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 absolute_import
18 18 from __future__ import print_function
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 functools
26 26 import os
27 27 import re
28 28 import runpy
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 from io import open as io_open
33 33
34 34 from IPython.config.configurable import SingletonConfigurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import magic
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager, AliasError
42 42 from IPython.core.autocall import ExitAutocall
43 43 from IPython.core.builtin_trap import BuiltinTrap
44 44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.payload import PayloadManager
57 57 from IPython.core.prefilter import PrefilterManager
58 58 from IPython.core.profiledir import ProfileDir
59 59 from IPython.core.prompts import PromptManager
60 60 from IPython.lib.latextools import LaTeXTool
61 61 from IPython.testing.skipdoctest import skip_doctest
62 62 from IPython.utils import PyColorize
63 63 from IPython.utils import io
64 64 from IPython.utils import py3compat
65 65 from IPython.utils import openpy
66 66 from IPython.utils.decorators import undoc
67 67 from IPython.utils.io import ask_yes_no
68 68 from IPython.utils.ipstruct import Struct
69 69 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
70 70 from IPython.utils.pickleshare import PickleShareDB
71 71 from IPython.utils.process import system, getoutput
72 72 from IPython.utils.strdispatch import StrDispatch
73 73 from IPython.utils.syspathcontext import prepended_to_syspath
74 74 from IPython.utils.text import (format_screen, LSString, SList,
75 75 DollarFormatter)
76 76 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
77 77 List, Unicode, Instance, Type)
78 78 from IPython.utils.warn import warn, error
79 79 import IPython.core.hooks
80 80
81 81 #-----------------------------------------------------------------------------
82 82 # Globals
83 83 #-----------------------------------------------------------------------------
84 84
85 85 # compiled regexps for autoindent management
86 86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 87
88 88 #-----------------------------------------------------------------------------
89 89 # Utilities
90 90 #-----------------------------------------------------------------------------
91 91
92 92 @undoc
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 @undoc
109 109 def no_op(*a, **kw): pass
110 110
111 111 @undoc
112 112 class NoOpContext(object):
113 113 def __enter__(self): pass
114 114 def __exit__(self, type, value, traceback): pass
115 115 no_op_context = NoOpContext()
116 116
117 117 class SpaceInInput(Exception): pass
118 118
119 119 @undoc
120 120 class Bunch: pass
121 121
122 122
123 123 def get_default_colors():
124 124 if sys.platform=='darwin':
125 125 return "LightBG"
126 126 elif os.name=='nt':
127 127 return 'Linux'
128 128 else:
129 129 return 'Linux'
130 130
131 131
132 132 class SeparateUnicode(Unicode):
133 133 """A Unicode subclass to validate separate_in, separate_out, etc.
134 134
135 135 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
136 136 """
137 137
138 138 def validate(self, obj, value):
139 139 if value == '0': value = ''
140 140 value = value.replace('\\n','\n')
141 141 return super(SeparateUnicode, self).validate(obj, value)
142 142
143 143
144 144 class ReadlineNoRecord(object):
145 145 """Context manager to execute some code, then reload readline history
146 146 so that interactive input to the code doesn't appear when pressing up."""
147 147 def __init__(self, shell):
148 148 self.shell = shell
149 149 self._nested_level = 0
150 150
151 151 def __enter__(self):
152 152 if self._nested_level == 0:
153 153 try:
154 154 self.orig_length = self.current_length()
155 155 self.readline_tail = self.get_readline_tail()
156 156 except (AttributeError, IndexError): # Can fail with pyreadline
157 157 self.orig_length, self.readline_tail = 999999, []
158 158 self._nested_level += 1
159 159
160 160 def __exit__(self, type, value, traceback):
161 161 self._nested_level -= 1
162 162 if self._nested_level == 0:
163 163 # Try clipping the end if it's got longer
164 164 try:
165 165 e = self.current_length() - self.orig_length
166 166 if e > 0:
167 167 for _ in range(e):
168 168 self.shell.readline.remove_history_item(self.orig_length)
169 169
170 170 # If it still doesn't match, just reload readline history.
171 171 if self.current_length() != self.orig_length \
172 172 or self.get_readline_tail() != self.readline_tail:
173 173 self.shell.refill_readline_hist()
174 174 except (AttributeError, IndexError):
175 175 pass
176 176 # Returning False will cause exceptions to propagate
177 177 return False
178 178
179 179 def current_length(self):
180 180 return self.shell.readline.get_current_history_length()
181 181
182 182 def get_readline_tail(self, n=10):
183 183 """Get the last n items in readline history."""
184 184 end = self.shell.readline.get_current_history_length() + 1
185 185 start = max(end-n, 1)
186 186 ghi = self.shell.readline.get_history_item
187 187 return [ghi(x) for x in range(start, end)]
188 188
189 189
190 190 @undoc
191 191 class DummyMod(object):
192 192 """A dummy module used for IPython's interactive module when
193 193 a namespace must be assigned to the module's __dict__."""
194 194 pass
195 195
196 196 #-----------------------------------------------------------------------------
197 197 # Main IPython class
198 198 #-----------------------------------------------------------------------------
199 199
200 200 class InteractiveShell(SingletonConfigurable):
201 201 """An enhanced, interactive shell for Python."""
202 202
203 203 _instance = None
204 204
205 205 ast_transformers = List([], config=True, help=
206 206 """
207 207 A list of ast.NodeTransformer subclass instances, which will be applied
208 208 to user input before code is run.
209 209 """
210 210 )
211 211
212 212 autocall = Enum((0,1,2), default_value=0, config=True, help=
213 213 """
214 214 Make IPython automatically call any callable object even if you didn't
215 215 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
216 216 automatically. The value can be '0' to disable the feature, '1' for
217 217 'smart' autocall, where it is not applied if there are no more
218 218 arguments on the line, and '2' for 'full' autocall, where all callable
219 219 objects are automatically called (even if no arguments are present).
220 220 """
221 221 )
222 222 # TODO: remove all autoindent logic and put into frontends.
223 223 # We can't do this yet because even runlines uses the autoindent.
224 224 autoindent = CBool(True, config=True, help=
225 225 """
226 226 Autoindent IPython code entered interactively.
227 227 """
228 228 )
229 229 automagic = CBool(True, config=True, help=
230 230 """
231 231 Enable magic commands to be called without the leading %.
232 232 """
233 233 )
234 234 cache_size = Integer(1000, config=True, help=
235 235 """
236 236 Set the size of the output cache. The default is 1000, you can
237 237 change it permanently in your config file. Setting it to 0 completely
238 238 disables the caching system, and the minimum value accepted is 20 (if
239 239 you provide a value less than 20, it is reset to 0 and a warning is
240 240 issued). This limit is defined because otherwise you'll spend more
241 241 time re-flushing a too small cache than working
242 242 """
243 243 )
244 244 color_info = CBool(True, config=True, help=
245 245 """
246 246 Use colors for displaying information about objects. Because this
247 247 information is passed through a pager (like 'less'), and some pagers
248 248 get confused with color codes, this capability can be turned off.
249 249 """
250 250 )
251 251 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
252 252 default_value=get_default_colors(), config=True,
253 253 help="Set the color scheme (NoColor, Linux, or LightBG)."
254 254 )
255 255 colors_force = CBool(False, help=
256 256 """
257 257 Force use of ANSI color codes, regardless of OS and readline
258 258 availability.
259 259 """
260 260 # FIXME: This is essentially a hack to allow ZMQShell to show colors
261 261 # without readline on Win32. When the ZMQ formatting system is
262 262 # refactored, this should be removed.
263 263 )
264 264 debug = CBool(False, config=True)
265 265 deep_reload = CBool(False, config=True, help=
266 266 """
267 267 Enable deep (recursive) reloading by default. IPython can use the
268 268 deep_reload module which reloads changes in modules recursively (it
269 269 replaces the reload() function, so you don't need to change anything to
270 270 use it). deep_reload() forces a full reload of modules whose code may
271 271 have changed, which the default reload() function does not. When
272 272 deep_reload is off, IPython will use the normal reload(), but
273 273 deep_reload will still be available as dreload().
274 274 """
275 275 )
276 276 disable_failing_post_execute = CBool(False, config=True,
277 277 help="Don't call post-execute functions that have failed in the past."
278 278 )
279 279 display_formatter = Instance(DisplayFormatter)
280 280 displayhook_class = Type(DisplayHook)
281 281 display_pub_class = Type(DisplayPublisher)
282 282 data_pub_class = None
283 283
284 284 exit_now = CBool(False)
285 285 exiter = Instance(ExitAutocall)
286 286 def _exiter_default(self):
287 287 return ExitAutocall(self)
288 288 # Monotonically increasing execution counter
289 289 execution_count = Integer(1)
290 290 filename = Unicode("<ipython console>")
291 291 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
292 292
293 293 # Input splitter, to transform input line by line and detect when a block
294 294 # is ready to be executed.
295 295 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
296 296 (), {'line_input_checker': True})
297 297
298 298 # This InputSplitter instance is used to transform completed cells before
299 299 # running them. It allows cell magics to contain blank lines.
300 300 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
301 301 (), {'line_input_checker': False})
302 302
303 303 logstart = CBool(False, config=True, help=
304 304 """
305 305 Start logging to the default log file.
306 306 """
307 307 )
308 308 logfile = Unicode('', config=True, help=
309 309 """
310 310 The name of the logfile to use.
311 311 """
312 312 )
313 313 logappend = Unicode('', config=True, help=
314 314 """
315 315 Start logging to the given file in append mode.
316 316 """
317 317 )
318 318 object_info_string_level = Enum((0,1,2), default_value=0,
319 319 config=True)
320 320 pdb = CBool(False, config=True, help=
321 321 """
322 322 Automatically call the pdb debugger after every exception.
323 323 """
324 324 )
325 325 multiline_history = CBool(sys.platform != 'win32', config=True,
326 326 help="Save multi-line entries as one entry in readline history"
327 327 )
328 328
329 329 # deprecated prompt traits:
330 330
331 331 prompt_in1 = Unicode('In [\\#]: ', config=True,
332 332 help="Deprecated, use PromptManager.in_template")
333 333 prompt_in2 = Unicode(' .\\D.: ', config=True,
334 334 help="Deprecated, use PromptManager.in2_template")
335 335 prompt_out = Unicode('Out[\\#]: ', config=True,
336 336 help="Deprecated, use PromptManager.out_template")
337 337 prompts_pad_left = CBool(True, config=True,
338 338 help="Deprecated, use PromptManager.justify")
339 339
340 340 def _prompt_trait_changed(self, name, old, new):
341 341 table = {
342 342 'prompt_in1' : 'in_template',
343 343 'prompt_in2' : 'in2_template',
344 344 'prompt_out' : 'out_template',
345 345 'prompts_pad_left' : 'justify',
346 346 }
347 347 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
348 348 name=name, newname=table[name])
349 349 )
350 350 # protect against weird cases where self.config may not exist:
351 351 if self.config is not None:
352 352 # propagate to corresponding PromptManager trait
353 353 setattr(self.config.PromptManager, table[name], new)
354 354
355 355 _prompt_in1_changed = _prompt_trait_changed
356 356 _prompt_in2_changed = _prompt_trait_changed
357 357 _prompt_out_changed = _prompt_trait_changed
358 358 _prompt_pad_left_changed = _prompt_trait_changed
359 359
360 360 show_rewritten_input = CBool(True, config=True,
361 361 help="Show rewritten input, e.g. for autocall."
362 362 )
363 363
364 364 quiet = CBool(False, config=True)
365 365
366 366 history_length = Integer(10000, config=True)
367 367
368 368 # The readline stuff will eventually be moved to the terminal subclass
369 369 # but for now, we can't do that as readline is welded in everywhere.
370 370 readline_use = CBool(True, config=True)
371 371 readline_remove_delims = Unicode('-/~', config=True)
372 372 readline_delims = Unicode() # set by init_readline()
373 373 # don't use \M- bindings by default, because they
374 374 # conflict with 8-bit encodings. See gh-58,gh-88
375 375 readline_parse_and_bind = List([
376 376 'tab: complete',
377 377 '"\C-l": clear-screen',
378 378 'set show-all-if-ambiguous on',
379 379 '"\C-o": tab-insert',
380 380 '"\C-r": reverse-search-history',
381 381 '"\C-s": forward-search-history',
382 382 '"\C-p": history-search-backward',
383 383 '"\C-n": history-search-forward',
384 384 '"\e[A": history-search-backward',
385 385 '"\e[B": history-search-forward',
386 386 '"\C-k": kill-line',
387 387 '"\C-u": unix-line-discard',
388 388 ], allow_none=False, config=True)
389 389
390 390 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
391 391 default_value='last_expr', config=True,
392 392 help="""
393 393 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
394 394 run interactively (displaying output from expressions).""")
395 395
396 396 # TODO: this part of prompt management should be moved to the frontends.
397 397 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
398 398 separate_in = SeparateUnicode('\n', config=True)
399 399 separate_out = SeparateUnicode('', config=True)
400 400 separate_out2 = SeparateUnicode('', config=True)
401 401 wildcards_case_sensitive = CBool(True, config=True)
402 402 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
403 403 default_value='Context', config=True)
404 404
405 405 # Subcomponents of InteractiveShell
406 406 alias_manager = Instance('IPython.core.alias.AliasManager')
407 407 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
408 408 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
409 409 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
410 410 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
411 411 payload_manager = Instance('IPython.core.payload.PayloadManager')
412 412 history_manager = Instance('IPython.core.history.HistoryManager')
413 413 magics_manager = Instance('IPython.core.magic.MagicsManager')
414 414
415 415 profile_dir = Instance('IPython.core.application.ProfileDir')
416 416 @property
417 417 def profile(self):
418 418 if self.profile_dir is not None:
419 419 name = os.path.basename(self.profile_dir.location)
420 420 return name.replace('profile_','')
421 421
422 422
423 423 # Private interface
424 424 _post_execute = Instance(dict)
425 425
426 426 # Tracks any GUI loop loaded for pylab
427 427 pylab_gui_select = None
428 428
429 429 def __init__(self, ipython_dir=None, profile_dir=None,
430 430 user_module=None, user_ns=None,
431 431 custom_exceptions=((), None), **kwargs):
432 432
433 433 # This is where traits with a config_key argument are updated
434 434 # from the values on config.
435 435 super(InteractiveShell, self).__init__(**kwargs)
436 436 self.configurables = [self]
437 437
438 438 # These are relatively independent and stateless
439 439 self.init_ipython_dir(ipython_dir)
440 440 self.init_profile_dir(profile_dir)
441 441 self.init_instance_attrs()
442 442 self.init_environment()
443 443
444 444 # Check if we're in a virtualenv, and set up sys.path.
445 445 self.init_virtualenv()
446 446
447 447 # Create namespaces (user_ns, user_global_ns, etc.)
448 448 self.init_create_namespaces(user_module, user_ns)
449 449 # This has to be done after init_create_namespaces because it uses
450 450 # something in self.user_ns, but before init_sys_modules, which
451 451 # is the first thing to modify sys.
452 452 # TODO: When we override sys.stdout and sys.stderr before this class
453 453 # is created, we are saving the overridden ones here. Not sure if this
454 454 # is what we want to do.
455 455 self.save_sys_module_state()
456 456 self.init_sys_modules()
457 457
458 458 # While we're trying to have each part of the code directly access what
459 459 # it needs without keeping redundant references to objects, we have too
460 460 # much legacy code that expects ip.db to exist.
461 461 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
462 462
463 463 self.init_history()
464 464 self.init_encoding()
465 465 self.init_prefilter()
466 466
467 467 self.init_syntax_highlighting()
468 468 self.init_hooks()
469 469 self.init_pushd_popd_magic()
470 470 # self.init_traceback_handlers use to be here, but we moved it below
471 471 # because it and init_io have to come after init_readline.
472 472 self.init_user_ns()
473 473 self.init_logger()
474 474 self.init_alias()
475 475 self.init_builtins()
476 476
477 477 # The following was in post_config_initialization
478 478 self.init_inspector()
479 479 # init_readline() must come before init_io(), because init_io uses
480 480 # readline related things.
481 481 self.init_readline()
482 482 # We save this here in case user code replaces raw_input, but it needs
483 483 # to be after init_readline(), because PyPy's readline works by replacing
484 484 # raw_input.
485 485 if py3compat.PY3:
486 486 self.raw_input_original = input
487 487 else:
488 488 self.raw_input_original = raw_input
489 489 # init_completer must come after init_readline, because it needs to
490 490 # know whether readline is present or not system-wide to configure the
491 491 # completers, since the completion machinery can now operate
492 492 # independently of readline (e.g. over the network)
493 493 self.init_completer()
494 494 # TODO: init_io() needs to happen before init_traceback handlers
495 495 # because the traceback handlers hardcode the stdout/stderr streams.
496 496 # This logic in in debugger.Pdb and should eventually be changed.
497 497 self.init_io()
498 498 self.init_traceback_handlers(custom_exceptions)
499 499 self.init_prompts()
500 500 self.init_display_formatter()
501 501 self.init_display_pub()
502 502 self.init_data_pub()
503 503 self.init_displayhook()
504 504 self.init_latextool()
505 505 self.init_magics()
506 506 self.init_logstart()
507 507 self.init_pdb()
508 508 self.init_extension_manager()
509 509 self.init_payload()
510 510 self.hooks.late_startup_hook()
511 511 atexit.register(self.atexit_operations)
512 512
513 513 def get_ipython(self):
514 514 """Return the currently running IPython instance."""
515 515 return self
516 516
517 517 #-------------------------------------------------------------------------
518 518 # Trait changed handlers
519 519 #-------------------------------------------------------------------------
520 520
521 521 def _ipython_dir_changed(self, name, new):
522 522 if not os.path.isdir(new):
523 523 os.makedirs(new, mode = 0o777)
524 524
525 525 def set_autoindent(self,value=None):
526 526 """Set the autoindent flag, checking for readline support.
527 527
528 528 If called with no arguments, it acts as a toggle."""
529 529
530 530 if value != 0 and not self.has_readline:
531 531 if os.name == 'posix':
532 532 warn("The auto-indent feature requires the readline library")
533 533 self.autoindent = 0
534 534 return
535 535 if value is None:
536 536 self.autoindent = not self.autoindent
537 537 else:
538 538 self.autoindent = value
539 539
540 540 #-------------------------------------------------------------------------
541 541 # init_* methods called by __init__
542 542 #-------------------------------------------------------------------------
543 543
544 544 def init_ipython_dir(self, ipython_dir):
545 545 if ipython_dir is not None:
546 546 self.ipython_dir = ipython_dir
547 547 return
548 548
549 549 self.ipython_dir = get_ipython_dir()
550 550
551 551 def init_profile_dir(self, profile_dir):
552 552 if profile_dir is not None:
553 553 self.profile_dir = profile_dir
554 554 return
555 555 self.profile_dir =\
556 556 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
557 557
558 558 def init_instance_attrs(self):
559 559 self.more = False
560 560
561 561 # command compiler
562 562 self.compile = CachingCompiler()
563 563
564 564 # Make an empty namespace, which extension writers can rely on both
565 565 # existing and NEVER being used by ipython itself. This gives them a
566 566 # convenient location for storing additional information and state
567 567 # their extensions may require, without fear of collisions with other
568 568 # ipython names that may develop later.
569 569 self.meta = Struct()
570 570
571 571 # Temporary files used for various purposes. Deleted at exit.
572 572 self.tempfiles = []
573 573
574 574 # Keep track of readline usage (later set by init_readline)
575 575 self.has_readline = False
576 576
577 577 # keep track of where we started running (mainly for crash post-mortem)
578 578 # This is not being used anywhere currently.
579 579 self.starting_dir = os.getcwdu()
580 580
581 581 # Indentation management
582 582 self.indent_current_nsp = 0
583 583
584 584 # Dict to track post-execution functions that have been registered
585 585 self._post_execute = {}
586 586
587 587 def init_environment(self):
588 588 """Any changes we need to make to the user's environment."""
589 589 pass
590 590
591 591 def init_encoding(self):
592 592 # Get system encoding at startup time. Certain terminals (like Emacs
593 593 # under Win32 have it set to None, and we need to have a known valid
594 594 # encoding to use in the raw_input() method
595 595 try:
596 596 self.stdin_encoding = sys.stdin.encoding or 'ascii'
597 597 except AttributeError:
598 598 self.stdin_encoding = 'ascii'
599 599
600 600 def init_syntax_highlighting(self):
601 601 # Python source parser/formatter for syntax highlighting
602 602 pyformat = PyColorize.Parser().format
603 603 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
604 604
605 605 def init_pushd_popd_magic(self):
606 606 # for pushd/popd management
607 607 self.home_dir = get_home_dir()
608 608
609 609 self.dir_stack = []
610 610
611 611 def init_logger(self):
612 612 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
613 613 logmode='rotate')
614 614
615 615 def init_logstart(self):
616 616 """Initialize logging in case it was requested at the command line.
617 617 """
618 618 if self.logappend:
619 619 self.magic('logstart %s append' % self.logappend)
620 620 elif self.logfile:
621 621 self.magic('logstart %s' % self.logfile)
622 622 elif self.logstart:
623 623 self.magic('logstart')
624 624
625 625 def init_builtins(self):
626 626 # A single, static flag that we set to True. Its presence indicates
627 627 # that an IPython shell has been created, and we make no attempts at
628 628 # removing on exit or representing the existence of more than one
629 629 # IPython at a time.
630 630 builtin_mod.__dict__['__IPYTHON__'] = True
631 631
632 632 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
633 633 # manage on enter/exit, but with all our shells it's virtually
634 634 # impossible to get all the cases right. We're leaving the name in for
635 635 # those who adapted their codes to check for this flag, but will
636 636 # eventually remove it after a few more releases.
637 637 builtin_mod.__dict__['__IPYTHON__active'] = \
638 638 'Deprecated, check for __IPYTHON__'
639 639
640 640 self.builtin_trap = BuiltinTrap(shell=self)
641 641
642 642 def init_inspector(self):
643 643 # Object inspector
644 644 self.inspector = oinspect.Inspector(oinspect.InspectColors,
645 645 PyColorize.ANSICodeColors,
646 646 'NoColor',
647 647 self.object_info_string_level)
648 648
649 649 def init_io(self):
650 650 # This will just use sys.stdout and sys.stderr. If you want to
651 651 # override sys.stdout and sys.stderr themselves, you need to do that
652 652 # *before* instantiating this class, because io holds onto
653 653 # references to the underlying streams.
654 654 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
655 655 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
656 656 else:
657 657 io.stdout = io.IOStream(sys.stdout)
658 658 io.stderr = io.IOStream(sys.stderr)
659 659
660 660 def init_prompts(self):
661 661 self.prompt_manager = PromptManager(shell=self, parent=self)
662 662 self.configurables.append(self.prompt_manager)
663 663 # Set system prompts, so that scripts can decide if they are running
664 664 # interactively.
665 665 sys.ps1 = 'In : '
666 666 sys.ps2 = '...: '
667 667 sys.ps3 = 'Out: '
668 668
669 669 def init_display_formatter(self):
670 670 self.display_formatter = DisplayFormatter(parent=self)
671 671 self.configurables.append(self.display_formatter)
672 672
673 673 def init_display_pub(self):
674 674 self.display_pub = self.display_pub_class(parent=self)
675 675 self.configurables.append(self.display_pub)
676 676
677 677 def init_data_pub(self):
678 678 if not self.data_pub_class:
679 679 self.data_pub = None
680 680 return
681 681 self.data_pub = self.data_pub_class(parent=self)
682 682 self.configurables.append(self.data_pub)
683 683
684 684 def init_displayhook(self):
685 685 # Initialize displayhook, set in/out prompts and printing system
686 686 self.displayhook = self.displayhook_class(
687 687 parent=self,
688 688 shell=self,
689 689 cache_size=self.cache_size,
690 690 )
691 691 self.configurables.append(self.displayhook)
692 692 # This is a context manager that installs/revmoes the displayhook at
693 693 # the appropriate time.
694 694 self.display_trap = DisplayTrap(hook=self.displayhook)
695 695
696 696 def init_latextool(self):
697 697 """Configure LaTeXTool."""
698 698 cfg = LaTeXTool.instance(parent=self)
699 699 if cfg not in self.configurables:
700 700 self.configurables.append(cfg)
701 701
702 702 def init_virtualenv(self):
703 703 """Add a virtualenv to sys.path so the user can import modules from it.
704 704 This isn't perfect: it doesn't use the Python interpreter with which the
705 705 virtualenv was built, and it ignores the --no-site-packages option. A
706 706 warning will appear suggesting the user installs IPython in the
707 707 virtualenv, but for many cases, it probably works well enough.
708 708
709 709 Adapted from code snippets online.
710 710
711 711 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
712 712 """
713 713 if 'VIRTUAL_ENV' not in os.environ:
714 714 # Not in a virtualenv
715 715 return
716 716
717 717 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
718 718 # Running properly in the virtualenv, don't need to do anything
719 719 return
720 720
721 721 warn("Attempting to work in a virtualenv. If you encounter problems, please "
722 722 "install IPython inside the virtualenv.")
723 723 if sys.platform == "win32":
724 724 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
725 725 else:
726 726 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
727 727 'python%d.%d' % sys.version_info[:2], 'site-packages')
728 728
729 729 import site
730 730 sys.path.insert(0, virtual_env)
731 731 site.addsitedir(virtual_env)
732 732
733 733 #-------------------------------------------------------------------------
734 734 # Things related to injections into the sys module
735 735 #-------------------------------------------------------------------------
736 736
737 737 def save_sys_module_state(self):
738 738 """Save the state of hooks in the sys module.
739 739
740 740 This has to be called after self.user_module is created.
741 741 """
742 742 self._orig_sys_module_state = {}
743 743 self._orig_sys_module_state['stdin'] = sys.stdin
744 744 self._orig_sys_module_state['stdout'] = sys.stdout
745 745 self._orig_sys_module_state['stderr'] = sys.stderr
746 746 self._orig_sys_module_state['excepthook'] = sys.excepthook
747 747 self._orig_sys_modules_main_name = self.user_module.__name__
748 748 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
749 749
750 750 def restore_sys_module_state(self):
751 751 """Restore the state of the sys module."""
752 752 try:
753 753 for k, v in self._orig_sys_module_state.iteritems():
754 754 setattr(sys, k, v)
755 755 except AttributeError:
756 756 pass
757 757 # Reset what what done in self.init_sys_modules
758 758 if self._orig_sys_modules_main_mod is not None:
759 759 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
760 760
761 761 #-------------------------------------------------------------------------
762 762 # Things related to hooks
763 763 #-------------------------------------------------------------------------
764 764
765 765 def init_hooks(self):
766 766 # hooks holds pointers used for user-side customizations
767 767 self.hooks = Struct()
768 768
769 769 self.strdispatchers = {}
770 770
771 771 # Set all default hooks, defined in the IPython.hooks module.
772 772 hooks = IPython.core.hooks
773 773 for hook_name in hooks.__all__:
774 774 # default hooks have priority 100, i.e. low; user hooks should have
775 775 # 0-100 priority
776 776 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
777 777
778 778 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
779 779 """set_hook(name,hook) -> sets an internal IPython hook.
780 780
781 781 IPython exposes some of its internal API as user-modifiable hooks. By
782 782 adding your function to one of these hooks, you can modify IPython's
783 783 behavior to call at runtime your own routines."""
784 784
785 785 # At some point in the future, this should validate the hook before it
786 786 # accepts it. Probably at least check that the hook takes the number
787 787 # of args it's supposed to.
788 788
789 789 f = types.MethodType(hook,self)
790 790
791 791 # check if the hook is for strdispatcher first
792 792 if str_key is not None:
793 793 sdp = self.strdispatchers.get(name, StrDispatch())
794 794 sdp.add_s(str_key, f, priority )
795 795 self.strdispatchers[name] = sdp
796 796 return
797 797 if re_key is not None:
798 798 sdp = self.strdispatchers.get(name, StrDispatch())
799 799 sdp.add_re(re.compile(re_key), f, priority )
800 800 self.strdispatchers[name] = sdp
801 801 return
802 802
803 803 dp = getattr(self.hooks, name, None)
804 804 if name not in IPython.core.hooks.__all__:
805 805 print("Warning! Hook '%s' is not one of %s" % \
806 806 (name, IPython.core.hooks.__all__ ))
807 807 if not dp:
808 808 dp = IPython.core.hooks.CommandChainDispatcher()
809 809
810 810 try:
811 811 dp.add(f,priority)
812 812 except AttributeError:
813 813 # it was not commandchain, plain old func - replace
814 814 dp = f
815 815
816 816 setattr(self.hooks,name, dp)
817 817
818 818 def register_post_execute(self, func):
819 819 """Register a function for calling after code execution.
820 820 """
821 821 if not callable(func):
822 822 raise ValueError('argument %s must be callable' % func)
823 823 self._post_execute[func] = True
824 824
825 825 #-------------------------------------------------------------------------
826 826 # Things related to the "main" module
827 827 #-------------------------------------------------------------------------
828 828
829 829 def new_main_mod(self, filename):
830 830 """Return a new 'main' module object for user code execution.
831 831
832 832 ``filename`` should be the path of the script which will be run in the
833 833 module. Requests with the same filename will get the same module, with
834 834 its namespace cleared.
835 835
836 836 When scripts are executed via %run, we must keep a reference to their
837 837 __main__ module (a FakeModule instance) around so that Python doesn't
838 838 clear it, rendering references to module globals useless.
839 839
840 840 This method keeps said reference in a private dict, keyed by the
841 841 absolute path of the script. This way, for multiple executions of the
842 842 same script we only keep one copy of the namespace (the last one),
843 843 thus preventing memory leaks from old references while allowing the
844 844 objects from the last execution to be accessible.
845 845 """
846 846 filename = os.path.abspath(filename)
847 847 try:
848 848 main_mod = self._main_mod_cache[filename]
849 849 except KeyError:
850 850 main_mod = self._main_mod_cache[filename] = FakeModule()
851 851 else:
852 852 init_fakemod_dict(main_mod)
853 853
854 854 return main_mod
855 855
856 856 def clear_main_mod_cache(self):
857 857 """Clear the cache of main modules.
858 858
859 859 Mainly for use by utilities like %reset.
860 860
861 861 Examples
862 862 --------
863 863
864 864 In [15]: import IPython
865 865
866 866 In [16]: m = _ip.new_main_mod(IPython.__file__)
867 867
868 868 In [17]: len(_ip._main_mod_cache) > 0
869 869 Out[17]: True
870 870
871 871 In [18]: _ip.clear_main_mod_cache()
872 872
873 873 In [19]: len(_ip._main_mod_cache) == 0
874 874 Out[19]: True
875 875 """
876 876 self._main_mod_cache.clear()
877 877
878 878 #-------------------------------------------------------------------------
879 879 # Things related to debugging
880 880 #-------------------------------------------------------------------------
881 881
882 882 def init_pdb(self):
883 883 # Set calling of pdb on exceptions
884 884 # self.call_pdb is a property
885 885 self.call_pdb = self.pdb
886 886
887 887 def _get_call_pdb(self):
888 888 return self._call_pdb
889 889
890 890 def _set_call_pdb(self,val):
891 891
892 892 if val not in (0,1,False,True):
893 893 raise ValueError('new call_pdb value must be boolean')
894 894
895 895 # store value in instance
896 896 self._call_pdb = val
897 897
898 898 # notify the actual exception handlers
899 899 self.InteractiveTB.call_pdb = val
900 900
901 901 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
902 902 'Control auto-activation of pdb at exceptions')
903 903
904 904 def debugger(self,force=False):
905 905 """Call the pydb/pdb debugger.
906 906
907 907 Keywords:
908 908
909 909 - force(False): by default, this routine checks the instance call_pdb
910 flag and does not actually invoke the debugger if the flag is false.
911 The 'force' option forces the debugger to activate even if the flag
912 is false.
910 flag and does not actually invoke the debugger if the flag is false.
911 The 'force' option forces the debugger to activate even if the flag
912 is false.
913 913 """
914 914
915 915 if not (force or self.call_pdb):
916 916 return
917 917
918 918 if not hasattr(sys,'last_traceback'):
919 919 error('No traceback has been produced, nothing to debug.')
920 920 return
921 921
922 922 # use pydb if available
923 923 if debugger.has_pydb:
924 924 from pydb import pm
925 925 else:
926 926 # fallback to our internal debugger
927 927 pm = lambda : self.InteractiveTB.debugger(force=True)
928 928
929 929 with self.readline_no_record:
930 930 pm()
931 931
932 932 #-------------------------------------------------------------------------
933 933 # Things related to IPython's various namespaces
934 934 #-------------------------------------------------------------------------
935 935 default_user_namespaces = True
936 936
937 937 def init_create_namespaces(self, user_module=None, user_ns=None):
938 938 # Create the namespace where the user will operate. user_ns is
939 939 # normally the only one used, and it is passed to the exec calls as
940 940 # the locals argument. But we do carry a user_global_ns namespace
941 941 # given as the exec 'globals' argument, This is useful in embedding
942 942 # situations where the ipython shell opens in a context where the
943 943 # distinction between locals and globals is meaningful. For
944 944 # non-embedded contexts, it is just the same object as the user_ns dict.
945 945
946 946 # FIXME. For some strange reason, __builtins__ is showing up at user
947 947 # level as a dict instead of a module. This is a manual fix, but I
948 948 # should really track down where the problem is coming from. Alex
949 949 # Schmolck reported this problem first.
950 950
951 951 # A useful post by Alex Martelli on this topic:
952 952 # Re: inconsistent value from __builtins__
953 953 # Von: Alex Martelli <aleaxit@yahoo.com>
954 954 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
955 955 # Gruppen: comp.lang.python
956 956
957 957 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
958 958 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
959 959 # > <type 'dict'>
960 960 # > >>> print type(__builtins__)
961 961 # > <type 'module'>
962 962 # > Is this difference in return value intentional?
963 963
964 964 # Well, it's documented that '__builtins__' can be either a dictionary
965 965 # or a module, and it's been that way for a long time. Whether it's
966 966 # intentional (or sensible), I don't know. In any case, the idea is
967 967 # that if you need to access the built-in namespace directly, you
968 968 # should start with "import __builtin__" (note, no 's') which will
969 969 # definitely give you a module. Yeah, it's somewhat confusing:-(.
970 970
971 971 # These routines return a properly built module and dict as needed by
972 972 # the rest of the code, and can also be used by extension writers to
973 973 # generate properly initialized namespaces.
974 974 if (user_ns is not None) or (user_module is not None):
975 975 self.default_user_namespaces = False
976 976 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
977 977
978 978 # A record of hidden variables we have added to the user namespace, so
979 979 # we can list later only variables defined in actual interactive use.
980 980 self.user_ns_hidden = {}
981 981
982 982 # Now that FakeModule produces a real module, we've run into a nasty
983 983 # problem: after script execution (via %run), the module where the user
984 984 # code ran is deleted. Now that this object is a true module (needed
985 985 # so docetst and other tools work correctly), the Python module
986 986 # teardown mechanism runs over it, and sets to None every variable
987 987 # present in that module. Top-level references to objects from the
988 988 # script survive, because the user_ns is updated with them. However,
989 989 # calling functions defined in the script that use other things from
990 990 # the script will fail, because the function's closure had references
991 991 # to the original objects, which are now all None. So we must protect
992 992 # these modules from deletion by keeping a cache.
993 993 #
994 994 # To avoid keeping stale modules around (we only need the one from the
995 995 # last run), we use a dict keyed with the full path to the script, so
996 996 # only the last version of the module is held in the cache. Note,
997 997 # however, that we must cache the module *namespace contents* (their
998 998 # __dict__). Because if we try to cache the actual modules, old ones
999 999 # (uncached) could be destroyed while still holding references (such as
1000 1000 # those held by GUI objects that tend to be long-lived)>
1001 1001 #
1002 1002 # The %reset command will flush this cache. See the cache_main_mod()
1003 1003 # and clear_main_mod_cache() methods for details on use.
1004 1004
1005 1005 # This is the cache used for 'main' namespaces
1006 1006 self._main_mod_cache = {}
1007 1007
1008 1008 # A table holding all the namespaces IPython deals with, so that
1009 1009 # introspection facilities can search easily.
1010 1010 self.ns_table = {'user_global':self.user_module.__dict__,
1011 1011 'user_local':self.user_ns,
1012 1012 'builtin':builtin_mod.__dict__
1013 1013 }
1014 1014
1015 1015 @property
1016 1016 def user_global_ns(self):
1017 1017 return self.user_module.__dict__
1018 1018
1019 1019 def prepare_user_module(self, user_module=None, user_ns=None):
1020 1020 """Prepare the module and namespace in which user code will be run.
1021 1021
1022 1022 When IPython is started normally, both parameters are None: a new module
1023 1023 is created automatically, and its __dict__ used as the namespace.
1024 1024
1025 1025 If only user_module is provided, its __dict__ is used as the namespace.
1026 1026 If only user_ns is provided, a dummy module is created, and user_ns
1027 1027 becomes the global namespace. If both are provided (as they may be
1028 1028 when embedding), user_ns is the local namespace, and user_module
1029 1029 provides the global namespace.
1030 1030
1031 1031 Parameters
1032 1032 ----------
1033 1033 user_module : module, optional
1034 1034 The current user module in which IPython is being run. If None,
1035 1035 a clean module will be created.
1036 1036 user_ns : dict, optional
1037 1037 A namespace in which to run interactive commands.
1038 1038
1039 1039 Returns
1040 1040 -------
1041 1041 A tuple of user_module and user_ns, each properly initialised.
1042 1042 """
1043 1043 if user_module is None and user_ns is not None:
1044 1044 user_ns.setdefault("__name__", "__main__")
1045 1045 user_module = DummyMod()
1046 1046 user_module.__dict__ = user_ns
1047 1047
1048 1048 if user_module is None:
1049 1049 user_module = types.ModuleType("__main__",
1050 1050 doc="Automatically created module for IPython interactive environment")
1051 1051
1052 1052 # We must ensure that __builtin__ (without the final 's') is always
1053 1053 # available and pointing to the __builtin__ *module*. For more details:
1054 1054 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1055 1055 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1056 1056 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1057 1057
1058 1058 if user_ns is None:
1059 1059 user_ns = user_module.__dict__
1060 1060
1061 1061 return user_module, user_ns
1062 1062
1063 1063 def init_sys_modules(self):
1064 1064 # We need to insert into sys.modules something that looks like a
1065 1065 # module but which accesses the IPython namespace, for shelve and
1066 1066 # pickle to work interactively. Normally they rely on getting
1067 1067 # everything out of __main__, but for embedding purposes each IPython
1068 1068 # instance has its own private namespace, so we can't go shoving
1069 1069 # everything into __main__.
1070 1070
1071 1071 # note, however, that we should only do this for non-embedded
1072 1072 # ipythons, which really mimic the __main__.__dict__ with their own
1073 1073 # namespace. Embedded instances, on the other hand, should not do
1074 1074 # this because they need to manage the user local/global namespaces
1075 1075 # only, but they live within a 'normal' __main__ (meaning, they
1076 1076 # shouldn't overtake the execution environment of the script they're
1077 1077 # embedded in).
1078 1078
1079 1079 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1080 1080 main_name = self.user_module.__name__
1081 1081 sys.modules[main_name] = self.user_module
1082 1082
1083 1083 def init_user_ns(self):
1084 1084 """Initialize all user-visible namespaces to their minimum defaults.
1085 1085
1086 1086 Certain history lists are also initialized here, as they effectively
1087 1087 act as user namespaces.
1088 1088
1089 1089 Notes
1090 1090 -----
1091 1091 All data structures here are only filled in, they are NOT reset by this
1092 1092 method. If they were not empty before, data will simply be added to
1093 1093 therm.
1094 1094 """
1095 1095 # This function works in two parts: first we put a few things in
1096 1096 # user_ns, and we sync that contents into user_ns_hidden so that these
1097 1097 # initial variables aren't shown by %who. After the sync, we add the
1098 1098 # rest of what we *do* want the user to see with %who even on a new
1099 1099 # session (probably nothing, so theye really only see their own stuff)
1100 1100
1101 1101 # The user dict must *always* have a __builtin__ reference to the
1102 1102 # Python standard __builtin__ namespace, which must be imported.
1103 1103 # This is so that certain operations in prompt evaluation can be
1104 1104 # reliably executed with builtins. Note that we can NOT use
1105 1105 # __builtins__ (note the 's'), because that can either be a dict or a
1106 1106 # module, and can even mutate at runtime, depending on the context
1107 1107 # (Python makes no guarantees on it). In contrast, __builtin__ is
1108 1108 # always a module object, though it must be explicitly imported.
1109 1109
1110 1110 # For more details:
1111 1111 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1112 1112 ns = dict()
1113 1113
1114 1114 # Put 'help' in the user namespace
1115 1115 try:
1116 1116 from site import _Helper
1117 1117 ns['help'] = _Helper()
1118 1118 except ImportError:
1119 1119 warn('help() not available - check site.py')
1120 1120
1121 1121 # make global variables for user access to the histories
1122 1122 ns['_ih'] = self.history_manager.input_hist_parsed
1123 1123 ns['_oh'] = self.history_manager.output_hist
1124 1124 ns['_dh'] = self.history_manager.dir_hist
1125 1125
1126 1126 ns['_sh'] = shadowns
1127 1127
1128 1128 # user aliases to input and output histories. These shouldn't show up
1129 1129 # in %who, as they can have very large reprs.
1130 1130 ns['In'] = self.history_manager.input_hist_parsed
1131 1131 ns['Out'] = self.history_manager.output_hist
1132 1132
1133 1133 # Store myself as the public api!!!
1134 1134 ns['get_ipython'] = self.get_ipython
1135 1135
1136 1136 ns['exit'] = self.exiter
1137 1137 ns['quit'] = self.exiter
1138 1138
1139 1139 # Sync what we've added so far to user_ns_hidden so these aren't seen
1140 1140 # by %who
1141 1141 self.user_ns_hidden.update(ns)
1142 1142
1143 1143 # Anything put into ns now would show up in %who. Think twice before
1144 1144 # putting anything here, as we really want %who to show the user their
1145 1145 # stuff, not our variables.
1146 1146
1147 1147 # Finally, update the real user's namespace
1148 1148 self.user_ns.update(ns)
1149 1149
1150 1150 @property
1151 1151 def all_ns_refs(self):
1152 1152 """Get a list of references to all the namespace dictionaries in which
1153 1153 IPython might store a user-created object.
1154 1154
1155 1155 Note that this does not include the displayhook, which also caches
1156 1156 objects from the output."""
1157 1157 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1158 1158 [m.__dict__ for m in self._main_mod_cache.values()]
1159 1159
1160 1160 def reset(self, new_session=True):
1161 1161 """Clear all internal namespaces, and attempt to release references to
1162 1162 user objects.
1163 1163
1164 1164 If new_session is True, a new history session will be opened.
1165 1165 """
1166 1166 # Clear histories
1167 1167 self.history_manager.reset(new_session)
1168 1168 # Reset counter used to index all histories
1169 1169 if new_session:
1170 1170 self.execution_count = 1
1171 1171
1172 1172 # Flush cached output items
1173 1173 if self.displayhook.do_full_cache:
1174 1174 self.displayhook.flush()
1175 1175
1176 1176 # The main execution namespaces must be cleared very carefully,
1177 1177 # skipping the deletion of the builtin-related keys, because doing so
1178 1178 # would cause errors in many object's __del__ methods.
1179 1179 if self.user_ns is not self.user_global_ns:
1180 1180 self.user_ns.clear()
1181 1181 ns = self.user_global_ns
1182 1182 drop_keys = set(ns.keys())
1183 1183 drop_keys.discard('__builtin__')
1184 1184 drop_keys.discard('__builtins__')
1185 1185 drop_keys.discard('__name__')
1186 1186 for k in drop_keys:
1187 1187 del ns[k]
1188 1188
1189 1189 self.user_ns_hidden.clear()
1190 1190
1191 1191 # Restore the user namespaces to minimal usability
1192 1192 self.init_user_ns()
1193 1193
1194 1194 # Restore the default and user aliases
1195 1195 self.alias_manager.clear_aliases()
1196 1196 self.alias_manager.init_aliases()
1197 1197
1198 1198 # Flush the private list of module references kept for script
1199 1199 # execution protection
1200 1200 self.clear_main_mod_cache()
1201 1201
1202 1202 def del_var(self, varname, by_name=False):
1203 1203 """Delete a variable from the various namespaces, so that, as
1204 1204 far as possible, we're not keeping any hidden references to it.
1205 1205
1206 1206 Parameters
1207 1207 ----------
1208 1208 varname : str
1209 1209 The name of the variable to delete.
1210 1210 by_name : bool
1211 1211 If True, delete variables with the given name in each
1212 1212 namespace. If False (default), find the variable in the user
1213 1213 namespace, and delete references to it.
1214 1214 """
1215 1215 if varname in ('__builtin__', '__builtins__'):
1216 1216 raise ValueError("Refusing to delete %s" % varname)
1217 1217
1218 1218 ns_refs = self.all_ns_refs
1219 1219
1220 1220 if by_name: # Delete by name
1221 1221 for ns in ns_refs:
1222 1222 try:
1223 1223 del ns[varname]
1224 1224 except KeyError:
1225 1225 pass
1226 1226 else: # Delete by object
1227 1227 try:
1228 1228 obj = self.user_ns[varname]
1229 1229 except KeyError:
1230 1230 raise NameError("name '%s' is not defined" % varname)
1231 1231 # Also check in output history
1232 1232 ns_refs.append(self.history_manager.output_hist)
1233 1233 for ns in ns_refs:
1234 1234 to_delete = [n for n, o in ns.iteritems() if o is obj]
1235 1235 for name in to_delete:
1236 1236 del ns[name]
1237 1237
1238 1238 # displayhook keeps extra references, but not in a dictionary
1239 1239 for name in ('_', '__', '___'):
1240 1240 if getattr(self.displayhook, name) is obj:
1241 1241 setattr(self.displayhook, name, None)
1242 1242
1243 1243 def reset_selective(self, regex=None):
1244 1244 """Clear selective variables from internal namespaces based on a
1245 1245 specified regular expression.
1246 1246
1247 1247 Parameters
1248 1248 ----------
1249 1249 regex : string or compiled pattern, optional
1250 1250 A regular expression pattern that will be used in searching
1251 1251 variable names in the users namespaces.
1252 1252 """
1253 1253 if regex is not None:
1254 1254 try:
1255 1255 m = re.compile(regex)
1256 1256 except TypeError:
1257 1257 raise TypeError('regex must be a string or compiled pattern')
1258 1258 # Search for keys in each namespace that match the given regex
1259 1259 # If a match is found, delete the key/value pair.
1260 1260 for ns in self.all_ns_refs:
1261 1261 for var in ns:
1262 1262 if m.search(var):
1263 1263 del ns[var]
1264 1264
1265 1265 def push(self, variables, interactive=True):
1266 1266 """Inject a group of variables into the IPython user namespace.
1267 1267
1268 1268 Parameters
1269 1269 ----------
1270 1270 variables : dict, str or list/tuple of str
1271 1271 The variables to inject into the user's namespace. If a dict, a
1272 1272 simple update is done. If a str, the string is assumed to have
1273 1273 variable names separated by spaces. A list/tuple of str can also
1274 1274 be used to give the variable names. If just the variable names are
1275 1275 give (list/tuple/str) then the variable values looked up in the
1276 1276 callers frame.
1277 1277 interactive : bool
1278 1278 If True (default), the variables will be listed with the ``who``
1279 1279 magic.
1280 1280 """
1281 1281 vdict = None
1282 1282
1283 1283 # We need a dict of name/value pairs to do namespace updates.
1284 1284 if isinstance(variables, dict):
1285 1285 vdict = variables
1286 1286 elif isinstance(variables, (basestring, list, tuple)):
1287 1287 if isinstance(variables, basestring):
1288 1288 vlist = variables.split()
1289 1289 else:
1290 1290 vlist = variables
1291 1291 vdict = {}
1292 1292 cf = sys._getframe(1)
1293 1293 for name in vlist:
1294 1294 try:
1295 1295 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1296 1296 except:
1297 1297 print('Could not get variable %s from %s' %
1298 1298 (name,cf.f_code.co_name))
1299 1299 else:
1300 1300 raise ValueError('variables must be a dict/str/list/tuple')
1301 1301
1302 1302 # Propagate variables to user namespace
1303 1303 self.user_ns.update(vdict)
1304 1304
1305 1305 # And configure interactive visibility
1306 1306 user_ns_hidden = self.user_ns_hidden
1307 1307 if interactive:
1308 1308 for name in vdict:
1309 1309 user_ns_hidden.pop(name, None)
1310 1310 else:
1311 1311 user_ns_hidden.update(vdict)
1312 1312
1313 1313 def drop_by_id(self, variables):
1314 1314 """Remove a dict of variables from the user namespace, if they are the
1315 1315 same as the values in the dictionary.
1316 1316
1317 1317 This is intended for use by extensions: variables that they've added can
1318 1318 be taken back out if they are unloaded, without removing any that the
1319 1319 user has overwritten.
1320 1320
1321 1321 Parameters
1322 1322 ----------
1323 1323 variables : dict
1324 1324 A dictionary mapping object names (as strings) to the objects.
1325 1325 """
1326 1326 for name, obj in variables.iteritems():
1327 1327 if name in self.user_ns and self.user_ns[name] is obj:
1328 1328 del self.user_ns[name]
1329 1329 self.user_ns_hidden.pop(name, None)
1330 1330
1331 1331 #-------------------------------------------------------------------------
1332 1332 # Things related to object introspection
1333 1333 #-------------------------------------------------------------------------
1334 1334
1335 1335 def _ofind(self, oname, namespaces=None):
1336 1336 """Find an object in the available namespaces.
1337 1337
1338 1338 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1339 1339
1340 1340 Has special code to detect magic functions.
1341 1341 """
1342 1342 oname = oname.strip()
1343 1343 #print '1- oname: <%r>' % oname # dbg
1344 1344 if not oname.startswith(ESC_MAGIC) and \
1345 1345 not oname.startswith(ESC_MAGIC2) and \
1346 1346 not py3compat.isidentifier(oname, dotted=True):
1347 1347 return dict(found=False)
1348 1348
1349 1349 alias_ns = None
1350 1350 if namespaces is None:
1351 1351 # Namespaces to search in:
1352 1352 # Put them in a list. The order is important so that we
1353 1353 # find things in the same order that Python finds them.
1354 1354 namespaces = [ ('Interactive', self.user_ns),
1355 1355 ('Interactive (global)', self.user_global_ns),
1356 1356 ('Python builtin', builtin_mod.__dict__),
1357 1357 ('Alias', self.alias_manager.alias_table),
1358 1358 ]
1359 1359 alias_ns = self.alias_manager.alias_table
1360 1360
1361 1361 # initialize results to 'null'
1362 1362 found = False; obj = None; ospace = None; ds = None;
1363 1363 ismagic = False; isalias = False; parent = None
1364 1364
1365 1365 # We need to special-case 'print', which as of python2.6 registers as a
1366 1366 # function but should only be treated as one if print_function was
1367 1367 # loaded with a future import. In this case, just bail.
1368 1368 if (oname == 'print' and not py3compat.PY3 and not \
1369 1369 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1370 1370 return {'found':found, 'obj':obj, 'namespace':ospace,
1371 1371 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1372 1372
1373 1373 # Look for the given name by splitting it in parts. If the head is
1374 1374 # found, then we look for all the remaining parts as members, and only
1375 1375 # declare success if we can find them all.
1376 1376 oname_parts = oname.split('.')
1377 1377 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1378 1378 for nsname,ns in namespaces:
1379 1379 try:
1380 1380 obj = ns[oname_head]
1381 1381 except KeyError:
1382 1382 continue
1383 1383 else:
1384 1384 #print 'oname_rest:', oname_rest # dbg
1385 1385 for part in oname_rest:
1386 1386 try:
1387 1387 parent = obj
1388 1388 obj = getattr(obj,part)
1389 1389 except:
1390 1390 # Blanket except b/c some badly implemented objects
1391 1391 # allow __getattr__ to raise exceptions other than
1392 1392 # AttributeError, which then crashes IPython.
1393 1393 break
1394 1394 else:
1395 1395 # If we finish the for loop (no break), we got all members
1396 1396 found = True
1397 1397 ospace = nsname
1398 1398 if ns == alias_ns:
1399 1399 isalias = True
1400 1400 break # namespace loop
1401 1401
1402 1402 # Try to see if it's magic
1403 1403 if not found:
1404 1404 obj = None
1405 1405 if oname.startswith(ESC_MAGIC2):
1406 1406 oname = oname.lstrip(ESC_MAGIC2)
1407 1407 obj = self.find_cell_magic(oname)
1408 1408 elif oname.startswith(ESC_MAGIC):
1409 1409 oname = oname.lstrip(ESC_MAGIC)
1410 1410 obj = self.find_line_magic(oname)
1411 1411 else:
1412 1412 # search without prefix, so run? will find %run?
1413 1413 obj = self.find_line_magic(oname)
1414 1414 if obj is None:
1415 1415 obj = self.find_cell_magic(oname)
1416 1416 if obj is not None:
1417 1417 found = True
1418 1418 ospace = 'IPython internal'
1419 1419 ismagic = True
1420 1420
1421 1421 # Last try: special-case some literals like '', [], {}, etc:
1422 1422 if not found and oname_head in ["''",'""','[]','{}','()']:
1423 1423 obj = eval(oname_head)
1424 1424 found = True
1425 1425 ospace = 'Interactive'
1426 1426
1427 1427 return {'found':found, 'obj':obj, 'namespace':ospace,
1428 1428 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1429 1429
1430 1430 def _ofind_property(self, oname, info):
1431 1431 """Second part of object finding, to look for property details."""
1432 1432 if info.found:
1433 1433 # Get the docstring of the class property if it exists.
1434 1434 path = oname.split('.')
1435 1435 root = '.'.join(path[:-1])
1436 1436 if info.parent is not None:
1437 1437 try:
1438 1438 target = getattr(info.parent, '__class__')
1439 1439 # The object belongs to a class instance.
1440 1440 try:
1441 1441 target = getattr(target, path[-1])
1442 1442 # The class defines the object.
1443 1443 if isinstance(target, property):
1444 1444 oname = root + '.__class__.' + path[-1]
1445 1445 info = Struct(self._ofind(oname))
1446 1446 except AttributeError: pass
1447 1447 except AttributeError: pass
1448 1448
1449 1449 # We return either the new info or the unmodified input if the object
1450 1450 # hadn't been found
1451 1451 return info
1452 1452
1453 1453 def _object_find(self, oname, namespaces=None):
1454 1454 """Find an object and return a struct with info about it."""
1455 1455 inf = Struct(self._ofind(oname, namespaces))
1456 1456 return Struct(self._ofind_property(oname, inf))
1457 1457
1458 1458 def _inspect(self, meth, oname, namespaces=None, **kw):
1459 1459 """Generic interface to the inspector system.
1460 1460
1461 1461 This function is meant to be called by pdef, pdoc & friends."""
1462 1462 info = self._object_find(oname, namespaces)
1463 1463 if info.found:
1464 1464 pmethod = getattr(self.inspector, meth)
1465 1465 formatter = format_screen if info.ismagic else None
1466 1466 if meth == 'pdoc':
1467 1467 pmethod(info.obj, oname, formatter)
1468 1468 elif meth == 'pinfo':
1469 1469 pmethod(info.obj, oname, formatter, info, **kw)
1470 1470 else:
1471 1471 pmethod(info.obj, oname)
1472 1472 else:
1473 1473 print('Object `%s` not found.' % oname)
1474 1474 return 'not found' # so callers can take other action
1475 1475
1476 1476 def object_inspect(self, oname, detail_level=0):
1477 1477 with self.builtin_trap:
1478 1478 info = self._object_find(oname)
1479 1479 if info.found:
1480 1480 return self.inspector.info(info.obj, oname, info=info,
1481 1481 detail_level=detail_level
1482 1482 )
1483 1483 else:
1484 1484 return oinspect.object_info(name=oname, found=False)
1485 1485
1486 1486 #-------------------------------------------------------------------------
1487 1487 # Things related to history management
1488 1488 #-------------------------------------------------------------------------
1489 1489
1490 1490 def init_history(self):
1491 1491 """Sets up the command history, and starts regular autosaves."""
1492 1492 self.history_manager = HistoryManager(shell=self, parent=self)
1493 1493 self.configurables.append(self.history_manager)
1494 1494
1495 1495 #-------------------------------------------------------------------------
1496 1496 # Things related to exception handling and tracebacks (not debugging)
1497 1497 #-------------------------------------------------------------------------
1498 1498
1499 1499 def init_traceback_handlers(self, custom_exceptions):
1500 1500 # Syntax error handler.
1501 1501 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1502 1502
1503 1503 # The interactive one is initialized with an offset, meaning we always
1504 1504 # want to remove the topmost item in the traceback, which is our own
1505 1505 # internal code. Valid modes: ['Plain','Context','Verbose']
1506 1506 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1507 1507 color_scheme='NoColor',
1508 1508 tb_offset = 1,
1509 1509 check_cache=check_linecache_ipython)
1510 1510
1511 1511 # The instance will store a pointer to the system-wide exception hook,
1512 1512 # so that runtime code (such as magics) can access it. This is because
1513 1513 # during the read-eval loop, it may get temporarily overwritten.
1514 1514 self.sys_excepthook = sys.excepthook
1515 1515
1516 1516 # and add any custom exception handlers the user may have specified
1517 1517 self.set_custom_exc(*custom_exceptions)
1518 1518
1519 1519 # Set the exception mode
1520 1520 self.InteractiveTB.set_mode(mode=self.xmode)
1521 1521
1522 1522 def set_custom_exc(self, exc_tuple, handler):
1523 1523 """set_custom_exc(exc_tuple,handler)
1524 1524
1525 1525 Set a custom exception handler, which will be called if any of the
1526 1526 exceptions in exc_tuple occur in the mainloop (specifically, in the
1527 1527 run_code() method).
1528 1528
1529 1529 Parameters
1530 1530 ----------
1531 1531
1532 1532 exc_tuple : tuple of exception classes
1533 1533 A *tuple* of exception classes, for which to call the defined
1534 1534 handler. It is very important that you use a tuple, and NOT A
1535 1535 LIST here, because of the way Python's except statement works. If
1536 1536 you only want to trap a single exception, use a singleton tuple::
1537 1537
1538 1538 exc_tuple == (MyCustomException,)
1539 1539
1540 1540 handler : callable
1541 1541 handler must have the following signature::
1542 1542
1543 1543 def my_handler(self, etype, value, tb, tb_offset=None):
1544 1544 ...
1545 1545 return structured_traceback
1546 1546
1547 1547 Your handler must return a structured traceback (a list of strings),
1548 1548 or None.
1549 1549
1550 1550 This will be made into an instance method (via types.MethodType)
1551 1551 of IPython itself, and it will be called if any of the exceptions
1552 1552 listed in the exc_tuple are caught. If the handler is None, an
1553 1553 internal basic one is used, which just prints basic info.
1554 1554
1555 1555 To protect IPython from crashes, if your handler ever raises an
1556 1556 exception or returns an invalid result, it will be immediately
1557 1557 disabled.
1558 1558
1559 1559 WARNING: by putting in your own exception handler into IPython's main
1560 1560 execution loop, you run a very good chance of nasty crashes. This
1561 1561 facility should only be used if you really know what you are doing."""
1562 1562
1563 1563 assert type(exc_tuple)==type(()) , \
1564 1564 "The custom exceptions must be given AS A TUPLE."
1565 1565
1566 1566 def dummy_handler(self,etype,value,tb,tb_offset=None):
1567 1567 print('*** Simple custom exception handler ***')
1568 1568 print('Exception type :',etype)
1569 1569 print('Exception value:',value)
1570 1570 print('Traceback :',tb)
1571 1571 #print 'Source code :','\n'.join(self.buffer)
1572 1572
1573 1573 def validate_stb(stb):
1574 1574 """validate structured traceback return type
1575 1575
1576 1576 return type of CustomTB *should* be a list of strings, but allow
1577 1577 single strings or None, which are harmless.
1578 1578
1579 1579 This function will *always* return a list of strings,
1580 1580 and will raise a TypeError if stb is inappropriate.
1581 1581 """
1582 1582 msg = "CustomTB must return list of strings, not %r" % stb
1583 1583 if stb is None:
1584 1584 return []
1585 1585 elif isinstance(stb, basestring):
1586 1586 return [stb]
1587 1587 elif not isinstance(stb, list):
1588 1588 raise TypeError(msg)
1589 1589 # it's a list
1590 1590 for line in stb:
1591 1591 # check every element
1592 1592 if not isinstance(line, basestring):
1593 1593 raise TypeError(msg)
1594 1594 return stb
1595 1595
1596 1596 if handler is None:
1597 1597 wrapped = dummy_handler
1598 1598 else:
1599 1599 def wrapped(self,etype,value,tb,tb_offset=None):
1600 1600 """wrap CustomTB handler, to protect IPython from user code
1601 1601
1602 1602 This makes it harder (but not impossible) for custom exception
1603 1603 handlers to crash IPython.
1604 1604 """
1605 1605 try:
1606 1606 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1607 1607 return validate_stb(stb)
1608 1608 except:
1609 1609 # clear custom handler immediately
1610 1610 self.set_custom_exc((), None)
1611 1611 print("Custom TB Handler failed, unregistering", file=io.stderr)
1612 1612 # show the exception in handler first
1613 1613 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1614 1614 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1615 1615 print("The original exception:", file=io.stdout)
1616 1616 stb = self.InteractiveTB.structured_traceback(
1617 1617 (etype,value,tb), tb_offset=tb_offset
1618 1618 )
1619 1619 return stb
1620 1620
1621 1621 self.CustomTB = types.MethodType(wrapped,self)
1622 1622 self.custom_exceptions = exc_tuple
1623 1623
1624 1624 def excepthook(self, etype, value, tb):
1625 1625 """One more defense for GUI apps that call sys.excepthook.
1626 1626
1627 1627 GUI frameworks like wxPython trap exceptions and call
1628 1628 sys.excepthook themselves. I guess this is a feature that
1629 1629 enables them to keep running after exceptions that would
1630 1630 otherwise kill their mainloop. This is a bother for IPython
1631 1631 which excepts to catch all of the program exceptions with a try:
1632 1632 except: statement.
1633 1633
1634 1634 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1635 1635 any app directly invokes sys.excepthook, it will look to the user like
1636 1636 IPython crashed. In order to work around this, we can disable the
1637 1637 CrashHandler and replace it with this excepthook instead, which prints a
1638 1638 regular traceback using our InteractiveTB. In this fashion, apps which
1639 1639 call sys.excepthook will generate a regular-looking exception from
1640 1640 IPython, and the CrashHandler will only be triggered by real IPython
1641 1641 crashes.
1642 1642
1643 1643 This hook should be used sparingly, only in places which are not likely
1644 1644 to be true IPython errors.
1645 1645 """
1646 1646 self.showtraceback((etype,value,tb),tb_offset=0)
1647 1647
1648 1648 def _get_exc_info(self, exc_tuple=None):
1649 1649 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1650 1650
1651 1651 Ensures sys.last_type,value,traceback hold the exc_info we found,
1652 1652 from whichever source.
1653 1653
1654 1654 raises ValueError if none of these contain any information
1655 1655 """
1656 1656 if exc_tuple is None:
1657 1657 etype, value, tb = sys.exc_info()
1658 1658 else:
1659 1659 etype, value, tb = exc_tuple
1660 1660
1661 1661 if etype is None:
1662 1662 if hasattr(sys, 'last_type'):
1663 1663 etype, value, tb = sys.last_type, sys.last_value, \
1664 1664 sys.last_traceback
1665 1665
1666 1666 if etype is None:
1667 1667 raise ValueError("No exception to find")
1668 1668
1669 1669 # Now store the exception info in sys.last_type etc.
1670 1670 # WARNING: these variables are somewhat deprecated and not
1671 1671 # necessarily safe to use in a threaded environment, but tools
1672 1672 # like pdb depend on their existence, so let's set them. If we
1673 1673 # find problems in the field, we'll need to revisit their use.
1674 1674 sys.last_type = etype
1675 1675 sys.last_value = value
1676 1676 sys.last_traceback = tb
1677 1677
1678 1678 return etype, value, tb
1679 1679
1680 1680 def show_usage_error(self, exc):
1681 1681 """Show a short message for UsageErrors
1682 1682
1683 1683 These are special exceptions that shouldn't show a traceback.
1684 1684 """
1685 1685 self.write_err("UsageError: %s" % exc)
1686 1686
1687 1687 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1688 1688 exception_only=False):
1689 1689 """Display the exception that just occurred.
1690 1690
1691 1691 If nothing is known about the exception, this is the method which
1692 1692 should be used throughout the code for presenting user tracebacks,
1693 1693 rather than directly invoking the InteractiveTB object.
1694 1694
1695 1695 A specific showsyntaxerror() also exists, but this method can take
1696 1696 care of calling it if needed, so unless you are explicitly catching a
1697 1697 SyntaxError exception, don't try to analyze the stack manually and
1698 1698 simply call this method."""
1699 1699
1700 1700 try:
1701 1701 try:
1702 1702 etype, value, tb = self._get_exc_info(exc_tuple)
1703 1703 except ValueError:
1704 1704 self.write_err('No traceback available to show.\n')
1705 1705 return
1706 1706
1707 1707 if issubclass(etype, SyntaxError):
1708 1708 # Though this won't be called by syntax errors in the input
1709 1709 # line, there may be SyntaxError cases with imported code.
1710 1710 self.showsyntaxerror(filename)
1711 1711 elif etype is UsageError:
1712 1712 self.show_usage_error(value)
1713 1713 else:
1714 1714 if exception_only:
1715 1715 stb = ['An exception has occurred, use %tb to see '
1716 1716 'the full traceback.\n']
1717 1717 stb.extend(self.InteractiveTB.get_exception_only(etype,
1718 1718 value))
1719 1719 else:
1720 1720 try:
1721 1721 # Exception classes can customise their traceback - we
1722 1722 # use this in IPython.parallel for exceptions occurring
1723 1723 # in the engines. This should return a list of strings.
1724 1724 stb = value._render_traceback_()
1725 1725 except Exception:
1726 1726 stb = self.InteractiveTB.structured_traceback(etype,
1727 1727 value, tb, tb_offset=tb_offset)
1728 1728
1729 1729 self._showtraceback(etype, value, stb)
1730 1730 if self.call_pdb:
1731 1731 # drop into debugger
1732 1732 self.debugger(force=True)
1733 1733 return
1734 1734
1735 1735 # Actually show the traceback
1736 1736 self._showtraceback(etype, value, stb)
1737 1737
1738 1738 except KeyboardInterrupt:
1739 1739 self.write_err("\nKeyboardInterrupt\n")
1740 1740
1741 1741 def _showtraceback(self, etype, evalue, stb):
1742 1742 """Actually show a traceback.
1743 1743
1744 1744 Subclasses may override this method to put the traceback on a different
1745 1745 place, like a side channel.
1746 1746 """
1747 1747 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1748 1748
1749 1749 def showsyntaxerror(self, filename=None):
1750 1750 """Display the syntax error that just occurred.
1751 1751
1752 1752 This doesn't display a stack trace because there isn't one.
1753 1753
1754 1754 If a filename is given, it is stuffed in the exception instead
1755 1755 of what was there before (because Python's parser always uses
1756 1756 "<string>" when reading from a string).
1757 1757 """
1758 1758 etype, value, last_traceback = self._get_exc_info()
1759 1759
1760 1760 if filename and issubclass(etype, SyntaxError):
1761 1761 try:
1762 1762 value.filename = filename
1763 1763 except:
1764 1764 # Not the format we expect; leave it alone
1765 1765 pass
1766 1766
1767 1767 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1768 1768 self._showtraceback(etype, value, stb)
1769 1769
1770 1770 # This is overridden in TerminalInteractiveShell to show a message about
1771 1771 # the %paste magic.
1772 1772 def showindentationerror(self):
1773 1773 """Called by run_cell when there's an IndentationError in code entered
1774 1774 at the prompt.
1775 1775
1776 1776 This is overridden in TerminalInteractiveShell to show a message about
1777 1777 the %paste magic."""
1778 1778 self.showsyntaxerror()
1779 1779
1780 1780 #-------------------------------------------------------------------------
1781 1781 # Things related to readline
1782 1782 #-------------------------------------------------------------------------
1783 1783
1784 1784 def init_readline(self):
1785 1785 """Command history completion/saving/reloading."""
1786 1786
1787 1787 if self.readline_use:
1788 1788 import IPython.utils.rlineimpl as readline
1789 1789
1790 1790 self.rl_next_input = None
1791 1791 self.rl_do_indent = False
1792 1792
1793 1793 if not self.readline_use or not readline.have_readline:
1794 1794 self.has_readline = False
1795 1795 self.readline = None
1796 1796 # Set a number of methods that depend on readline to be no-op
1797 1797 self.readline_no_record = no_op_context
1798 1798 self.set_readline_completer = no_op
1799 1799 self.set_custom_completer = no_op
1800 1800 if self.readline_use:
1801 1801 warn('Readline services not available or not loaded.')
1802 1802 else:
1803 1803 self.has_readline = True
1804 1804 self.readline = readline
1805 1805 sys.modules['readline'] = readline
1806 1806
1807 1807 # Platform-specific configuration
1808 1808 if os.name == 'nt':
1809 1809 # FIXME - check with Frederick to see if we can harmonize
1810 1810 # naming conventions with pyreadline to avoid this
1811 1811 # platform-dependent check
1812 1812 self.readline_startup_hook = readline.set_pre_input_hook
1813 1813 else:
1814 1814 self.readline_startup_hook = readline.set_startup_hook
1815 1815
1816 1816 # Load user's initrc file (readline config)
1817 1817 # Or if libedit is used, load editrc.
1818 1818 inputrc_name = os.environ.get('INPUTRC')
1819 1819 if inputrc_name is None:
1820 1820 inputrc_name = '.inputrc'
1821 1821 if readline.uses_libedit:
1822 1822 inputrc_name = '.editrc'
1823 1823 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1824 1824 if os.path.isfile(inputrc_name):
1825 1825 try:
1826 1826 readline.read_init_file(inputrc_name)
1827 1827 except:
1828 1828 warn('Problems reading readline initialization file <%s>'
1829 1829 % inputrc_name)
1830 1830
1831 1831 # Configure readline according to user's prefs
1832 1832 # This is only done if GNU readline is being used. If libedit
1833 1833 # is being used (as on Leopard) the readline config is
1834 1834 # not run as the syntax for libedit is different.
1835 1835 if not readline.uses_libedit:
1836 1836 for rlcommand in self.readline_parse_and_bind:
1837 1837 #print "loading rl:",rlcommand # dbg
1838 1838 readline.parse_and_bind(rlcommand)
1839 1839
1840 1840 # Remove some chars from the delimiters list. If we encounter
1841 1841 # unicode chars, discard them.
1842 1842 delims = readline.get_completer_delims()
1843 1843 if not py3compat.PY3:
1844 1844 delims = delims.encode("ascii", "ignore")
1845 1845 for d in self.readline_remove_delims:
1846 1846 delims = delims.replace(d, "")
1847 1847 delims = delims.replace(ESC_MAGIC, '')
1848 1848 readline.set_completer_delims(delims)
1849 1849 # Store these so we can restore them if something like rpy2 modifies
1850 1850 # them.
1851 1851 self.readline_delims = delims
1852 1852 # otherwise we end up with a monster history after a while:
1853 1853 readline.set_history_length(self.history_length)
1854 1854
1855 1855 self.refill_readline_hist()
1856 1856 self.readline_no_record = ReadlineNoRecord(self)
1857 1857
1858 1858 # Configure auto-indent for all platforms
1859 1859 self.set_autoindent(self.autoindent)
1860 1860
1861 1861 def refill_readline_hist(self):
1862 1862 # Load the last 1000 lines from history
1863 1863 self.readline.clear_history()
1864 1864 stdin_encoding = sys.stdin.encoding or "utf-8"
1865 1865 last_cell = u""
1866 1866 for _, _, cell in self.history_manager.get_tail(1000,
1867 1867 include_latest=True):
1868 1868 # Ignore blank lines and consecutive duplicates
1869 1869 cell = cell.rstrip()
1870 1870 if cell and (cell != last_cell):
1871 1871 try:
1872 1872 if self.multiline_history:
1873 1873 self.readline.add_history(py3compat.unicode_to_str(cell,
1874 1874 stdin_encoding))
1875 1875 else:
1876 1876 for line in cell.splitlines():
1877 1877 self.readline.add_history(py3compat.unicode_to_str(line,
1878 1878 stdin_encoding))
1879 1879 last_cell = cell
1880 1880
1881 1881 except TypeError:
1882 1882 # The history DB can get corrupted so it returns strings
1883 1883 # containing null bytes, which readline objects to.
1884 1884 continue
1885 1885
1886 1886 @skip_doctest
1887 1887 def set_next_input(self, s):
1888 1888 """ Sets the 'default' input string for the next command line.
1889 1889
1890 1890 Requires readline.
1891 1891
1892 1892 Example::
1893 1893
1894 1894 In [1]: _ip.set_next_input("Hello Word")
1895 1895 In [2]: Hello Word_ # cursor is here
1896 1896 """
1897 1897 self.rl_next_input = py3compat.cast_bytes_py2(s)
1898 1898
1899 1899 # Maybe move this to the terminal subclass?
1900 1900 def pre_readline(self):
1901 1901 """readline hook to be used at the start of each line.
1902 1902
1903 1903 Currently it handles auto-indent only."""
1904 1904
1905 1905 if self.rl_do_indent:
1906 1906 self.readline.insert_text(self._indent_current_str())
1907 1907 if self.rl_next_input is not None:
1908 1908 self.readline.insert_text(self.rl_next_input)
1909 1909 self.rl_next_input = None
1910 1910
1911 1911 def _indent_current_str(self):
1912 1912 """return the current level of indentation as a string"""
1913 1913 return self.input_splitter.indent_spaces * ' '
1914 1914
1915 1915 #-------------------------------------------------------------------------
1916 1916 # Things related to text completion
1917 1917 #-------------------------------------------------------------------------
1918 1918
1919 1919 def init_completer(self):
1920 1920 """Initialize the completion machinery.
1921 1921
1922 1922 This creates completion machinery that can be used by client code,
1923 1923 either interactively in-process (typically triggered by the readline
1924 1924 library), programatically (such as in test suites) or out-of-prcess
1925 1925 (typically over the network by remote frontends).
1926 1926 """
1927 1927 from IPython.core.completer import IPCompleter
1928 1928 from IPython.core.completerlib import (module_completer,
1929 1929 magic_run_completer, cd_completer, reset_completer)
1930 1930
1931 1931 self.Completer = IPCompleter(shell=self,
1932 1932 namespace=self.user_ns,
1933 1933 global_namespace=self.user_global_ns,
1934 1934 alias_table=self.alias_manager.alias_table,
1935 1935 use_readline=self.has_readline,
1936 1936 parent=self,
1937 1937 )
1938 1938 self.configurables.append(self.Completer)
1939 1939
1940 1940 # Add custom completers to the basic ones built into IPCompleter
1941 1941 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1942 1942 self.strdispatchers['complete_command'] = sdisp
1943 1943 self.Completer.custom_completers = sdisp
1944 1944
1945 1945 self.set_hook('complete_command', module_completer, str_key = 'import')
1946 1946 self.set_hook('complete_command', module_completer, str_key = 'from')
1947 1947 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1948 1948 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1949 1949 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1950 1950
1951 1951 # Only configure readline if we truly are using readline. IPython can
1952 1952 # do tab-completion over the network, in GUIs, etc, where readline
1953 1953 # itself may be absent
1954 1954 if self.has_readline:
1955 1955 self.set_readline_completer()
1956 1956
1957 1957 def complete(self, text, line=None, cursor_pos=None):
1958 1958 """Return the completed text and a list of completions.
1959 1959
1960 1960 Parameters
1961 1961 ----------
1962 1962
1963 1963 text : string
1964 1964 A string of text to be completed on. It can be given as empty and
1965 1965 instead a line/position pair are given. In this case, the
1966 1966 completer itself will split the line like readline does.
1967 1967
1968 1968 line : string, optional
1969 1969 The complete line that text is part of.
1970 1970
1971 1971 cursor_pos : int, optional
1972 1972 The position of the cursor on the input line.
1973 1973
1974 1974 Returns
1975 1975 -------
1976 1976 text : string
1977 1977 The actual text that was completed.
1978 1978
1979 1979 matches : list
1980 1980 A sorted list with all possible completions.
1981 1981
1982 1982 The optional arguments allow the completion to take more context into
1983 1983 account, and are part of the low-level completion API.
1984 1984
1985 1985 This is a wrapper around the completion mechanism, similar to what
1986 1986 readline does at the command line when the TAB key is hit. By
1987 1987 exposing it as a method, it can be used by other non-readline
1988 1988 environments (such as GUIs) for text completion.
1989 1989
1990 1990 Simple usage example:
1991 1991
1992 1992 In [1]: x = 'hello'
1993 1993
1994 1994 In [2]: _ip.complete('x.l')
1995 1995 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1996 1996 """
1997 1997
1998 1998 # Inject names into __builtin__ so we can complete on the added names.
1999 1999 with self.builtin_trap:
2000 2000 return self.Completer.complete(text, line, cursor_pos)
2001 2001
2002 2002 def set_custom_completer(self, completer, pos=0):
2003 2003 """Adds a new custom completer function.
2004 2004
2005 2005 The position argument (defaults to 0) is the index in the completers
2006 2006 list where you want the completer to be inserted."""
2007 2007
2008 2008 newcomp = types.MethodType(completer,self.Completer)
2009 2009 self.Completer.matchers.insert(pos,newcomp)
2010 2010
2011 2011 def set_readline_completer(self):
2012 2012 """Reset readline's completer to be our own."""
2013 2013 self.readline.set_completer(self.Completer.rlcomplete)
2014 2014
2015 2015 def set_completer_frame(self, frame=None):
2016 2016 """Set the frame of the completer."""
2017 2017 if frame:
2018 2018 self.Completer.namespace = frame.f_locals
2019 2019 self.Completer.global_namespace = frame.f_globals
2020 2020 else:
2021 2021 self.Completer.namespace = self.user_ns
2022 2022 self.Completer.global_namespace = self.user_global_ns
2023 2023
2024 2024 #-------------------------------------------------------------------------
2025 2025 # Things related to magics
2026 2026 #-------------------------------------------------------------------------
2027 2027
2028 2028 def init_magics(self):
2029 2029 from IPython.core import magics as m
2030 2030 self.magics_manager = magic.MagicsManager(shell=self,
2031 2031 parent=self,
2032 2032 user_magics=m.UserMagics(self))
2033 2033 self.configurables.append(self.magics_manager)
2034 2034
2035 2035 # Expose as public API from the magics manager
2036 2036 self.register_magics = self.magics_manager.register
2037 2037 self.define_magic = self.magics_manager.define_magic
2038 2038
2039 2039 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2040 2040 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2041 2041 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2042 2042 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2043 2043 )
2044 2044
2045 2045 # Register Magic Aliases
2046 2046 mman = self.magics_manager
2047 2047 # FIXME: magic aliases should be defined by the Magics classes
2048 2048 # or in MagicsManager, not here
2049 2049 mman.register_alias('ed', 'edit')
2050 2050 mman.register_alias('hist', 'history')
2051 2051 mman.register_alias('rep', 'recall')
2052 2052 mman.register_alias('SVG', 'svg', 'cell')
2053 2053 mman.register_alias('HTML', 'html', 'cell')
2054 2054 mman.register_alias('file', 'writefile', 'cell')
2055 2055
2056 2056 # FIXME: Move the color initialization to the DisplayHook, which
2057 2057 # should be split into a prompt manager and displayhook. We probably
2058 2058 # even need a centralize colors management object.
2059 2059 self.magic('colors %s' % self.colors)
2060 2060
2061 2061 # Defined here so that it's included in the documentation
2062 2062 @functools.wraps(magic.MagicsManager.register_function)
2063 2063 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2064 2064 self.magics_manager.register_function(func,
2065 2065 magic_kind=magic_kind, magic_name=magic_name)
2066 2066
2067 2067 def run_line_magic(self, magic_name, line):
2068 2068 """Execute the given line magic.
2069 2069
2070 2070 Parameters
2071 2071 ----------
2072 2072 magic_name : str
2073 2073 Name of the desired magic function, without '%' prefix.
2074 2074
2075 2075 line : str
2076 2076 The rest of the input line as a single string.
2077 2077 """
2078 2078 fn = self.find_line_magic(magic_name)
2079 2079 if fn is None:
2080 2080 cm = self.find_cell_magic(magic_name)
2081 2081 etpl = "Line magic function `%%%s` not found%s."
2082 2082 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2083 2083 'did you mean that instead?)' % magic_name )
2084 2084 error(etpl % (magic_name, extra))
2085 2085 else:
2086 2086 # Note: this is the distance in the stack to the user's frame.
2087 2087 # This will need to be updated if the internal calling logic gets
2088 2088 # refactored, or else we'll be expanding the wrong variables.
2089 2089 stack_depth = 2
2090 2090 magic_arg_s = self.var_expand(line, stack_depth)
2091 2091 # Put magic args in a list so we can call with f(*a) syntax
2092 2092 args = [magic_arg_s]
2093 2093 kwargs = {}
2094 2094 # Grab local namespace if we need it:
2095 2095 if getattr(fn, "needs_local_scope", False):
2096 2096 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2097 2097 with self.builtin_trap:
2098 2098 result = fn(*args,**kwargs)
2099 2099 return result
2100 2100
2101 2101 def run_cell_magic(self, magic_name, line, cell):
2102 2102 """Execute the given cell magic.
2103 2103
2104 2104 Parameters
2105 2105 ----------
2106 2106 magic_name : str
2107 2107 Name of the desired magic function, without '%' prefix.
2108 2108
2109 2109 line : str
2110 2110 The rest of the first input line as a single string.
2111 2111
2112 2112 cell : str
2113 2113 The body of the cell as a (possibly multiline) string.
2114 2114 """
2115 2115 fn = self.find_cell_magic(magic_name)
2116 2116 if fn is None:
2117 2117 lm = self.find_line_magic(magic_name)
2118 2118 etpl = "Cell magic `%%{0}` not found{1}."
2119 2119 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2120 2120 'did you mean that instead?)'.format(magic_name))
2121 2121 error(etpl.format(magic_name, extra))
2122 2122 elif cell == '':
2123 2123 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2124 2124 if self.find_line_magic(magic_name) is not None:
2125 2125 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2126 2126 raise UsageError(message)
2127 2127 else:
2128 2128 # Note: this is the distance in the stack to the user's frame.
2129 2129 # This will need to be updated if the internal calling logic gets
2130 2130 # refactored, or else we'll be expanding the wrong variables.
2131 2131 stack_depth = 2
2132 2132 magic_arg_s = self.var_expand(line, stack_depth)
2133 2133 with self.builtin_trap:
2134 2134 result = fn(magic_arg_s, cell)
2135 2135 return result
2136 2136
2137 2137 def find_line_magic(self, magic_name):
2138 2138 """Find and return a line magic by name.
2139 2139
2140 2140 Returns None if the magic isn't found."""
2141 2141 return self.magics_manager.magics['line'].get(magic_name)
2142 2142
2143 2143 def find_cell_magic(self, magic_name):
2144 2144 """Find and return a cell magic by name.
2145 2145
2146 2146 Returns None if the magic isn't found."""
2147 2147 return self.magics_manager.magics['cell'].get(magic_name)
2148 2148
2149 2149 def find_magic(self, magic_name, magic_kind='line'):
2150 2150 """Find and return a magic of the given type by name.
2151 2151
2152 2152 Returns None if the magic isn't found."""
2153 2153 return self.magics_manager.magics[magic_kind].get(magic_name)
2154 2154
2155 2155 def magic(self, arg_s):
2156 2156 """DEPRECATED. Use run_line_magic() instead.
2157 2157
2158 2158 Call a magic function by name.
2159 2159
2160 2160 Input: a string containing the name of the magic function to call and
2161 2161 any additional arguments to be passed to the magic.
2162 2162
2163 2163 magic('name -opt foo bar') is equivalent to typing at the ipython
2164 2164 prompt:
2165 2165
2166 2166 In[1]: %name -opt foo bar
2167 2167
2168 2168 To call a magic without arguments, simply use magic('name').
2169 2169
2170 2170 This provides a proper Python function to call IPython's magics in any
2171 2171 valid Python code you can type at the interpreter, including loops and
2172 2172 compound statements.
2173 2173 """
2174 2174 # TODO: should we issue a loud deprecation warning here?
2175 2175 magic_name, _, magic_arg_s = arg_s.partition(' ')
2176 2176 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2177 2177 return self.run_line_magic(magic_name, magic_arg_s)
2178 2178
2179 2179 #-------------------------------------------------------------------------
2180 2180 # Things related to macros
2181 2181 #-------------------------------------------------------------------------
2182 2182
2183 2183 def define_macro(self, name, themacro):
2184 2184 """Define a new macro
2185 2185
2186 2186 Parameters
2187 2187 ----------
2188 2188 name : str
2189 2189 The name of the macro.
2190 2190 themacro : str or Macro
2191 2191 The action to do upon invoking the macro. If a string, a new
2192 2192 Macro object is created by passing the string to it.
2193 2193 """
2194 2194
2195 2195 from IPython.core import macro
2196 2196
2197 2197 if isinstance(themacro, basestring):
2198 2198 themacro = macro.Macro(themacro)
2199 2199 if not isinstance(themacro, macro.Macro):
2200 2200 raise ValueError('A macro must be a string or a Macro instance.')
2201 2201 self.user_ns[name] = themacro
2202 2202
2203 2203 #-------------------------------------------------------------------------
2204 2204 # Things related to the running of system commands
2205 2205 #-------------------------------------------------------------------------
2206 2206
2207 2207 def system_piped(self, cmd):
2208 2208 """Call the given cmd in a subprocess, piping stdout/err
2209 2209
2210 2210 Parameters
2211 2211 ----------
2212 2212 cmd : str
2213 2213 Command to execute (can not end in '&', as background processes are
2214 2214 not supported. Should not be a command that expects input
2215 2215 other than simple text.
2216 2216 """
2217 2217 if cmd.rstrip().endswith('&'):
2218 2218 # this is *far* from a rigorous test
2219 2219 # We do not support backgrounding processes because we either use
2220 2220 # pexpect or pipes to read from. Users can always just call
2221 2221 # os.system() or use ip.system=ip.system_raw
2222 2222 # if they really want a background process.
2223 2223 raise OSError("Background processes not supported.")
2224 2224
2225 2225 # we explicitly do NOT return the subprocess status code, because
2226 2226 # a non-None value would trigger :func:`sys.displayhook` calls.
2227 2227 # Instead, we store the exit_code in user_ns.
2228 2228 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2229 2229
2230 2230 def system_raw(self, cmd):
2231 2231 """Call the given cmd in a subprocess using os.system
2232 2232
2233 2233 Parameters
2234 2234 ----------
2235 2235 cmd : str
2236 2236 Command to execute.
2237 2237 """
2238 2238 cmd = self.var_expand(cmd, depth=1)
2239 2239 # protect os.system from UNC paths on Windows, which it can't handle:
2240 2240 if sys.platform == 'win32':
2241 2241 from IPython.utils._process_win32 import AvoidUNCPath
2242 2242 with AvoidUNCPath() as path:
2243 2243 if path is not None:
2244 2244 cmd = '"pushd %s &&"%s' % (path, cmd)
2245 2245 cmd = py3compat.unicode_to_str(cmd)
2246 2246 ec = os.system(cmd)
2247 2247 else:
2248 2248 cmd = py3compat.unicode_to_str(cmd)
2249 2249 ec = os.system(cmd)
2250 2250 # The high byte is the exit code, the low byte is a signal number
2251 2251 # that we discard for now. See the docs for os.wait()
2252 2252 if ec > 255:
2253 2253 ec >>= 8
2254 2254
2255 2255 # We explicitly do NOT return the subprocess status code, because
2256 2256 # a non-None value would trigger :func:`sys.displayhook` calls.
2257 2257 # Instead, we store the exit_code in user_ns.
2258 2258 self.user_ns['_exit_code'] = ec
2259 2259
2260 2260 # use piped system by default, because it is better behaved
2261 2261 system = system_piped
2262 2262
2263 2263 def getoutput(self, cmd, split=True, depth=0):
2264 2264 """Get output (possibly including stderr) from a subprocess.
2265 2265
2266 2266 Parameters
2267 2267 ----------
2268 2268 cmd : str
2269 2269 Command to execute (can not end in '&', as background processes are
2270 2270 not supported.
2271 2271 split : bool, optional
2272 2272 If True, split the output into an IPython SList. Otherwise, an
2273 2273 IPython LSString is returned. These are objects similar to normal
2274 2274 lists and strings, with a few convenience attributes for easier
2275 2275 manipulation of line-based output. You can use '?' on them for
2276 2276 details.
2277 2277 depth : int, optional
2278 2278 How many frames above the caller are the local variables which should
2279 2279 be expanded in the command string? The default (0) assumes that the
2280 2280 expansion variables are in the stack frame calling this function.
2281 2281 """
2282 2282 if cmd.rstrip().endswith('&'):
2283 2283 # this is *far* from a rigorous test
2284 2284 raise OSError("Background processes not supported.")
2285 2285 out = getoutput(self.var_expand(cmd, depth=depth+1))
2286 2286 if split:
2287 2287 out = SList(out.splitlines())
2288 2288 else:
2289 2289 out = LSString(out)
2290 2290 return out
2291 2291
2292 2292 #-------------------------------------------------------------------------
2293 2293 # Things related to aliases
2294 2294 #-------------------------------------------------------------------------
2295 2295
2296 2296 def init_alias(self):
2297 2297 self.alias_manager = AliasManager(shell=self, parent=self)
2298 2298 self.configurables.append(self.alias_manager)
2299 2299 self.ns_table['alias'] = self.alias_manager.alias_table,
2300 2300
2301 2301 #-------------------------------------------------------------------------
2302 2302 # Things related to extensions
2303 2303 #-------------------------------------------------------------------------
2304 2304
2305 2305 def init_extension_manager(self):
2306 2306 self.extension_manager = ExtensionManager(shell=self, parent=self)
2307 2307 self.configurables.append(self.extension_manager)
2308 2308
2309 2309 #-------------------------------------------------------------------------
2310 2310 # Things related to payloads
2311 2311 #-------------------------------------------------------------------------
2312 2312
2313 2313 def init_payload(self):
2314 2314 self.payload_manager = PayloadManager(parent=self)
2315 2315 self.configurables.append(self.payload_manager)
2316 2316
2317 2317 #-------------------------------------------------------------------------
2318 2318 # Things related to the prefilter
2319 2319 #-------------------------------------------------------------------------
2320 2320
2321 2321 def init_prefilter(self):
2322 2322 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2323 2323 self.configurables.append(self.prefilter_manager)
2324 2324 # Ultimately this will be refactored in the new interpreter code, but
2325 2325 # for now, we should expose the main prefilter method (there's legacy
2326 2326 # code out there that may rely on this).
2327 2327 self.prefilter = self.prefilter_manager.prefilter_lines
2328 2328
2329 2329 def auto_rewrite_input(self, cmd):
2330 2330 """Print to the screen the rewritten form of the user's command.
2331 2331
2332 2332 This shows visual feedback by rewriting input lines that cause
2333 2333 automatic calling to kick in, like::
2334 2334
2335 2335 /f x
2336 2336
2337 2337 into::
2338 2338
2339 2339 ------> f(x)
2340 2340
2341 2341 after the user's input prompt. This helps the user understand that the
2342 2342 input line was transformed automatically by IPython.
2343 2343 """
2344 2344 if not self.show_rewritten_input:
2345 2345 return
2346 2346
2347 2347 rw = self.prompt_manager.render('rewrite') + cmd
2348 2348
2349 2349 try:
2350 2350 # plain ascii works better w/ pyreadline, on some machines, so
2351 2351 # we use it and only print uncolored rewrite if we have unicode
2352 2352 rw = str(rw)
2353 2353 print(rw, file=io.stdout)
2354 2354 except UnicodeEncodeError:
2355 2355 print("------> " + cmd)
2356 2356
2357 2357 #-------------------------------------------------------------------------
2358 2358 # Things related to extracting values/expressions from kernel and user_ns
2359 2359 #-------------------------------------------------------------------------
2360 2360
2361 2361 def _user_obj_error(self):
2362 2362 """return simple exception dict
2363 2363
2364 2364 for use in user_variables / expressions
2365 2365 """
2366 2366
2367 2367 etype, evalue, tb = self._get_exc_info()
2368 2368 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2369 2369
2370 2370 exc_info = {
2371 2371 u'status' : 'error',
2372 2372 u'traceback' : stb,
2373 2373 u'ename' : unicode(etype.__name__),
2374 2374 u'evalue' : py3compat.safe_unicode(evalue),
2375 2375 }
2376 2376
2377 2377 return exc_info
2378 2378
2379 2379 def _format_user_obj(self, obj):
2380 2380 """format a user object to display dict
2381 2381
2382 2382 for use in user_expressions / variables
2383 2383 """
2384 2384
2385 2385 data, md = self.display_formatter.format(obj)
2386 2386 value = {
2387 2387 'status' : 'ok',
2388 2388 'data' : data,
2389 2389 'metadata' : md,
2390 2390 }
2391 2391 return value
2392 2392
2393 2393 def user_variables(self, names):
2394 2394 """Get a list of variable names from the user's namespace.
2395 2395
2396 2396 Parameters
2397 2397 ----------
2398 2398 names : list of strings
2399 2399 A list of names of variables to be read from the user namespace.
2400 2400
2401 2401 Returns
2402 2402 -------
2403 2403 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2404 2404 Each element will be a sub-dict of the same form as a display_data message.
2405 2405 """
2406 2406 out = {}
2407 2407 user_ns = self.user_ns
2408 2408
2409 2409 for varname in names:
2410 2410 try:
2411 2411 value = self._format_user_obj(user_ns[varname])
2412 2412 except:
2413 2413 value = self._user_obj_error()
2414 2414 out[varname] = value
2415 2415 return out
2416 2416
2417 2417 def user_expressions(self, expressions):
2418 2418 """Evaluate a dict of expressions in the user's namespace.
2419 2419
2420 2420 Parameters
2421 2421 ----------
2422 2422 expressions : dict
2423 2423 A dict with string keys and string values. The expression values
2424 2424 should be valid Python expressions, each of which will be evaluated
2425 2425 in the user namespace.
2426 2426
2427 2427 Returns
2428 2428 -------
2429 2429 A dict, keyed like the input expressions dict, with the rich mime-typed
2430 2430 display_data of each value.
2431 2431 """
2432 2432 out = {}
2433 2433 user_ns = self.user_ns
2434 2434 global_ns = self.user_global_ns
2435 2435
2436 2436 for key, expr in expressions.iteritems():
2437 2437 try:
2438 2438 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2439 2439 except:
2440 2440 value = self._user_obj_error()
2441 2441 out[key] = value
2442 2442 return out
2443 2443
2444 2444 #-------------------------------------------------------------------------
2445 2445 # Things related to the running of code
2446 2446 #-------------------------------------------------------------------------
2447 2447
2448 2448 def ex(self, cmd):
2449 2449 """Execute a normal python statement in user namespace."""
2450 2450 with self.builtin_trap:
2451 2451 exec cmd in self.user_global_ns, self.user_ns
2452 2452
2453 2453 def ev(self, expr):
2454 2454 """Evaluate python expression expr in user namespace.
2455 2455
2456 2456 Returns the result of evaluation
2457 2457 """
2458 2458 with self.builtin_trap:
2459 2459 return eval(expr, self.user_global_ns, self.user_ns)
2460 2460
2461 2461 def safe_execfile(self, fname, *where, **kw):
2462 2462 """A safe version of the builtin execfile().
2463 2463
2464 2464 This version will never throw an exception, but instead print
2465 2465 helpful error messages to the screen. This only works on pure
2466 2466 Python files with the .py extension.
2467 2467
2468 2468 Parameters
2469 2469 ----------
2470 2470 fname : string
2471 2471 The name of the file to be executed.
2472 2472 where : tuple
2473 2473 One or two namespaces, passed to execfile() as (globals,locals).
2474 2474 If only one is given, it is passed as both.
2475 2475 exit_ignore : bool (False)
2476 2476 If True, then silence SystemExit for non-zero status (it is always
2477 2477 silenced for zero status, as it is so common).
2478 2478 raise_exceptions : bool (False)
2479 2479 If True raise exceptions everywhere. Meant for testing.
2480 2480
2481 2481 """
2482 2482 kw.setdefault('exit_ignore', False)
2483 2483 kw.setdefault('raise_exceptions', False)
2484 2484
2485 2485 fname = os.path.abspath(os.path.expanduser(fname))
2486 2486
2487 2487 # Make sure we can open the file
2488 2488 try:
2489 2489 with open(fname) as thefile:
2490 2490 pass
2491 2491 except:
2492 2492 warn('Could not open file <%s> for safe execution.' % fname)
2493 2493 return
2494 2494
2495 2495 # Find things also in current directory. This is needed to mimic the
2496 2496 # behavior of running a script from the system command line, where
2497 2497 # Python inserts the script's directory into sys.path
2498 2498 dname = os.path.dirname(fname)
2499 2499
2500 2500 with prepended_to_syspath(dname):
2501 2501 try:
2502 2502 py3compat.execfile(fname,*where)
2503 2503 except SystemExit as status:
2504 2504 # If the call was made with 0 or None exit status (sys.exit(0)
2505 2505 # or sys.exit() ), don't bother showing a traceback, as both of
2506 2506 # these are considered normal by the OS:
2507 2507 # > python -c'import sys;sys.exit(0)'; echo $?
2508 2508 # 0
2509 2509 # > python -c'import sys;sys.exit()'; echo $?
2510 2510 # 0
2511 2511 # For other exit status, we show the exception unless
2512 2512 # explicitly silenced, but only in short form.
2513 2513 if kw['raise_exceptions']:
2514 2514 raise
2515 2515 if status.code and not kw['exit_ignore']:
2516 2516 self.showtraceback(exception_only=True)
2517 2517 except:
2518 2518 if kw['raise_exceptions']:
2519 2519 raise
2520 2520 self.showtraceback()
2521 2521
2522 2522 def safe_execfile_ipy(self, fname):
2523 2523 """Like safe_execfile, but for .ipy files with IPython syntax.
2524 2524
2525 2525 Parameters
2526 2526 ----------
2527 2527 fname : str
2528 2528 The name of the file to execute. The filename must have a
2529 2529 .ipy extension.
2530 2530 """
2531 2531 fname = os.path.abspath(os.path.expanduser(fname))
2532 2532
2533 2533 # Make sure we can open the file
2534 2534 try:
2535 2535 with open(fname) as thefile:
2536 2536 pass
2537 2537 except:
2538 2538 warn('Could not open file <%s> for safe execution.' % fname)
2539 2539 return
2540 2540
2541 2541 # Find things also in current directory. This is needed to mimic the
2542 2542 # behavior of running a script from the system command line, where
2543 2543 # Python inserts the script's directory into sys.path
2544 2544 dname = os.path.dirname(fname)
2545 2545
2546 2546 with prepended_to_syspath(dname):
2547 2547 try:
2548 2548 with open(fname) as thefile:
2549 2549 # self.run_cell currently captures all exceptions
2550 2550 # raised in user code. It would be nice if there were
2551 2551 # versions of runlines, execfile that did raise, so
2552 2552 # we could catch the errors.
2553 2553 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2554 2554 except:
2555 2555 self.showtraceback()
2556 2556 warn('Unknown failure executing file: <%s>' % fname)
2557 2557
2558 2558 def safe_run_module(self, mod_name, where):
2559 2559 """A safe version of runpy.run_module().
2560 2560
2561 2561 This version will never throw an exception, but instead print
2562 2562 helpful error messages to the screen.
2563 2563
2564 2564 `SystemExit` exceptions with status code 0 or None are ignored.
2565 2565
2566 2566 Parameters
2567 2567 ----------
2568 2568 mod_name : string
2569 2569 The name of the module to be executed.
2570 2570 where : dict
2571 2571 The globals namespace.
2572 2572 """
2573 2573 try:
2574 2574 try:
2575 2575 where.update(
2576 2576 runpy.run_module(str(mod_name), run_name="__main__",
2577 2577 alter_sys=True)
2578 2578 )
2579 2579 except SystemExit as status:
2580 2580 if status.code:
2581 2581 raise
2582 2582 except:
2583 2583 self.showtraceback()
2584 2584 warn('Unknown failure executing module: <%s>' % mod_name)
2585 2585
2586 2586 def _run_cached_cell_magic(self, magic_name, line):
2587 2587 """Special method to call a cell magic with the data stored in self.
2588 2588 """
2589 2589 cell = self._current_cell_magic_body
2590 2590 self._current_cell_magic_body = None
2591 2591 return self.run_cell_magic(magic_name, line, cell)
2592 2592
2593 2593 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2594 2594 """Run a complete IPython cell.
2595 2595
2596 2596 Parameters
2597 2597 ----------
2598 2598 raw_cell : str
2599 2599 The code (including IPython code such as %magic functions) to run.
2600 2600 store_history : bool
2601 2601 If True, the raw and translated cell will be stored in IPython's
2602 2602 history. For user code calling back into IPython's machinery, this
2603 2603 should be set to False.
2604 2604 silent : bool
2605 2605 If True, avoid side-effects, such as implicit displayhooks and
2606 2606 and logging. silent=True forces store_history=False.
2607 2607 shell_futures : bool
2608 2608 If True, the code will share future statements with the interactive
2609 2609 shell. It will both be affected by previous __future__ imports, and
2610 2610 any __future__ imports in the code will affect the shell. If False,
2611 2611 __future__ imports are not shared in either direction.
2612 2612 """
2613 2613 if (not raw_cell) or raw_cell.isspace():
2614 2614 return
2615 2615
2616 2616 if silent:
2617 2617 store_history = False
2618 2618
2619 2619 self.input_transformer_manager.push(raw_cell)
2620 2620 cell = self.input_transformer_manager.source_reset()
2621 2621
2622 2622 # Our own compiler remembers the __future__ environment. If we want to
2623 2623 # run code with a separate __future__ environment, use the default
2624 2624 # compiler
2625 2625 compiler = self.compile if shell_futures else CachingCompiler()
2626 2626
2627 2627 with self.builtin_trap:
2628 2628 prefilter_failed = False
2629 2629 if len(cell.splitlines()) == 1:
2630 2630 try:
2631 2631 # use prefilter_lines to handle trailing newlines
2632 2632 # restore trailing newline for ast.parse
2633 2633 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2634 2634 except AliasError as e:
2635 2635 error(e)
2636 2636 prefilter_failed = True
2637 2637 except Exception:
2638 2638 # don't allow prefilter errors to crash IPython
2639 2639 self.showtraceback()
2640 2640 prefilter_failed = True
2641 2641
2642 2642 # Store raw and processed history
2643 2643 if store_history:
2644 2644 self.history_manager.store_inputs(self.execution_count,
2645 2645 cell, raw_cell)
2646 2646 if not silent:
2647 2647 self.logger.log(cell, raw_cell)
2648 2648
2649 2649 if not prefilter_failed:
2650 2650 # don't run if prefilter failed
2651 2651 cell_name = self.compile.cache(cell, self.execution_count)
2652 2652
2653 2653 with self.display_trap:
2654 2654 try:
2655 2655 code_ast = compiler.ast_parse(cell, filename=cell_name)
2656 2656 except IndentationError:
2657 2657 self.showindentationerror()
2658 2658 if store_history:
2659 2659 self.execution_count += 1
2660 2660 return None
2661 2661 except (OverflowError, SyntaxError, ValueError, TypeError,
2662 2662 MemoryError):
2663 2663 self.showsyntaxerror()
2664 2664 if store_history:
2665 2665 self.execution_count += 1
2666 2666 return None
2667 2667
2668 2668 code_ast = self.transform_ast(code_ast)
2669 2669
2670 2670 interactivity = "none" if silent else self.ast_node_interactivity
2671 2671 self.run_ast_nodes(code_ast.body, cell_name,
2672 2672 interactivity=interactivity, compiler=compiler)
2673 2673
2674 2674 # Execute any registered post-execution functions.
2675 2675 # unless we are silent
2676 2676 post_exec = [] if silent else self._post_execute.iteritems()
2677 2677
2678 2678 for func, status in post_exec:
2679 2679 if self.disable_failing_post_execute and not status:
2680 2680 continue
2681 2681 try:
2682 2682 func()
2683 2683 except KeyboardInterrupt:
2684 2684 print("\nKeyboardInterrupt", file=io.stderr)
2685 2685 except Exception:
2686 2686 # register as failing:
2687 2687 self._post_execute[func] = False
2688 2688 self.showtraceback()
2689 2689 print('\n'.join([
2690 2690 "post-execution function %r produced an error." % func,
2691 2691 "If this problem persists, you can disable failing post-exec functions with:",
2692 2692 "",
2693 2693 " get_ipython().disable_failing_post_execute = True"
2694 2694 ]), file=io.stderr)
2695 2695
2696 2696 if store_history:
2697 2697 # Write output to the database. Does nothing unless
2698 2698 # history output logging is enabled.
2699 2699 self.history_manager.store_output(self.execution_count)
2700 2700 # Each cell is a *single* input, regardless of how many lines it has
2701 2701 self.execution_count += 1
2702 2702
2703 2703 def transform_ast(self, node):
2704 2704 """Apply the AST transformations from self.ast_transformers
2705 2705
2706 2706 Parameters
2707 2707 ----------
2708 2708 node : ast.Node
2709 2709 The root node to be transformed. Typically called with the ast.Module
2710 2710 produced by parsing user input.
2711 2711
2712 2712 Returns
2713 2713 -------
2714 2714 An ast.Node corresponding to the node it was called with. Note that it
2715 2715 may also modify the passed object, so don't rely on references to the
2716 2716 original AST.
2717 2717 """
2718 2718 for transformer in self.ast_transformers:
2719 2719 try:
2720 2720 node = transformer.visit(node)
2721 2721 except Exception:
2722 2722 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2723 2723 self.ast_transformers.remove(transformer)
2724 2724
2725 2725 if self.ast_transformers:
2726 2726 ast.fix_missing_locations(node)
2727 2727 return node
2728 2728
2729 2729
2730 2730 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2731 2731 compiler=compile):
2732 2732 """Run a sequence of AST nodes. The execution mode depends on the
2733 2733 interactivity parameter.
2734 2734
2735 2735 Parameters
2736 2736 ----------
2737 2737 nodelist : list
2738 2738 A sequence of AST nodes to run.
2739 2739 cell_name : str
2740 2740 Will be passed to the compiler as the filename of the cell. Typically
2741 2741 the value returned by ip.compile.cache(cell).
2742 2742 interactivity : str
2743 2743 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2744 2744 run interactively (displaying output from expressions). 'last_expr'
2745 2745 will run the last node interactively only if it is an expression (i.e.
2746 2746 expressions in loops or other blocks are not displayed. Other values
2747 2747 for this parameter will raise a ValueError.
2748 2748 compiler : callable
2749 2749 A function with the same interface as the built-in compile(), to turn
2750 2750 the AST nodes into code objects. Default is the built-in compile().
2751 2751 """
2752 2752 if not nodelist:
2753 2753 return
2754 2754
2755 2755 if interactivity == 'last_expr':
2756 2756 if isinstance(nodelist[-1], ast.Expr):
2757 2757 interactivity = "last"
2758 2758 else:
2759 2759 interactivity = "none"
2760 2760
2761 2761 if interactivity == 'none':
2762 2762 to_run_exec, to_run_interactive = nodelist, []
2763 2763 elif interactivity == 'last':
2764 2764 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2765 2765 elif interactivity == 'all':
2766 2766 to_run_exec, to_run_interactive = [], nodelist
2767 2767 else:
2768 2768 raise ValueError("Interactivity was %r" % interactivity)
2769 2769
2770 2770 exec_count = self.execution_count
2771 2771
2772 2772 try:
2773 2773 for i, node in enumerate(to_run_exec):
2774 2774 mod = ast.Module([node])
2775 2775 code = compiler(mod, cell_name, "exec")
2776 2776 if self.run_code(code):
2777 2777 return True
2778 2778
2779 2779 for i, node in enumerate(to_run_interactive):
2780 2780 mod = ast.Interactive([node])
2781 2781 code = compiler(mod, cell_name, "single")
2782 2782 if self.run_code(code):
2783 2783 return True
2784 2784
2785 2785 # Flush softspace
2786 2786 if softspace(sys.stdout, 0):
2787 2787 print()
2788 2788
2789 2789 except:
2790 2790 # It's possible to have exceptions raised here, typically by
2791 2791 # compilation of odd code (such as a naked 'return' outside a
2792 2792 # function) that did parse but isn't valid. Typically the exception
2793 2793 # is a SyntaxError, but it's safest just to catch anything and show
2794 2794 # the user a traceback.
2795 2795
2796 2796 # We do only one try/except outside the loop to minimize the impact
2797 2797 # on runtime, and also because if any node in the node list is
2798 2798 # broken, we should stop execution completely.
2799 2799 self.showtraceback()
2800 2800
2801 2801 return False
2802 2802
2803 2803 def run_code(self, code_obj):
2804 2804 """Execute a code object.
2805 2805
2806 2806 When an exception occurs, self.showtraceback() is called to display a
2807 2807 traceback.
2808 2808
2809 2809 Parameters
2810 2810 ----------
2811 2811 code_obj : code object
2812 2812 A compiled code object, to be executed
2813 2813
2814 2814 Returns
2815 2815 -------
2816 2816 False : successful execution.
2817 2817 True : an error occurred.
2818 2818 """
2819 2819
2820 2820 # Set our own excepthook in case the user code tries to call it
2821 2821 # directly, so that the IPython crash handler doesn't get triggered
2822 2822 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2823 2823
2824 2824 # we save the original sys.excepthook in the instance, in case config
2825 2825 # code (such as magics) needs access to it.
2826 2826 self.sys_excepthook = old_excepthook
2827 2827 outflag = 1 # happens in more places, so it's easier as default
2828 2828 try:
2829 2829 try:
2830 2830 self.hooks.pre_run_code_hook()
2831 2831 #rprint('Running code', repr(code_obj)) # dbg
2832 2832 exec code_obj in self.user_global_ns, self.user_ns
2833 2833 finally:
2834 2834 # Reset our crash handler in place
2835 2835 sys.excepthook = old_excepthook
2836 2836 except SystemExit:
2837 2837 self.showtraceback(exception_only=True)
2838 2838 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2839 2839 except self.custom_exceptions:
2840 2840 etype,value,tb = sys.exc_info()
2841 2841 self.CustomTB(etype,value,tb)
2842 2842 except:
2843 2843 self.showtraceback()
2844 2844 else:
2845 2845 outflag = 0
2846 2846 return outflag
2847 2847
2848 2848 # For backwards compatibility
2849 2849 runcode = run_code
2850 2850
2851 2851 #-------------------------------------------------------------------------
2852 2852 # Things related to GUI support and pylab
2853 2853 #-------------------------------------------------------------------------
2854 2854
2855 2855 def enable_gui(self, gui=None):
2856 2856 raise NotImplementedError('Implement enable_gui in a subclass')
2857 2857
2858 2858 def enable_matplotlib(self, gui=None):
2859 2859 """Enable interactive matplotlib and inline figure support.
2860 2860
2861 2861 This takes the following steps:
2862 2862
2863 2863 1. select the appropriate eventloop and matplotlib backend
2864 2864 2. set up matplotlib for interactive use with that backend
2865 2865 3. configure formatters for inline figure display
2866 2866 4. enable the selected gui eventloop
2867 2867
2868 2868 Parameters
2869 2869 ----------
2870 2870 gui : optional, string
2871 2871 If given, dictates the choice of matplotlib GUI backend to use
2872 2872 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2873 2873 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2874 2874 matplotlib (as dictated by the matplotlib build-time options plus the
2875 2875 user's matplotlibrc configuration file). Note that not all backends
2876 2876 make sense in all contexts, for example a terminal ipython can't
2877 2877 display figures inline.
2878 2878 """
2879 2879 from IPython.core import pylabtools as pt
2880 2880 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2881 2881
2882 2882 if gui != 'inline':
2883 2883 # If we have our first gui selection, store it
2884 2884 if self.pylab_gui_select is None:
2885 2885 self.pylab_gui_select = gui
2886 2886 # Otherwise if they are different
2887 2887 elif gui != self.pylab_gui_select:
2888 2888 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2889 2889 ' Using %s instead.' % (gui, self.pylab_gui_select))
2890 2890 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2891 2891
2892 2892 pt.activate_matplotlib(backend)
2893 2893 pt.configure_inline_support(self, backend)
2894 2894
2895 2895 # Now we must activate the gui pylab wants to use, and fix %run to take
2896 2896 # plot updates into account
2897 2897 self.enable_gui(gui)
2898 2898 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2899 2899 pt.mpl_runner(self.safe_execfile)
2900 2900
2901 2901 return gui, backend
2902 2902
2903 2903 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2904 2904 """Activate pylab support at runtime.
2905 2905
2906 2906 This turns on support for matplotlib, preloads into the interactive
2907 2907 namespace all of numpy and pylab, and configures IPython to correctly
2908 2908 interact with the GUI event loop. The GUI backend to be used can be
2909 2909 optionally selected with the optional ``gui`` argument.
2910 2910
2911 2911 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2912 2912
2913 2913 Parameters
2914 2914 ----------
2915 2915 gui : optional, string
2916 2916 If given, dictates the choice of matplotlib GUI backend to use
2917 2917 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2918 2918 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2919 2919 matplotlib (as dictated by the matplotlib build-time options plus the
2920 2920 user's matplotlibrc configuration file). Note that not all backends
2921 2921 make sense in all contexts, for example a terminal ipython can't
2922 2922 display figures inline.
2923 2923 import_all : optional, bool, default: True
2924 2924 Whether to do `from numpy import *` and `from pylab import *`
2925 2925 in addition to module imports.
2926 2926 welcome_message : deprecated
2927 2927 This argument is ignored, no welcome message will be displayed.
2928 2928 """
2929 2929 from IPython.core.pylabtools import import_pylab
2930 2930
2931 2931 gui, backend = self.enable_matplotlib(gui)
2932 2932
2933 2933 # We want to prevent the loading of pylab to pollute the user's
2934 2934 # namespace as shown by the %who* magics, so we execute the activation
2935 2935 # code in an empty namespace, and we update *both* user_ns and
2936 2936 # user_ns_hidden with this information.
2937 2937 ns = {}
2938 2938 import_pylab(ns, import_all)
2939 2939 # warn about clobbered names
2940 2940 ignored = set(["__builtins__"])
2941 2941 both = set(ns).intersection(self.user_ns).difference(ignored)
2942 2942 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2943 2943 self.user_ns.update(ns)
2944 2944 self.user_ns_hidden.update(ns)
2945 2945 return gui, backend, clobbered
2946 2946
2947 2947 #-------------------------------------------------------------------------
2948 2948 # Utilities
2949 2949 #-------------------------------------------------------------------------
2950 2950
2951 2951 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2952 2952 """Expand python variables in a string.
2953 2953
2954 2954 The depth argument indicates how many frames above the caller should
2955 2955 be walked to look for the local namespace where to expand variables.
2956 2956
2957 2957 The global namespace for expansion is always the user's interactive
2958 2958 namespace.
2959 2959 """
2960 2960 ns = self.user_ns.copy()
2961 2961 ns.update(sys._getframe(depth+1).f_locals)
2962 2962 try:
2963 2963 # We have to use .vformat() here, because 'self' is a valid and common
2964 2964 # name, and expanding **ns for .format() would make it collide with
2965 2965 # the 'self' argument of the method.
2966 2966 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2967 2967 except Exception:
2968 2968 # if formatter couldn't format, just let it go untransformed
2969 2969 pass
2970 2970 return cmd
2971 2971
2972 2972 def mktempfile(self, data=None, prefix='ipython_edit_'):
2973 2973 """Make a new tempfile and return its filename.
2974 2974
2975 2975 This makes a call to tempfile.mktemp, but it registers the created
2976 2976 filename internally so ipython cleans it up at exit time.
2977 2977
2978 2978 Optional inputs:
2979 2979
2980 2980 - data(None): if data is given, it gets written out to the temp file
2981 immediately, and the file is closed again."""
2981 immediately, and the file is closed again."""
2982 2982
2983 2983 filename = tempfile.mktemp('.py', prefix)
2984 2984 self.tempfiles.append(filename)
2985 2985
2986 2986 if data:
2987 2987 tmp_file = open(filename,'w')
2988 2988 tmp_file.write(data)
2989 2989 tmp_file.close()
2990 2990 return filename
2991 2991
2992 2992 # TODO: This should be removed when Term is refactored.
2993 2993 def write(self,data):
2994 2994 """Write a string to the default output"""
2995 2995 io.stdout.write(data)
2996 2996
2997 2997 # TODO: This should be removed when Term is refactored.
2998 2998 def write_err(self,data):
2999 2999 """Write a string to the default error output"""
3000 3000 io.stderr.write(data)
3001 3001
3002 3002 def ask_yes_no(self, prompt, default=None):
3003 3003 if self.quiet:
3004 3004 return True
3005 3005 return ask_yes_no(prompt,default)
3006 3006
3007 3007 def show_usage(self):
3008 3008 """Show a usage message"""
3009 3009 page.page(IPython.core.usage.interactive_usage)
3010 3010
3011 3011 def extract_input_lines(self, range_str, raw=False):
3012 3012 """Return as a string a set of input history slices.
3013 3013
3014 3014 Parameters
3015 3015 ----------
3016 3016 range_str : string
3017 3017 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3018 3018 since this function is for use by magic functions which get their
3019 3019 arguments as strings. The number before the / is the session
3020 3020 number: ~n goes n back from the current session.
3021 3021
3022 3022 Optional Parameters:
3023 3023 - raw(False): by default, the processed input is used. If this is
3024 true, the raw input history is used instead.
3024 true, the raw input history is used instead.
3025 3025
3026 3026 Note that slices can be called with two notations:
3027 3027
3028 3028 N:M -> standard python form, means including items N...(M-1).
3029 3029
3030 N-M -> include items N..M (closed endpoint)."""
3030 N-M -> include items N..M (closed endpoint).
3031 """
3031 3032 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3032 3033 return "\n".join(x for _, _, x in lines)
3033 3034
3034 3035 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
3035 3036 """Get a code string from history, file, url, or a string or macro.
3036 3037
3037 3038 This is mainly used by magic functions.
3038 3039
3039 3040 Parameters
3040 3041 ----------
3041 3042
3042 3043 target : str
3043 3044
3044 3045 A string specifying code to retrieve. This will be tried respectively
3045 3046 as: ranges of input history (see %history for syntax), url,
3046 3047 correspnding .py file, filename, or an expression evaluating to a
3047 3048 string or Macro in the user namespace.
3048 3049
3049 3050 raw : bool
3050 3051 If true (default), retrieve raw history. Has no effect on the other
3051 3052 retrieval mechanisms.
3052 3053
3053 3054 py_only : bool (default False)
3054 3055 Only try to fetch python code, do not try alternative methods to decode file
3055 3056 if unicode fails.
3056 3057
3057 3058 Returns
3058 3059 -------
3059 3060 A string of code.
3060 3061
3061 3062 ValueError is raised if nothing is found, and TypeError if it evaluates
3062 3063 to an object of another type. In each case, .args[0] is a printable
3063 3064 message.
3064 3065 """
3065 3066 code = self.extract_input_lines(target, raw=raw) # Grab history
3066 3067 if code:
3067 3068 return code
3068 3069 utarget = unquote_filename(target)
3069 3070 try:
3070 3071 if utarget.startswith(('http://', 'https://')):
3071 3072 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3072 3073 except UnicodeDecodeError:
3073 3074 if not py_only :
3074 3075 from urllib import urlopen # Deferred import
3075 3076 response = urlopen(target)
3076 3077 return response.read().decode('latin1')
3077 3078 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3078 3079
3079 3080 potential_target = [target]
3080 3081 try :
3081 3082 potential_target.insert(0,get_py_filename(target))
3082 3083 except IOError:
3083 3084 pass
3084 3085
3085 3086 for tgt in potential_target :
3086 3087 if os.path.isfile(tgt): # Read file
3087 3088 try :
3088 3089 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3089 3090 except UnicodeDecodeError :
3090 3091 if not py_only :
3091 3092 with io_open(tgt,'r', encoding='latin1') as f :
3092 3093 return f.read()
3093 3094 raise ValueError(("'%s' seem to be unreadable.") % target)
3094 3095 elif os.path.isdir(os.path.expanduser(tgt)):
3095 3096 raise ValueError("'%s' is a directory, not a regular file." % target)
3096 3097
3097 3098 try: # User namespace
3098 3099 codeobj = eval(target, self.user_ns)
3099 3100 except Exception:
3100 3101 raise ValueError(("'%s' was not found in history, as a file, url, "
3101 3102 "nor in the user namespace.") % target)
3102 3103 if isinstance(codeobj, basestring):
3103 3104 return codeobj
3104 3105 elif isinstance(codeobj, Macro):
3105 3106 return codeobj.value
3106 3107
3107 3108 raise TypeError("%s is neither a string nor a macro." % target,
3108 3109 codeobj)
3109 3110
3110 3111 #-------------------------------------------------------------------------
3111 3112 # Things related to IPython exiting
3112 3113 #-------------------------------------------------------------------------
3113 3114 def atexit_operations(self):
3114 3115 """This will be executed at the time of exit.
3115 3116
3116 3117 Cleanup operations and saving of persistent data that is done
3117 3118 unconditionally by IPython should be performed here.
3118 3119
3119 3120 For things that may depend on startup flags or platform specifics (such
3120 3121 as having readline or not), register a separate atexit function in the
3121 3122 code that has the appropriate information, rather than trying to
3122 3123 clutter
3123 3124 """
3124 3125 # Close the history session (this stores the end time and line count)
3125 3126 # this must be *before* the tempfile cleanup, in case of temporary
3126 3127 # history db
3127 3128 self.history_manager.end_session()
3128 3129
3129 3130 # Cleanup all tempfiles left around
3130 3131 for tfile in self.tempfiles:
3131 3132 try:
3132 3133 os.unlink(tfile)
3133 3134 except OSError:
3134 3135 pass
3135 3136
3136 3137 # Clear all user namespaces to release all references cleanly.
3137 3138 self.reset(new_session=False)
3138 3139
3139 3140 # Run user hooks
3140 3141 self.hooks.shutdown_hook()
3141 3142
3142 3143 def cleanup(self):
3143 3144 self.restore_sys_module_state()
3144 3145
3145 3146
3146 3147 class InteractiveShellABC(object):
3147 3148 """An abstract base class for InteractiveShell."""
3148 3149 __metaclass__ = abc.ABCMeta
3149 3150
3150 3151 InteractiveShellABC.register(InteractiveShell)
@@ -1,220 +1,220 b''
1 1 """Logger class for IPython's logging facilities.
2 2 """
3 3
4 4 #*****************************************************************************
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 6 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 7 #
8 8 # Distributed under the terms of the BSD License. The full license is in
9 9 # the file COPYING, distributed as part of this software.
10 10 #*****************************************************************************
11 11
12 12 #****************************************************************************
13 13 # Modules and globals
14 14
15 15 # Python standard modules
16 16 import glob
17 17 import io
18 18 import os
19 19 import time
20 20
21 21 from IPython.utils.py3compat import str_to_unicode
22 22
23 23 #****************************************************************************
24 24 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
25 25 # ipython and does input cache management. Finish cleanup later...
26 26
27 27 class Logger(object):
28 28 """A Logfile class with different policies for file creation"""
29 29
30 30 def __init__(self, home_dir, logfname='Logger.log', loghead=u'',
31 31 logmode='over'):
32 32
33 33 # this is the full ipython instance, we need some attributes from it
34 34 # which won't exist until later. What a mess, clean up later...
35 35 self.home_dir = home_dir
36 36
37 37 self.logfname = logfname
38 38 self.loghead = loghead
39 39 self.logmode = logmode
40 40 self.logfile = None
41 41
42 42 # Whether to log raw or processed input
43 43 self.log_raw_input = False
44 44
45 45 # whether to also log output
46 46 self.log_output = False
47 47
48 48 # whether to put timestamps before each log entry
49 49 self.timestamp = False
50 50
51 51 # activity control flags
52 52 self.log_active = False
53 53
54 54 # logmode is a validated property
55 55 def _set_mode(self,mode):
56 56 if mode not in ['append','backup','global','over','rotate']:
57 57 raise ValueError('invalid log mode %s given' % mode)
58 58 self._logmode = mode
59 59
60 60 def _get_mode(self):
61 61 return self._logmode
62 62
63 63 logmode = property(_get_mode,_set_mode)
64 64
65 65 def logstart(self, logfname=None, loghead=None, logmode=None,
66 66 log_output=False, timestamp=False, log_raw_input=False):
67 67 """Generate a new log-file with a default header.
68 68
69 69 Raises RuntimeError if the log has already been started"""
70 70
71 71 if self.logfile is not None:
72 72 raise RuntimeError('Log file is already active: %s' %
73 73 self.logfname)
74 74
75 75 # The parameters can override constructor defaults
76 76 if logfname is not None: self.logfname = logfname
77 77 if loghead is not None: self.loghead = loghead
78 78 if logmode is not None: self.logmode = logmode
79 79
80 80 # Parameters not part of the constructor
81 81 self.timestamp = timestamp
82 82 self.log_output = log_output
83 83 self.log_raw_input = log_raw_input
84 84
85 85 # init depending on the log mode requested
86 86 isfile = os.path.isfile
87 87 logmode = self.logmode
88 88
89 89 if logmode == 'append':
90 90 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
91 91
92 92 elif logmode == 'backup':
93 93 if isfile(self.logfname):
94 94 backup_logname = self.logfname+'~'
95 95 # Manually remove any old backup, since os.rename may fail
96 96 # under Windows.
97 97 if isfile(backup_logname):
98 98 os.remove(backup_logname)
99 99 os.rename(self.logfname,backup_logname)
100 100 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
101 101
102 102 elif logmode == 'global':
103 103 self.logfname = os.path.join(self.home_dir,self.logfname)
104 104 self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
105 105
106 106 elif logmode == 'over':
107 107 if isfile(self.logfname):
108 108 os.remove(self.logfname)
109 109 self.logfile = io.open(self.logfname,'w', encoding='utf-8')
110 110
111 111 elif logmode == 'rotate':
112 112 if isfile(self.logfname):
113 113 if isfile(self.logfname+'.001~'):
114 114 old = glob.glob(self.logfname+'.*~')
115 115 old.sort()
116 116 old.reverse()
117 117 for f in old:
118 118 root, ext = os.path.splitext(f)
119 119 num = int(ext[1:-1])+1
120 120 os.rename(f, root+'.'+repr(num).zfill(3)+'~')
121 121 os.rename(self.logfname, self.logfname+'.001~')
122 122 self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
123 123
124 124 if logmode != 'append':
125 125 self.logfile.write(self.loghead)
126 126
127 127 self.logfile.flush()
128 128 self.log_active = True
129 129
130 130 def switch_log(self,val):
131 131 """Switch logging on/off. val should be ONLY a boolean."""
132 132
133 133 if val not in [False,True,0,1]:
134 134 raise ValueError('Call switch_log ONLY with a boolean argument, '
135 135 'not with: %s' % val)
136 136
137 137 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 138
139 139 if self.logfile is None:
140 140 print """
141 141 Logging hasn't been started yet (use logstart for that).
142 142
143 143 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 144 which already exists. But you must first start the logging process with
145 145 %logstart (optionally giving a logfile name)."""
146 146
147 147 else:
148 148 if self.log_active == val:
149 149 print 'Logging is already',label[val]
150 150 else:
151 151 print 'Switching logging',label[val]
152 152 self.log_active = not self.log_active
153 153 self.log_active_out = self.log_active
154 154
155 155 def logstate(self):
156 156 """Print a status message about the logger."""
157 157 if self.logfile is None:
158 158 print 'Logging has not been activated.'
159 159 else:
160 160 state = self.log_active and 'active' or 'temporarily suspended'
161 161 print 'Filename :',self.logfname
162 162 print 'Mode :',self.logmode
163 163 print 'Output logging :',self.log_output
164 164 print 'Raw input log :',self.log_raw_input
165 165 print 'Timestamping :',self.timestamp
166 166 print 'State :',state
167 167
168 168 def log(self, line_mod, line_ori):
169 169 """Write the sources to a log.
170 170
171 171 Inputs:
172 172
173 173 - line_mod: possibly modified input, such as the transformations made
174 by input prefilters or input handlers of various kinds. This should
175 always be valid Python.
174 by input prefilters or input handlers of various kinds. This should
175 always be valid Python.
176 176
177 - line_ori: unmodified input line from the user. This is not
178 necessarily valid Python.
177 - line_ori: unmodified input line from the user. This is not
178 necessarily valid Python.
179 179 """
180 180
181 181 # Write the log line, but decide which one according to the
182 182 # log_raw_input flag, set when the log is started.
183 183 if self.log_raw_input:
184 184 self.log_write(line_ori)
185 185 else:
186 186 self.log_write(line_mod)
187 187
188 188 def log_write(self, data, kind='input'):
189 189 """Write data to the log file, if active"""
190 190
191 191 #print 'data: %r' % data # dbg
192 192 if self.log_active and data:
193 193 write = self.logfile.write
194 194 if kind=='input':
195 195 if self.timestamp:
196 196 write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
197 197 time.localtime())))
198 198 write(data)
199 199 elif kind=='output' and self.log_output:
200 200 odata = u'\n'.join([u'#[Out]# %s' % s
201 201 for s in data.splitlines()])
202 202 write(u'%s\n' % odata)
203 203 self.logfile.flush()
204 204
205 205 def logstop(self):
206 206 """Fully stop logging and close log file.
207 207
208 208 In order to start logging again, a new logstart() call needs to be
209 209 made, possibly (though not necessarily) with a new filename, mode and
210 210 other options."""
211 211
212 212 if self.logfile is not None:
213 213 self.logfile.close()
214 214 self.logfile = None
215 215 else:
216 216 print "Logging hadn't been started."
217 217 self.log_active = False
218 218
219 219 # For backwards compatibility, in case anyone was using this.
220 220 close_log = logstop
@@ -1,676 +1,676 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 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008 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 # Stdlib
18 18 import os
19 19 import re
20 20 import sys
21 21 import types
22 22 from getopt import getopt, GetoptError
23 23
24 24 # Our own
25 25 from IPython.config.configurable import Configurable
26 26 from IPython.core import oinspect
27 27 from IPython.core.error import UsageError
28 28 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
29 29 from IPython.external.decorator import decorator
30 30 from IPython.utils.ipstruct import Struct
31 31 from IPython.utils.process import arg_split
32 32 from IPython.utils.text import dedent
33 33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
34 34 from IPython.utils.warn import error
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Globals
38 38 #-----------------------------------------------------------------------------
39 39
40 40 # A dict we'll use for each class that has magics, used as temporary storage to
41 41 # pass information between the @line/cell_magic method decorators and the
42 42 # @magics_class class decorator, because the method decorators have no
43 43 # access to the class when they run. See for more details:
44 44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
45 45
46 46 magics = dict(line={}, cell={})
47 47
48 48 magic_kinds = ('line', 'cell')
49 49 magic_spec = ('line', 'cell', 'line_cell')
50 50 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
51 51
52 52 #-----------------------------------------------------------------------------
53 53 # Utility classes and functions
54 54 #-----------------------------------------------------------------------------
55 55
56 56 class Bunch: pass
57 57
58 58
59 59 def on_off(tag):
60 60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 61 return ['OFF','ON'][tag]
62 62
63 63
64 64 def compress_dhist(dh):
65 65 """Compress a directory history into a new one with at most 20 entries.
66 66
67 67 Return a new list made from the first and last 10 elements of dhist after
68 68 removal of duplicates.
69 69 """
70 70 head, tail = dh[:-10], dh[-10:]
71 71
72 72 newhead = []
73 73 done = set()
74 74 for h in head:
75 75 if h in done:
76 76 continue
77 77 newhead.append(h)
78 78 done.add(h)
79 79
80 80 return newhead + tail
81 81
82 82
83 83 def needs_local_scope(func):
84 84 """Decorator to mark magic functions which need to local scope to run."""
85 85 func.needs_local_scope = True
86 86 return func
87 87
88 88 #-----------------------------------------------------------------------------
89 89 # Class and method decorators for registering magics
90 90 #-----------------------------------------------------------------------------
91 91
92 92 def magics_class(cls):
93 93 """Class decorator for all subclasses of the main Magics class.
94 94
95 95 Any class that subclasses Magics *must* also apply this decorator, to
96 96 ensure that all the methods that have been decorated as line/cell magics
97 97 get correctly registered in the class instance. This is necessary because
98 98 when method decorators run, the class does not exist yet, so they
99 99 temporarily store their information into a module global. Application of
100 100 this class decorator copies that global data to the class instance and
101 101 clears the global.
102 102
103 103 Obviously, this mechanism is not thread-safe, which means that the
104 104 *creation* of subclasses of Magic should only be done in a single-thread
105 105 context. Instantiation of the classes has no restrictions. Given that
106 106 these classes are typically created at IPython startup time and before user
107 107 application code becomes active, in practice this should not pose any
108 108 problems.
109 109 """
110 110 cls.registered = True
111 111 cls.magics = dict(line = magics['line'],
112 112 cell = magics['cell'])
113 113 magics['line'] = {}
114 114 magics['cell'] = {}
115 115 return cls
116 116
117 117
118 118 def record_magic(dct, magic_kind, magic_name, func):
119 119 """Utility function to store a function as a magic of a specific kind.
120 120
121 121 Parameters
122 122 ----------
123 123 dct : dict
124 124 A dictionary with 'line' and 'cell' subdicts.
125 125
126 126 magic_kind : str
127 127 Kind of magic to be stored.
128 128
129 129 magic_name : str
130 130 Key to store the magic as.
131 131
132 132 func : function
133 133 Callable object to store.
134 134 """
135 135 if magic_kind == 'line_cell':
136 136 dct['line'][magic_name] = dct['cell'][magic_name] = func
137 137 else:
138 138 dct[magic_kind][magic_name] = func
139 139
140 140
141 141 def validate_type(magic_kind):
142 142 """Ensure that the given magic_kind is valid.
143 143
144 144 Check that the given magic_kind is one of the accepted spec types (stored
145 145 in the global `magic_spec`), raise ValueError otherwise.
146 146 """
147 147 if magic_kind not in magic_spec:
148 148 raise ValueError('magic_kind must be one of %s, %s given' %
149 149 magic_kinds, magic_kind)
150 150
151 151
152 152 # The docstrings for the decorator below will be fairly similar for the two
153 153 # types (method and function), so we generate them here once and reuse the
154 154 # templates below.
155 155 _docstring_template = \
156 156 """Decorate the given {0} as {1} magic.
157 157
158 158 The decorator can be used with or without arguments, as follows.
159 159
160 160 i) without arguments: it will create a {1} magic named as the {0} being
161 161 decorated::
162 162
163 163 @deco
164 164 def foo(...)
165 165
166 166 will create a {1} magic named `foo`.
167 167
168 168 ii) with one string argument: which will be used as the actual name of the
169 169 resulting magic::
170 170
171 171 @deco('bar')
172 172 def foo(...)
173 173
174 174 will create a {1} magic named `bar`.
175 175 """
176 176
177 177 # These two are decorator factories. While they are conceptually very similar,
178 178 # there are enough differences in the details that it's simpler to have them
179 179 # written as completely standalone functions rather than trying to share code
180 180 # and make a single one with convoluted logic.
181 181
182 182 def _method_magic_marker(magic_kind):
183 183 """Decorator factory for methods in Magics subclasses.
184 184 """
185 185
186 186 validate_type(magic_kind)
187 187
188 188 # This is a closure to capture the magic_kind. We could also use a class,
189 189 # but it's overkill for just that one bit of state.
190 190 def magic_deco(arg):
191 191 call = lambda f, *a, **k: f(*a, **k)
192 192
193 193 if callable(arg):
194 194 # "Naked" decorator call (just @foo, no args)
195 195 func = arg
196 196 name = func.func_name
197 197 retval = decorator(call, func)
198 198 record_magic(magics, magic_kind, name, name)
199 199 elif isinstance(arg, basestring):
200 200 # Decorator called with arguments (@foo('bar'))
201 201 name = arg
202 202 def mark(func, *a, **kw):
203 203 record_magic(magics, magic_kind, name, func.func_name)
204 204 return decorator(call, func)
205 205 retval = mark
206 206 else:
207 207 raise TypeError("Decorator can only be called with "
208 208 "string or function")
209 209 return retval
210 210
211 211 # Ensure the resulting decorator has a usable docstring
212 212 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
213 213 return magic_deco
214 214
215 215
216 216 def _function_magic_marker(magic_kind):
217 217 """Decorator factory for standalone functions.
218 218 """
219 219 validate_type(magic_kind)
220 220
221 221 # This is a closure to capture the magic_kind. We could also use a class,
222 222 # but it's overkill for just that one bit of state.
223 223 def magic_deco(arg):
224 224 call = lambda f, *a, **k: f(*a, **k)
225 225
226 226 # Find get_ipython() in the caller's namespace
227 227 caller = sys._getframe(1)
228 228 for ns in ['f_locals', 'f_globals', 'f_builtins']:
229 229 get_ipython = getattr(caller, ns).get('get_ipython')
230 230 if get_ipython is not None:
231 231 break
232 232 else:
233 233 raise NameError('Decorator can only run in context where '
234 234 '`get_ipython` exists')
235 235
236 236 ip = get_ipython()
237 237
238 238 if callable(arg):
239 239 # "Naked" decorator call (just @foo, no args)
240 240 func = arg
241 241 name = func.func_name
242 242 ip.register_magic_function(func, magic_kind, name)
243 243 retval = decorator(call, func)
244 244 elif isinstance(arg, basestring):
245 245 # Decorator called with arguments (@foo('bar'))
246 246 name = arg
247 247 def mark(func, *a, **kw):
248 248 ip.register_magic_function(func, magic_kind, name)
249 249 return decorator(call, func)
250 250 retval = mark
251 251 else:
252 252 raise TypeError("Decorator can only be called with "
253 253 "string or function")
254 254 return retval
255 255
256 256 # Ensure the resulting decorator has a usable docstring
257 257 ds = _docstring_template.format('function', magic_kind)
258 258
259 259 ds += dedent("""
260 260 Note: this decorator can only be used in a context where IPython is already
261 261 active, so that the `get_ipython()` call succeeds. You can therefore use
262 262 it in your startup files loaded after IPython initializes, but *not* in the
263 263 IPython configuration file itself, which is executed before IPython is
264 264 fully up and running. Any file located in the `startup` subdirectory of
265 265 your configuration profile will be OK in this sense.
266 266 """)
267 267
268 268 magic_deco.__doc__ = ds
269 269 return magic_deco
270 270
271 271
272 272 # Create the actual decorators for public use
273 273
274 274 # These three are used to decorate methods in class definitions
275 275 line_magic = _method_magic_marker('line')
276 276 cell_magic = _method_magic_marker('cell')
277 277 line_cell_magic = _method_magic_marker('line_cell')
278 278
279 279 # These three decorate standalone functions and perform the decoration
280 280 # immediately. They can only run where get_ipython() works
281 281 register_line_magic = _function_magic_marker('line')
282 282 register_cell_magic = _function_magic_marker('cell')
283 283 register_line_cell_magic = _function_magic_marker('line_cell')
284 284
285 285 #-----------------------------------------------------------------------------
286 286 # Core Magic classes
287 287 #-----------------------------------------------------------------------------
288 288
289 289 class MagicsManager(Configurable):
290 290 """Object that handles all magic-related functionality for IPython.
291 291 """
292 292 # Non-configurable class attributes
293 293
294 294 # A two-level dict, first keyed by magic type, then by magic function, and
295 295 # holding the actual callable object as value. This is the dict used for
296 296 # magic function dispatch
297 297 magics = Dict
298 298
299 299 # A registry of the original objects that we've been given holding magics.
300 300 registry = Dict
301 301
302 302 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
303 303
304 304 auto_magic = Bool(True, config=True, help=
305 305 "Automatically call line magics without requiring explicit % prefix")
306 306
307 307 def _auto_magic_changed(self, name, value):
308 308 self.shell.automagic = value
309 309
310 310 _auto_status = [
311 311 'Automagic is OFF, % prefix IS needed for line magics.',
312 312 'Automagic is ON, % prefix IS NOT needed for line magics.']
313 313
314 314 user_magics = Instance('IPython.core.magics.UserMagics')
315 315
316 316 def __init__(self, shell=None, config=None, user_magics=None, **traits):
317 317
318 318 super(MagicsManager, self).__init__(shell=shell, config=config,
319 319 user_magics=user_magics, **traits)
320 320 self.magics = dict(line={}, cell={})
321 321 # Let's add the user_magics to the registry for uniformity, so *all*
322 322 # registered magic containers can be found there.
323 323 self.registry[user_magics.__class__.__name__] = user_magics
324 324
325 325 def auto_status(self):
326 326 """Return descriptive string with automagic status."""
327 327 return self._auto_status[self.auto_magic]
328 328
329 329 def lsmagic(self):
330 330 """Return a dict of currently available magic functions.
331 331
332 332 The return dict has the keys 'line' and 'cell', corresponding to the
333 333 two types of magics we support. Each value is a list of names.
334 334 """
335 335 return self.magics
336 336
337 337 def lsmagic_docs(self, brief=False, missing=''):
338 338 """Return dict of documentation of magic functions.
339 339
340 340 The return dict has the keys 'line' and 'cell', corresponding to the
341 341 two types of magics we support. Each value is a dict keyed by magic
342 342 name whose value is the function docstring. If a docstring is
343 343 unavailable, the value of `missing` is used instead.
344 344
345 345 If brief is True, only the first line of each docstring will be returned.
346 346 """
347 347 docs = {}
348 348 for m_type in self.magics:
349 349 m_docs = {}
350 350 for m_name, m_func in self.magics[m_type].iteritems():
351 351 if m_func.__doc__:
352 352 if brief:
353 353 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
354 354 else:
355 355 m_docs[m_name] = m_func.__doc__.rstrip()
356 356 else:
357 357 m_docs[m_name] = missing
358 358 docs[m_type] = m_docs
359 359 return docs
360 360
361 361 def register(self, *magic_objects):
362 362 """Register one or more instances of Magics.
363 363
364 364 Take one or more classes or instances of classes that subclass the main
365 365 `core.Magic` class, and register them with IPython to use the magic
366 366 functions they provide. The registration process will then ensure that
367 367 any methods that have decorated to provide line and/or cell magics will
368 368 be recognized with the `%x`/`%%x` syntax as a line/cell magic
369 369 respectively.
370 370
371 371 If classes are given, they will be instantiated with the default
372 372 constructor. If your classes need a custom constructor, you should
373 373 instanitate them first and pass the instance.
374 374
375 375 The provided arguments can be an arbitrary mix of classes and instances.
376 376
377 377 Parameters
378 378 ----------
379 379 magic_objects : one or more classes or instances
380 380 """
381 381 # Start by validating them to ensure they have all had their magic
382 382 # methods registered at the instance level
383 383 for m in magic_objects:
384 384 if not m.registered:
385 385 raise ValueError("Class of magics %r was constructed without "
386 386 "the @register_magics class decorator")
387 387 if type(m) in (type, MetaHasTraits):
388 388 # If we're given an uninstantiated class
389 389 m = m(shell=self.shell)
390 390
391 391 # Now that we have an instance, we can register it and update the
392 392 # table of callables
393 393 self.registry[m.__class__.__name__] = m
394 394 for mtype in magic_kinds:
395 395 self.magics[mtype].update(m.magics[mtype])
396 396
397 397 def register_function(self, func, magic_kind='line', magic_name=None):
398 398 """Expose a standalone function as magic function for IPython.
399 399
400 400 This will create an IPython magic (line, cell or both) from a
401 401 standalone function. The functions should have the following
402 402 signatures:
403 403
404 404 * For line magics: `def f(line)`
405 405 * For cell magics: `def f(line, cell)`
406 406 * For a function that does both: `def f(line, cell=None)`
407 407
408 408 In the latter case, the function will be called with `cell==None` when
409 409 invoked as `%f`, and with cell as a string when invoked as `%%f`.
410 410
411 411 Parameters
412 412 ----------
413 413 func : callable
414 414 Function to be registered as a magic.
415 415
416 416 magic_kind : str
417 417 Kind of magic, one of 'line', 'cell' or 'line_cell'
418 418
419 419 magic_name : optional str
420 420 If given, the name the magic will have in the IPython namespace. By
421 421 default, the name of the function itself is used.
422 422 """
423 423
424 424 # Create the new method in the user_magics and register it in the
425 425 # global table
426 426 validate_type(magic_kind)
427 427 magic_name = func.func_name if magic_name is None else magic_name
428 428 setattr(self.user_magics, magic_name, func)
429 429 record_magic(self.magics, magic_kind, magic_name, func)
430 430
431 431 def define_magic(self, name, func):
432 432 """[Deprecated] Expose own function as magic function for IPython.
433 433
434 434 Example::
435 435
436 436 def foo_impl(self, parameter_s=''):
437 437 'My very own magic!. (Use docstrings, IPython reads them).'
438 438 print 'Magic function. Passed parameter is between < >:'
439 439 print '<%s>' % parameter_s
440 440 print 'The self object is:', self
441 441
442 442 ip.define_magic('foo',foo_impl)
443 443 """
444 444 meth = types.MethodType(func, self.user_magics)
445 445 setattr(self.user_magics, name, meth)
446 446 record_magic(self.magics, 'line', name, meth)
447 447
448 448 def register_alias(self, alias_name, magic_name, magic_kind='line'):
449 449 """Register an alias to a magic function.
450 450
451 451 The alias is an instance of :class:`MagicAlias`, which holds the
452 452 name and kind of the magic it should call. Binding is done at
453 453 call time, so if the underlying magic function is changed the alias
454 454 will call the new function.
455 455
456 456 Parameters
457 457 ----------
458 458 alias_name : str
459 459 The name of the magic to be registered.
460 460
461 461 magic_name : str
462 462 The name of an existing magic.
463 463
464 464 magic_kind : str
465 465 Kind of magic, one of 'line' or 'cell'
466 466 """
467 467
468 468 # `validate_type` is too permissive, as it allows 'line_cell'
469 469 # which we do not handle.
470 470 if magic_kind not in magic_kinds:
471 471 raise ValueError('magic_kind must be one of %s, %s given' %
472 472 magic_kinds, magic_kind)
473 473
474 474 alias = MagicAlias(self.shell, magic_name, magic_kind)
475 475 setattr(self.user_magics, alias_name, alias)
476 476 record_magic(self.magics, magic_kind, alias_name, alias)
477 477
478 478 # Key base class that provides the central functionality for magics.
479 479
480 480 class Magics(object):
481 481 """Base class for implementing magic functions.
482 482
483 483 Shell functions which can be reached as %function_name. All magic
484 484 functions should accept a string, which they can parse for their own
485 485 needs. This can make some functions easier to type, eg `%cd ../`
486 486 vs. `%cd("../")`
487 487
488 488 Classes providing magic functions need to subclass this class, and they
489 489 MUST:
490 490
491 491 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
492 individual methods as magic functions, AND
492 individual methods as magic functions, AND
493 493
494 494 - Use the class decorator `@magics_class` to ensure that the magic
495 methods are properly registered at the instance level upon instance
496 initialization.
495 methods are properly registered at the instance level upon instance
496 initialization.
497 497
498 498 See :mod:`magic_functions` for examples of actual implementation classes.
499 499 """
500 500 # Dict holding all command-line options for each magic.
501 501 options_table = None
502 502 # Dict for the mapping of magic names to methods, set by class decorator
503 503 magics = None
504 504 # Flag to check that the class decorator was properly applied
505 505 registered = False
506 506 # Instance of IPython shell
507 507 shell = None
508 508
509 509 def __init__(self, shell):
510 510 if not(self.__class__.registered):
511 511 raise ValueError('Magics subclass without registration - '
512 512 'did you forget to apply @magics_class?')
513 513 self.shell = shell
514 514 self.options_table = {}
515 515 # The method decorators are run when the instance doesn't exist yet, so
516 516 # they can only record the names of the methods they are supposed to
517 517 # grab. Only now, that the instance exists, can we create the proper
518 518 # mapping to bound methods. So we read the info off the original names
519 519 # table and replace each method name by the actual bound method.
520 520 # But we mustn't clobber the *class* mapping, in case of multiple instances.
521 521 class_magics = self.magics
522 522 self.magics = {}
523 523 for mtype in magic_kinds:
524 524 tab = self.magics[mtype] = {}
525 525 cls_tab = class_magics[mtype]
526 526 for magic_name, meth_name in cls_tab.iteritems():
527 527 if isinstance(meth_name, basestring):
528 528 # it's a method name, grab it
529 529 tab[magic_name] = getattr(self, meth_name)
530 530 else:
531 531 # it's the real thing
532 532 tab[magic_name] = meth_name
533 533
534 534 def arg_err(self,func):
535 535 """Print docstring if incorrect arguments were passed"""
536 536 print 'Error in arguments:'
537 537 print oinspect.getdoc(func)
538 538
539 539 def format_latex(self, strng):
540 540 """Format a string for latex inclusion."""
541 541
542 542 # Characters that need to be escaped for latex:
543 543 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
544 544 # Magic command names as headers:
545 545 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
546 546 re.MULTILINE)
547 547 # Magic commands
548 548 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
549 549 re.MULTILINE)
550 550 # Paragraph continue
551 551 par_re = re.compile(r'\\$',re.MULTILINE)
552 552
553 553 # The "\n" symbol
554 554 newline_re = re.compile(r'\\n')
555 555
556 556 # Now build the string for output:
557 557 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
558 558 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
559 559 strng)
560 560 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
561 561 strng = par_re.sub(r'\\\\',strng)
562 562 strng = escape_re.sub(r'\\\1',strng)
563 563 strng = newline_re.sub(r'\\textbackslash{}n',strng)
564 564 return strng
565 565
566 566 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
567 567 """Parse options passed to an argument string.
568 568
569 569 The interface is similar to that of getopt(), but it returns back a
570 570 Struct with the options as keys and the stripped argument string still
571 571 as a string.
572 572
573 573 arg_str is quoted as a true sys.argv vector by using shlex.split.
574 574 This allows us to easily expand variables, glob files, quote
575 575 arguments, etc.
576 576
577 577 Options:
578 578 -mode: default 'string'. If given as 'list', the argument string is
579 579 returned as a list (split on whitespace) instead of a string.
580 580
581 581 -list_all: put all option values in lists. Normally only options
582 582 appearing more than once are put in a list.
583 583
584 584 -posix (True): whether to split the input line in POSIX mode or not,
585 585 as per the conventions outlined in the shlex module from the
586 586 standard library."""
587 587
588 588 # inject default options at the beginning of the input line
589 589 caller = sys._getframe(1).f_code.co_name
590 590 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
591 591
592 592 mode = kw.get('mode','string')
593 593 if mode not in ['string','list']:
594 594 raise ValueError('incorrect mode given: %s' % mode)
595 595 # Get options
596 596 list_all = kw.get('list_all',0)
597 597 posix = kw.get('posix', os.name == 'posix')
598 598 strict = kw.get('strict', True)
599 599
600 600 # Check if we have more than one argument to warrant extra processing:
601 601 odict = {} # Dictionary with options
602 602 args = arg_str.split()
603 603 if len(args) >= 1:
604 604 # If the list of inputs only has 0 or 1 thing in it, there's no
605 605 # need to look for options
606 606 argv = arg_split(arg_str, posix, strict)
607 607 # Do regular option processing
608 608 try:
609 609 opts,args = getopt(argv, opt_str, long_opts)
610 610 except GetoptError as e:
611 611 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
612 612 " ".join(long_opts)))
613 613 for o,a in opts:
614 614 if o.startswith('--'):
615 615 o = o[2:]
616 616 else:
617 617 o = o[1:]
618 618 try:
619 619 odict[o].append(a)
620 620 except AttributeError:
621 621 odict[o] = [odict[o],a]
622 622 except KeyError:
623 623 if list_all:
624 624 odict[o] = [a]
625 625 else:
626 626 odict[o] = a
627 627
628 628 # Prepare opts,args for return
629 629 opts = Struct(odict)
630 630 if mode == 'string':
631 631 args = ' '.join(args)
632 632
633 633 return opts,args
634 634
635 635 def default_option(self, fn, optstr):
636 636 """Make an entry in the options_table for fn, with value optstr"""
637 637
638 638 if fn not in self.lsmagic():
639 639 error("%s is not a magic function" % fn)
640 640 self.options_table[fn] = optstr
641 641
642 642 class MagicAlias(object):
643 643 """An alias to another magic function.
644 644
645 645 An alias is determined by its magic name and magic kind. Lookup
646 646 is done at call time, so if the underlying magic changes the alias
647 647 will call the new function.
648 648
649 649 Use the :meth:`MagicsManager.register_alias` method or the
650 650 `%alias_magic` magic function to create and register a new alias.
651 651 """
652 652 def __init__(self, shell, magic_name, magic_kind):
653 653 self.shell = shell
654 654 self.magic_name = magic_name
655 655 self.magic_kind = magic_kind
656 656
657 657 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
658 658 self.__doc__ = "Alias for `%s`." % self.pretty_target
659 659
660 660 self._in_call = False
661 661
662 662 def __call__(self, *args, **kwargs):
663 663 """Call the magic alias."""
664 664 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
665 665 if fn is None:
666 666 raise UsageError("Magic `%s` not found." % self.pretty_target)
667 667
668 668 # Protect against infinite recursion.
669 669 if self._in_call:
670 670 raise UsageError("Infinite recursion detected; "
671 671 "magic aliases cannot call themselves.")
672 672 self._in_call = True
673 673 try:
674 674 return fn(*args, **kwargs)
675 675 finally:
676 676 self._in_call = False
@@ -1,1231 +1,1248 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2012 The IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # Stdlib
17 17 import __builtin__ as builtin_mod
18 18 import ast
19 19 import bdb
20 20 import os
21 21 import sys
22 22 import time
23 23 from StringIO import StringIO
24 24
25 25 # cProfile was added in Python2.5
26 26 try:
27 27 import cProfile as profile
28 28 import pstats
29 29 except ImportError:
30 30 # profile isn't bundled by default in Debian for license reasons
31 31 try:
32 32 import profile, pstats
33 33 except ImportError:
34 34 profile = pstats = None
35 35
36 36 # Our own packages
37 37 from IPython.core import debugger, oinspect
38 38 from IPython.core import magic_arguments
39 39 from IPython.core import page
40 40 from IPython.core.error import UsageError
41 41 from IPython.core.macro import Macro
42 42 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
43 43 line_cell_magic, on_off, needs_local_scope)
44 44 from IPython.testing.skipdoctest import skip_doctest
45 45 from IPython.utils import py3compat
46 46 from IPython.utils.contexts import preserve_keys
47 47 from IPython.utils.io import capture_output
48 48 from IPython.utils.ipstruct import Struct
49 49 from IPython.utils.module_paths import find_mod
50 50 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
51 51 from IPython.utils.timing import clock, clock2
52 52 from IPython.utils.warn import warn, error
53 53
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Magic implementation classes
57 57 #-----------------------------------------------------------------------------
58 58
59 59 @magics_class
60 60 class ExecutionMagics(Magics):
61 61 """Magics related to code execution, debugging, profiling, etc.
62 62
63 63 """
64 64
65 65 def __init__(self, shell):
66 66 super(ExecutionMagics, self).__init__(shell)
67 67 if profile is None:
68 68 self.prun = self.profile_missing_notice
69 69 # Default execution function used to actually run user code.
70 70 self.default_runner = None
71 71
72 72 def profile_missing_notice(self, *args, **kwargs):
73 73 error("""\
74 74 The profile module could not be found. It has been removed from the standard
75 75 python packages because of its non-free license. To use profiling, install the
76 76 python-profiler package from non-free.""")
77 77
78 78 @skip_doctest
79 79 @line_cell_magic
80 80 def prun(self, parameter_s='', cell=None):
81 81
82 82 """Run a statement through the python code profiler.
83 83
84 84 Usage, in line mode:
85 85 %prun [options] statement
86 86
87 87 Usage, in cell mode:
88 88 %%prun [options] [statement]
89 89 code...
90 90 code...
91 91
92 92 In cell mode, the additional code lines are appended to the (possibly
93 93 empty) statement in the first line. Cell mode allows you to easily
94 94 profile multiline blocks without having to put them in a separate
95 95 function.
96 96
97 97 The given statement (which doesn't require quote marks) is run via the
98 98 python profiler in a manner similar to the profile.run() function.
99 99 Namespaces are internally managed to work correctly; profile.run
100 100 cannot be used in IPython because it makes certain assumptions about
101 101 namespaces which do not hold under IPython.
102 102
103 103 Options:
104 104
105 -l <limit>: you can place restrictions on what or how much of the
106 profile gets printed. The limit value can be:
107
108 * A string: only information for function names containing this string
109 is printed.
110
111 * An integer: only these many lines are printed.
112
113 * A float (between 0 and 1): this fraction of the report is printed
114 (for example, use a limit of 0.4 to see the topmost 40% only).
115
116 You can combine several limits with repeated use of the option. For
117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
118 information about class constructors.
119
120 -r: return the pstats.Stats object generated by the profiling. This
121 object has all the information about the profile in it, and you can
122 later use it for further analysis or in other functions.
123
124 -s <key>: sort profile by given key. You can provide more than one key
125 by using the option several times: '-s key1 -s key2 -s key3...'. The
126 default sorting key is 'time'.
127
128 The following is copied verbatim from the profile documentation
129 referenced below:
130
131 When more than one key is provided, additional keys are used as
132 secondary criteria when the there is equality in all keys selected
133 before them.
134
135 Abbreviations can be used for any key names, as long as the
136 abbreviation is unambiguous. The following are the keys currently
137 defined:
138
139 Valid Arg Meaning
140 "calls" call count
141 "cumulative" cumulative time
142 "file" file name
143 "module" file name
144 "pcalls" primitive call count
145 "line" line number
146 "name" function name
147 "nfl" name/file/line
148 "stdname" standard name
149 "time" internal time
150
151 Note that all sorts on statistics are in descending order (placing
152 most time consuming items first), where as name, file, and line number
153 searches are in ascending order (i.e., alphabetical). The subtle
154 distinction between "nfl" and "stdname" is that the standard name is a
155 sort of the name as printed, which means that the embedded line
156 numbers get compared in an odd way. For example, lines 3, 20, and 40
157 would (if the file names were the same) appear in the string order
158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
159 line numbers. In fact, sort_stats("nfl") is the same as
160 sort_stats("name", "file", "line").
161
162 -T <filename>: save profile results as shown on screen to a text
163 file. The profile is still shown on screen.
164
165 -D <filename>: save (via dump_stats) profile statistics to given
166 filename. This data is in a format understood by the pstats module, and
167 is generated by a call to the dump_stats() method of profile
168 objects. The profile is still shown on screen.
169
170 -q: suppress output to the pager. Best used with -T and/or -D above.
105 -l <limit>
106 you can place restrictions on what or how much of the
107 profile gets printed. The limit value can be:
108
109 * A string: only information for function names containing this string
110 is printed.
111
112 * An integer: only these many lines are printed.
113
114 * A float (between 0 and 1): this fraction of the report is printed
115 (for example, use a limit of 0.4 to see the topmost 40% only).
116
117 You can combine several limits with repeated use of the option. For
118 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
119 information about class constructors.
120
121 -r
122 return the pstats.Stats object generated by the profiling. This
123 object has all the information about the profile in it, and you can
124 later use it for further analysis or in other functions.
125
126 -s <key>
127 sort profile by given key. You can provide more than one key
128 by using the option several times: '-s key1 -s key2 -s key3...'. The
129 default sorting key is 'time'.
130
131 The following is copied verbatim from the profile documentation
132 referenced below:
133
134 When more than one key is provided, additional keys are used as
135 secondary criteria when the there is equality in all keys selected
136 before them.
137
138 Abbreviations can be used for any key names, as long as the
139 abbreviation is unambiguous. The following are the keys currently
140 defined:
141
142 ============ =====================
143 Valid Arg Meaning
144 ============ =====================
145 "calls" call count
146 "cumulative" cumulative time
147 "file" file name
148 "module" file name
149 "pcalls" primitive call count
150 "line" line number
151 "name" function name
152 "nfl" name/file/line
153 "stdname" standard name
154 "time" internal time
155 ============ =====================
156
157 Note that all sorts on statistics are in descending order (placing
158 most time consuming items first), where as name, file, and line number
159 searches are in ascending order (i.e., alphabetical). The subtle
160 distinction between "nfl" and "stdname" is that the standard name is a
161 sort of the name as printed, which means that the embedded line
162 numbers get compared in an odd way. For example, lines 3, 20, and 40
163 would (if the file names were the same) appear in the string order
164 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
165 line numbers. In fact, sort_stats("nfl") is the same as
166 sort_stats("name", "file", "line").
167
168 -T <filename>
169 save profile results as shown on screen to a text
170 file. The profile is still shown on screen.
171
172 -D <filename>
173 save (via dump_stats) profile statistics to given
174 filename. This data is in a format understood by the pstats module, and
175 is generated by a call to the dump_stats() method of profile
176 objects. The profile is still shown on screen.
177
178 -q
179 suppress output to the pager. Best used with -T and/or -D above.
171 180
172 181 If you want to run complete programs under the profiler's control, use
173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
182 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
174 183 contains profiler specific options as described here.
175 184
176 185 You can read the complete documentation for the profile module with::
177 186
178 187 In [1]: import profile; profile.help()
179 188 """
180 189 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
181 190 list_all=True, posix=False)
182 191 if cell is not None:
183 192 arg_str += '\n' + cell
184 193 arg_str = self.shell.input_splitter.transform_cell(arg_str)
185 194 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
186 195
187 196 def _run_with_profiler(self, code, opts, namespace):
188 197 """
189 198 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
190 199
191 200 Parameters
192 201 ----------
193 202 code : str
194 203 Code to be executed.
195 204 opts : Struct
196 205 Options parsed by `self.parse_options`.
197 206 namespace : dict
198 207 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
199 208
200 209 """
201 210
202 211 # Fill default values for unspecified options:
203 212 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
204 213
205 214 prof = profile.Profile()
206 215 try:
207 216 prof = prof.runctx(code, namespace, namespace)
208 217 sys_exit = ''
209 218 except SystemExit:
210 219 sys_exit = """*** SystemExit exception caught in code being profiled."""
211 220
212 221 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
213 222
214 223 lims = opts.l
215 224 if lims:
216 225 lims = [] # rebuild lims with ints/floats/strings
217 226 for lim in opts.l:
218 227 try:
219 228 lims.append(int(lim))
220 229 except ValueError:
221 230 try:
222 231 lims.append(float(lim))
223 232 except ValueError:
224 233 lims.append(lim)
225 234
226 235 # Trap output.
227 236 stdout_trap = StringIO()
228 237 stats_stream = stats.stream
229 238 try:
230 239 stats.stream = stdout_trap
231 240 stats.print_stats(*lims)
232 241 finally:
233 242 stats.stream = stats_stream
234 243
235 244 output = stdout_trap.getvalue()
236 245 output = output.rstrip()
237 246
238 247 if 'q' not in opts:
239 248 page.page(output)
240 249 print sys_exit,
241 250
242 251 dump_file = opts.D[0]
243 252 text_file = opts.T[0]
244 253 if dump_file:
245 254 dump_file = unquote_filename(dump_file)
246 255 prof.dump_stats(dump_file)
247 256 print '\n*** Profile stats marshalled to file',\
248 257 repr(dump_file)+'.',sys_exit
249 258 if text_file:
250 259 text_file = unquote_filename(text_file)
251 260 pfile = open(text_file,'w')
252 261 pfile.write(output)
253 262 pfile.close()
254 263 print '\n*** Profile printout saved to text file',\
255 264 repr(text_file)+'.',sys_exit
256 265
257 266 if 'r' in opts:
258 267 return stats
259 268 else:
260 269 return None
261 270
262 271 @line_magic
263 272 def pdb(self, parameter_s=''):
264 273 """Control the automatic calling of the pdb interactive debugger.
265 274
266 275 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
267 276 argument it works as a toggle.
268 277
269 278 When an exception is triggered, IPython can optionally call the
270 279 interactive pdb debugger after the traceback printout. %pdb toggles
271 280 this feature on and off.
272 281
273 282 The initial state of this feature is set in your configuration
274 283 file (the option is ``InteractiveShell.pdb``).
275 284
276 285 If you want to just activate the debugger AFTER an exception has fired,
277 286 without having to type '%pdb on' and rerunning your code, you can use
278 287 the %debug magic."""
279 288
280 289 par = parameter_s.strip().lower()
281 290
282 291 if par:
283 292 try:
284 293 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
285 294 except KeyError:
286 295 print ('Incorrect argument. Use on/1, off/0, '
287 296 'or nothing for a toggle.')
288 297 return
289 298 else:
290 299 # toggle
291 300 new_pdb = not self.shell.call_pdb
292 301
293 302 # set on the shell
294 303 self.shell.call_pdb = new_pdb
295 304 print 'Automatic pdb calling has been turned',on_off(new_pdb)
296 305
297 306 @skip_doctest
298 307 @magic_arguments.magic_arguments()
299 308 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
300 309 help="""
301 310 Set break point at LINE in FILE.
302 311 """
303 312 )
304 313 @magic_arguments.argument('statement', nargs='*',
305 314 help="""
306 315 Code to run in debugger.
307 316 You can omit this in cell magic mode.
308 317 """
309 318 )
310 319 @line_cell_magic
311 320 def debug(self, line='', cell=None):
312 321 """Activate the interactive debugger.
313 322
314 323 This magic command support two ways of activating debugger.
315 324 One is to activate debugger before executing code. This way, you
316 325 can set a break point, to step through the code from the point.
317 326 You can use this mode by giving statements to execute and optionally
318 327 a breakpoint.
319 328
320 329 The other one is to activate debugger in post-mortem mode. You can
321 330 activate this mode simply running %debug without any argument.
322 331 If an exception has just occurred, this lets you inspect its stack
323 332 frames interactively. Note that this will always work only on the last
324 333 traceback that occurred, so you must call this quickly after an
325 334 exception that you wish to inspect has fired, because if another one
326 335 occurs, it clobbers the previous one.
327 336
328 337 If you want IPython to automatically do this on every exception, see
329 338 the %pdb magic for more details.
330 339 """
331 340 args = magic_arguments.parse_argstring(self.debug, line)
332 341
333 342 if not (args.breakpoint or args.statement or cell):
334 343 self._debug_post_mortem()
335 344 else:
336 345 code = "\n".join(args.statement)
337 346 if cell:
338 347 code += "\n" + cell
339 348 self._debug_exec(code, args.breakpoint)
340 349
341 350 def _debug_post_mortem(self):
342 351 self.shell.debugger(force=True)
343 352
344 353 def _debug_exec(self, code, breakpoint):
345 354 if breakpoint:
346 355 (filename, bp_line) = breakpoint.split(':', 1)
347 356 bp_line = int(bp_line)
348 357 else:
349 358 (filename, bp_line) = (None, None)
350 359 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
351 360
352 361 @line_magic
353 362 def tb(self, s):
354 363 """Print the last traceback with the currently active exception mode.
355 364
356 365 See %xmode for changing exception reporting modes."""
357 366 self.shell.showtraceback()
358 367
359 368 @skip_doctest
360 369 @line_magic
361 370 def run(self, parameter_s='', runner=None,
362 371 file_finder=get_py_filename):
363 372 """Run the named file inside IPython as a program.
364 373
365 Usage:
374 Usage::
375
366 376 %run [-n -i -e -G]
367 377 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
368 378 ( -m mod | file ) [args]
369 379
370 380 Parameters after the filename are passed as command-line arguments to
371 381 the program (put in sys.argv). Then, control returns to IPython's
372 382 prompt.
373 383
374 This is similar to running at a system prompt:\\
375 $ python file args\\
384 This is similar to running at a system prompt ``python file args``,
376 385 but with the advantage of giving you IPython's tracebacks, and of
377 386 loading all variables into your interactive namespace for further use
378 387 (unless -p is used, see below).
379 388
380 389 The file is executed in a namespace initially consisting only of
381 __name__=='__main__' and sys.argv constructed as indicated. It thus
390 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
382 391 sees its environment as if it were being run as a stand-alone program
383 392 (except for sharing global objects such as previously imported
384 393 modules). But after execution, the IPython interactive namespace gets
385 394 updated with all variables defined in the program (except for __name__
386 395 and sys.argv). This allows for very convenient loading of code for
387 396 interactive work, while giving each program a 'clean sheet' to run in.
388 397
389 398 Arguments are expanded using shell-like glob match. Patterns
390 399 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
391 400 tilde '~' will be expanded into user's home directory. Unlike
392 401 real shells, quotation does not suppress expansions. Use
393 *two* back slashes (e.g., '\\\\*') to suppress expansions.
402 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
394 403 To completely disable these expansions, you can use -G flag.
395 404
396 405 Options:
397 406
398 -n: __name__ is NOT set to '__main__', but to the running file's name
399 without extension (as python does under import). This allows running
400 scripts and reloading the definitions in them without calling code
401 protected by an ' if __name__ == "__main__" ' clause.
402
403 -i: run the file in IPython's namespace instead of an empty one. This
404 is useful if you are experimenting with code written in a text editor
405 which depends on variables defined interactively.
406
407 -e: ignore sys.exit() calls or SystemExit exceptions in the script
408 being run. This is particularly useful if IPython is being used to
409 run unittests, which always exit with a sys.exit() call. In such
410 cases you are interested in the output of the test results, not in
411 seeing a traceback of the unittest module.
412
413 -t: print timing information at the end of the run. IPython will give
414 you an estimated CPU time consumption for your script, which under
415 Unix uses the resource module to avoid the wraparound problems of
416 time.clock(). Under Unix, an estimate of time spent on system tasks
417 is also given (for Windows platforms this is reported as 0.0).
418
419 If -t is given, an additional -N<N> option can be given, where <N>
407 -n
408 __name__ is NOT set to '__main__', but to the running file's name
409 without extension (as python does under import). This allows running
410 scripts and reloading the definitions in them without calling code
411 protected by an ``if __name__ == "__main__"`` clause.
412
413 -i
414 run the file in IPython's namespace instead of an empty one. This
415 is useful if you are experimenting with code written in a text editor
416 which depends on variables defined interactively.
417
418 -e
419 ignore sys.exit() calls or SystemExit exceptions in the script
420 being run. This is particularly useful if IPython is being used to
421 run unittests, which always exit with a sys.exit() call. In such
422 cases you are interested in the output of the test results, not in
423 seeing a traceback of the unittest module.
424
425 -t
426 print timing information at the end of the run. IPython will give
427 you an estimated CPU time consumption for your script, which under
428 Unix uses the resource module to avoid the wraparound problems of
429 time.clock(). Under Unix, an estimate of time spent on system tasks
430 is also given (for Windows platforms this is reported as 0.0).
431
432 If -t is given, an additional ``-N<N>`` option can be given, where <N>
420 433 must be an integer indicating how many times you want the script to
421 434 run. The final timing report will include total and per run results.
422 435
423 436 For example (testing the script uniq_stable.py)::
424 437
425 438 In [1]: run -t uniq_stable
426 439
427 IPython CPU timings (estimated):\\
428 User : 0.19597 s.\\
429 System: 0.0 s.\\
440 IPython CPU timings (estimated):
441 User : 0.19597 s.
442 System: 0.0 s.
430 443
431 444 In [2]: run -t -N5 uniq_stable
432 445
433 IPython CPU timings (estimated):\\
434 Total runs performed: 5\\
435 Times : Total Per run\\
436 User : 0.910862 s, 0.1821724 s.\\
446 IPython CPU timings (estimated):
447 Total runs performed: 5
448 Times : Total Per run
449 User : 0.910862 s, 0.1821724 s.
437 450 System: 0.0 s, 0.0 s.
438 451
439 -d: run your program under the control of pdb, the Python debugger.
440 This allows you to execute your program step by step, watch variables,
441 etc. Internally, what IPython does is similar to calling:
452 -d
453 run your program under the control of pdb, the Python debugger.
454 This allows you to execute your program step by step, watch variables,
455 etc. Internally, what IPython does is similar to calling::
442 456
443 pdb.run('execfile("YOURFILENAME")')
457 pdb.run('execfile("YOURFILENAME")')
444 458
445 with a breakpoint set on line 1 of your file. You can change the line
446 number for this automatic breakpoint to be <N> by using the -bN option
447 (where N must be an integer). For example::
459 with a breakpoint set on line 1 of your file. You can change the line
460 number for this automatic breakpoint to be <N> by using the -bN option
461 (where N must be an integer). For example::
448 462
449 %run -d -b40 myscript
463 %run -d -b40 myscript
450 464
451 will set the first breakpoint at line 40 in myscript.py. Note that
452 the first breakpoint must be set on a line which actually does
453 something (not a comment or docstring) for it to stop execution.
465 will set the first breakpoint at line 40 in myscript.py. Note that
466 the first breakpoint must be set on a line which actually does
467 something (not a comment or docstring) for it to stop execution.
454 468
455 Or you can specify a breakpoint in a different file::
469 Or you can specify a breakpoint in a different file::
456 470
457 %run -d -b myotherfile.py:20 myscript
471 %run -d -b myotherfile.py:20 myscript
458 472
459 When the pdb debugger starts, you will see a (Pdb) prompt. You must
460 first enter 'c' (without quotes) to start execution up to the first
461 breakpoint.
473 When the pdb debugger starts, you will see a (Pdb) prompt. You must
474 first enter 'c' (without quotes) to start execution up to the first
475 breakpoint.
462 476
463 Entering 'help' gives information about the use of the debugger. You
464 can easily see pdb's full documentation with "import pdb;pdb.help()"
465 at a prompt.
477 Entering 'help' gives information about the use of the debugger. You
478 can easily see pdb's full documentation with "import pdb;pdb.help()"
479 at a prompt.
466 480
467 -p: run program under the control of the Python profiler module (which
468 prints a detailed report of execution times, function calls, etc).
481 -p
482 run program under the control of the Python profiler module (which
483 prints a detailed report of execution times, function calls, etc).
469 484
470 You can pass other options after -p which affect the behavior of the
471 profiler itself. See the docs for %prun for details.
485 You can pass other options after -p which affect the behavior of the
486 profiler itself. See the docs for %prun for details.
472 487
473 In this mode, the program's variables do NOT propagate back to the
474 IPython interactive namespace (because they remain in the namespace
475 where the profiler executes them).
488 In this mode, the program's variables do NOT propagate back to the
489 IPython interactive namespace (because they remain in the namespace
490 where the profiler executes them).
476 491
477 Internally this triggers a call to %prun, see its documentation for
478 details on the options available specifically for profiling.
492 Internally this triggers a call to %prun, see its documentation for
493 details on the options available specifically for profiling.
479 494
480 495 There is one special usage for which the text above doesn't apply:
481 496 if the filename ends with .ipy, the file is run as ipython script,
482 497 just as if the commands were written on IPython prompt.
483 498
484 -m: specify module name to load instead of script path. Similar to
485 the -m option for the python interpreter. Use this option last if you
486 want to combine with other %run options. Unlike the python interpreter
487 only source modules are allowed no .pyc or .pyo files.
488 For example::
499 -m
500 specify module name to load instead of script path. Similar to
501 the -m option for the python interpreter. Use this option last if you
502 want to combine with other %run options. Unlike the python interpreter
503 only source modules are allowed no .pyc or .pyo files.
504 For example::
489 505
490 %run -m example
506 %run -m example
491 507
492 will run the example module.
508 will run the example module.
493 509
494 -G: disable shell-like glob expansion of arguments.
510 -G
511 disable shell-like glob expansion of arguments.
495 512
496 513 """
497 514
498 515 # get arguments and set sys.argv for program to be run.
499 516 opts, arg_lst = self.parse_options(parameter_s,
500 517 'nidtN:b:pD:l:rs:T:em:G',
501 518 mode='list', list_all=1)
502 519 if "m" in opts:
503 520 modulename = opts["m"][0]
504 521 modpath = find_mod(modulename)
505 522 if modpath is None:
506 523 warn('%r is not a valid modulename on sys.path'%modulename)
507 524 return
508 525 arg_lst = [modpath] + arg_lst
509 526 try:
510 527 filename = file_finder(arg_lst[0])
511 528 except IndexError:
512 529 warn('you must provide at least a filename.')
513 530 print '\n%run:\n', oinspect.getdoc(self.run)
514 531 return
515 532 except IOError as e:
516 533 try:
517 534 msg = str(e)
518 535 except UnicodeError:
519 536 msg = e.message
520 537 error(msg)
521 538 return
522 539
523 540 if filename.lower().endswith('.ipy'):
524 541 with preserve_keys(self.shell.user_ns, '__file__'):
525 542 self.shell.user_ns['__file__'] = filename
526 543 self.shell.safe_execfile_ipy(filename)
527 544 return
528 545
529 546 # Control the response to exit() calls made by the script being run
530 547 exit_ignore = 'e' in opts
531 548
532 549 # Make sure that the running script gets a proper sys.argv as if it
533 550 # were run from a system shell.
534 551 save_argv = sys.argv # save it for later restoring
535 552
536 553 if 'G' in opts:
537 554 args = arg_lst[1:]
538 555 else:
539 556 # tilde and glob expansion
540 557 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
541 558
542 559 sys.argv = [filename] + args # put in the proper filename
543 560 # protect sys.argv from potential unicode strings on Python 2:
544 561 if not py3compat.PY3:
545 562 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
546 563
547 564 if 'i' in opts:
548 565 # Run in user's interactive namespace
549 566 prog_ns = self.shell.user_ns
550 567 __name__save = self.shell.user_ns['__name__']
551 568 prog_ns['__name__'] = '__main__'
552 569 main_mod = self.shell.user_module
553 570 else:
554 571 # Run in a fresh, empty namespace
555 572 if 'n' in opts:
556 573 name = os.path.splitext(os.path.basename(filename))[0]
557 574 else:
558 575 name = '__main__'
559 576
560 577 # The shell MUST hold a reference to prog_ns so after %run
561 578 # exits, the python deletion mechanism doesn't zero it out
562 579 # (leaving dangling references). See interactiveshell for details
563 580 main_mod = self.shell.new_main_mod(filename)
564 581 prog_ns = main_mod.__dict__
565 582 prog_ns['__name__'] = name
566 583
567 584 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
568 585 # set the __file__ global in the script's namespace
569 586 prog_ns['__file__'] = filename
570 587
571 588 # pickle fix. See interactiveshell for an explanation. But we need to
572 589 # make sure that, if we overwrite __main__, we replace it at the end
573 590 main_mod_name = prog_ns['__name__']
574 591
575 592 if main_mod_name == '__main__':
576 593 restore_main = sys.modules['__main__']
577 594 else:
578 595 restore_main = False
579 596
580 597 # This needs to be undone at the end to prevent holding references to
581 598 # every single object ever created.
582 599 sys.modules[main_mod_name] = main_mod
583 600
584 601 if 'p' in opts or 'd' in opts:
585 602 if 'm' in opts:
586 603 code = 'run_module(modulename, prog_ns)'
587 604 code_ns = {
588 605 'run_module': self.shell.safe_run_module,
589 606 'prog_ns': prog_ns,
590 607 'modulename': modulename,
591 608 }
592 609 else:
593 610 code = 'execfile(filename, prog_ns)'
594 611 code_ns = {
595 612 'execfile': self.shell.safe_execfile,
596 613 'prog_ns': prog_ns,
597 614 'filename': get_py_filename(filename),
598 615 }
599 616
600 617 try:
601 618 stats = None
602 619 with self.shell.readline_no_record:
603 620 if 'p' in opts:
604 621 stats = self._run_with_profiler(code, opts, code_ns)
605 622 else:
606 623 if 'd' in opts:
607 624 bp_file, bp_line = parse_breakpoint(
608 625 opts.get('b', ['1'])[0], filename)
609 626 self._run_with_debugger(
610 627 code, code_ns, filename, bp_line, bp_file)
611 628 else:
612 629 if 'm' in opts:
613 630 def run():
614 631 self.shell.safe_run_module(modulename, prog_ns)
615 632 else:
616 633 if runner is None:
617 634 runner = self.default_runner
618 635 if runner is None:
619 636 runner = self.shell.safe_execfile
620 637
621 638 def run():
622 639 runner(filename, prog_ns, prog_ns,
623 640 exit_ignore=exit_ignore)
624 641
625 642 if 't' in opts:
626 643 # timed execution
627 644 try:
628 645 nruns = int(opts['N'][0])
629 646 if nruns < 1:
630 647 error('Number of runs must be >=1')
631 648 return
632 649 except (KeyError):
633 650 nruns = 1
634 651 self._run_with_timing(run, nruns)
635 652 else:
636 653 # regular execution
637 654 run()
638 655
639 656 if 'i' in opts:
640 657 self.shell.user_ns['__name__'] = __name__save
641 658 else:
642 659 # update IPython interactive namespace
643 660
644 661 # Some forms of read errors on the file may mean the
645 662 # __name__ key was never set; using pop we don't have to
646 663 # worry about a possible KeyError.
647 664 prog_ns.pop('__name__', None)
648 665
649 666 with preserve_keys(self.shell.user_ns, '__file__'):
650 667 self.shell.user_ns.update(prog_ns)
651 668 finally:
652 669 # It's a bit of a mystery why, but __builtins__ can change from
653 670 # being a module to becoming a dict missing some key data after
654 671 # %run. As best I can see, this is NOT something IPython is doing
655 672 # at all, and similar problems have been reported before:
656 673 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
657 674 # Since this seems to be done by the interpreter itself, the best
658 675 # we can do is to at least restore __builtins__ for the user on
659 676 # exit.
660 677 self.shell.user_ns['__builtins__'] = builtin_mod
661 678
662 679 # Ensure key global structures are restored
663 680 sys.argv = save_argv
664 681 if restore_main:
665 682 sys.modules['__main__'] = restore_main
666 683 else:
667 684 # Remove from sys.modules the reference to main_mod we'd
668 685 # added. Otherwise it will trap references to objects
669 686 # contained therein.
670 687 del sys.modules[main_mod_name]
671 688
672 689 return stats
673 690
674 691 def _run_with_debugger(self, code, code_ns, filename=None,
675 692 bp_line=None, bp_file=None):
676 693 """
677 694 Run `code` in debugger with a break point.
678 695
679 696 Parameters
680 697 ----------
681 698 code : str
682 699 Code to execute.
683 700 code_ns : dict
684 701 A namespace in which `code` is executed.
685 702 filename : str
686 703 `code` is ran as if it is in `filename`.
687 704 bp_line : int, optional
688 705 Line number of the break point.
689 706 bp_file : str, optional
690 707 Path to the file in which break point is specified.
691 708 `filename` is used if not given.
692 709
693 710 Raises
694 711 ------
695 712 UsageError
696 713 If the break point given by `bp_line` is not valid.
697 714
698 715 """
699 716 deb = debugger.Pdb(self.shell.colors)
700 717 # reset Breakpoint state, which is moronically kept
701 718 # in a class
702 719 bdb.Breakpoint.next = 1
703 720 bdb.Breakpoint.bplist = {}
704 721 bdb.Breakpoint.bpbynumber = [None]
705 722 if bp_line is not None:
706 723 # Set an initial breakpoint to stop execution
707 724 maxtries = 10
708 725 bp_file = bp_file or filename
709 726 checkline = deb.checkline(bp_file, bp_line)
710 727 if not checkline:
711 728 for bp in range(bp_line + 1, bp_line + maxtries + 1):
712 729 if deb.checkline(bp_file, bp):
713 730 break
714 731 else:
715 732 msg = ("\nI failed to find a valid line to set "
716 733 "a breakpoint\n"
717 734 "after trying up to line: %s.\n"
718 735 "Please set a valid breakpoint manually "
719 736 "with the -b option." % bp)
720 737 raise UsageError(msg)
721 738 # if we find a good linenumber, set the breakpoint
722 739 deb.do_break('%s:%s' % (bp_file, bp_line))
723 740
724 741 if filename:
725 742 # Mimic Pdb._runscript(...)
726 743 deb._wait_for_mainpyfile = True
727 744 deb.mainpyfile = deb.canonic(filename)
728 745
729 746 # Start file run
730 747 print "NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt
731 748 try:
732 749 if filename:
733 750 # save filename so it can be used by methods on the deb object
734 751 deb._exec_filename = filename
735 752 deb.run(code, code_ns)
736 753
737 754 except:
738 755 etype, value, tb = sys.exc_info()
739 756 # Skip three frames in the traceback: the %run one,
740 757 # one inside bdb.py, and the command-line typed by the
741 758 # user (run by exec in pdb itself).
742 759 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
743 760
744 761 @staticmethod
745 762 def _run_with_timing(run, nruns):
746 763 """
747 764 Run function `run` and print timing information.
748 765
749 766 Parameters
750 767 ----------
751 768 run : callable
752 769 Any callable object which takes no argument.
753 770 nruns : int
754 771 Number of times to execute `run`.
755 772
756 773 """
757 774 twall0 = time.time()
758 775 if nruns == 1:
759 776 t0 = clock2()
760 777 run()
761 778 t1 = clock2()
762 779 t_usr = t1[0] - t0[0]
763 780 t_sys = t1[1] - t0[1]
764 781 print "\nIPython CPU timings (estimated):"
765 782 print " User : %10.2f s." % t_usr
766 783 print " System : %10.2f s." % t_sys
767 784 else:
768 785 runs = range(nruns)
769 786 t0 = clock2()
770 787 for nr in runs:
771 788 run()
772 789 t1 = clock2()
773 790 t_usr = t1[0] - t0[0]
774 791 t_sys = t1[1] - t0[1]
775 792 print "\nIPython CPU timings (estimated):"
776 793 print "Total runs performed:", nruns
777 794 print " Times : %10s %10s" % ('Total', 'Per run')
778 795 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
779 796 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
780 797 twall1 = time.time()
781 798 print "Wall time: %10.2f s." % (twall1 - twall0)
782 799
783 800 @skip_doctest
784 801 @line_cell_magic
785 802 def timeit(self, line='', cell=None):
786 803 """Time execution of a Python statement or expression
787 804
788 805 Usage, in line mode:
789 806 %timeit [-n<N> -r<R> [-t|-c]] statement
790 807 or in cell mode:
791 808 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
792 809 code
793 810 code...
794 811
795 812 Time execution of a Python statement or expression using the timeit
796 813 module. This function can be used both as a line and cell magic:
797 814
798 815 - In line mode you can time a single-line statement (though multiple
799 816 ones can be chained with using semicolons).
800 817
801 818 - In cell mode, the statement in the first line is used as setup code
802 819 (executed but not timed) and the body of the cell is timed. The cell
803 820 body has access to any variables created in the setup code.
804 821
805 822 Options:
806 823 -n<N>: execute the given statement <N> times in a loop. If this value
807 824 is not given, a fitting value is chosen.
808 825
809 826 -r<R>: repeat the loop iteration <R> times and take the best result.
810 827 Default: 3
811 828
812 829 -t: use time.time to measure the time, which is the default on Unix.
813 830 This function measures wall time.
814 831
815 832 -c: use time.clock to measure the time, which is the default on
816 833 Windows and measures wall time. On Unix, resource.getrusage is used
817 834 instead and returns the CPU user time.
818 835
819 836 -p<P>: use a precision of <P> digits to display the timing result.
820 837 Default: 3
821 838
822 839
823 840 Examples
824 841 --------
825 842 ::
826 843
827 844 In [1]: %timeit pass
828 845 10000000 loops, best of 3: 53.3 ns per loop
829 846
830 847 In [2]: u = None
831 848
832 849 In [3]: %timeit u is None
833 850 10000000 loops, best of 3: 184 ns per loop
834 851
835 852 In [4]: %timeit -r 4 u == None
836 853 1000000 loops, best of 4: 242 ns per loop
837 854
838 855 In [5]: import time
839 856
840 857 In [6]: %timeit -n1 time.sleep(2)
841 858 1 loops, best of 3: 2 s per loop
842 859
843 860
844 861 The times reported by %timeit will be slightly higher than those
845 862 reported by the timeit.py script when variables are accessed. This is
846 863 due to the fact that %timeit executes the statement in the namespace
847 864 of the shell, compared with timeit.py, which uses a single setup
848 865 statement to import function or create variables. Generally, the bias
849 866 does not matter as long as results from timeit.py are not mixed with
850 867 those from %timeit."""
851 868
852 869 import timeit
853 870
854 871 opts, stmt = self.parse_options(line,'n:r:tcp:',
855 872 posix=False, strict=False)
856 873 if stmt == "" and cell is None:
857 874 return
858 875
859 876 timefunc = timeit.default_timer
860 877 number = int(getattr(opts, "n", 0))
861 878 repeat = int(getattr(opts, "r", timeit.default_repeat))
862 879 precision = int(getattr(opts, "p", 3))
863 880 if hasattr(opts, "t"):
864 881 timefunc = time.time
865 882 if hasattr(opts, "c"):
866 883 timefunc = clock
867 884
868 885 timer = timeit.Timer(timer=timefunc)
869 886 # this code has tight coupling to the inner workings of timeit.Timer,
870 887 # but is there a better way to achieve that the code stmt has access
871 888 # to the shell namespace?
872 889 transform = self.shell.input_splitter.transform_cell
873 890
874 891 if cell is None:
875 892 # called as line magic
876 893 ast_setup = ast.parse("pass")
877 894 ast_stmt = ast.parse(transform(stmt))
878 895 else:
879 896 ast_setup = ast.parse(transform(stmt))
880 897 ast_stmt = ast.parse(transform(cell))
881 898
882 899 ast_setup = self.shell.transform_ast(ast_setup)
883 900 ast_stmt = self.shell.transform_ast(ast_stmt)
884 901
885 902 # This codestring is taken from timeit.template - we fill it in as an
886 903 # AST, so that we can apply our AST transformations to the user code
887 904 # without affecting the timing code.
888 905 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
889 906 ' setup\n'
890 907 ' _t0 = _timer()\n'
891 908 ' for _i in _it:\n'
892 909 ' stmt\n'
893 910 ' _t1 = _timer()\n'
894 911 ' return _t1 - _t0\n')
895 912
896 913 class TimeitTemplateFiller(ast.NodeTransformer):
897 914 "This is quite tightly tied to the template definition above."
898 915 def visit_FunctionDef(self, node):
899 916 "Fill in the setup statement"
900 917 self.generic_visit(node)
901 918 if node.name == "inner":
902 919 node.body[:1] = ast_setup.body
903 920
904 921 return node
905 922
906 923 def visit_For(self, node):
907 924 "Fill in the statement to be timed"
908 925 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
909 926 node.body = ast_stmt.body
910 927 return node
911 928
912 929 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
913 930 timeit_ast = ast.fix_missing_locations(timeit_ast)
914 931
915 932 # Track compilation time so it can be reported if too long
916 933 # Minimum time above which compilation time will be reported
917 934 tc_min = 0.1
918 935
919 936 t0 = clock()
920 937 code = compile(timeit_ast, "<magic-timeit>", "exec")
921 938 tc = clock()-t0
922 939
923 940 ns = {}
924 941 exec code in self.shell.user_ns, ns
925 942 timer.inner = ns["inner"]
926 943
927 944 if number == 0:
928 945 # determine number so that 0.2 <= total time < 2.0
929 946 number = 1
930 947 for i in range(1, 10):
931 948 if timer.timeit(number) >= 0.2:
932 949 break
933 950 number *= 10
934 951
935 952 best = min(timer.repeat(repeat, number)) / number
936 953
937 954 print u"%d loops, best of %d: %s per loop" % (number, repeat,
938 955 _format_time(best, precision))
939 956 if tc > tc_min:
940 957 print "Compiler time: %.2f s" % tc
941 958
942 959 @skip_doctest
943 960 @needs_local_scope
944 961 @line_cell_magic
945 962 def time(self,line='', cell=None, local_ns=None):
946 963 """Time execution of a Python statement or expression.
947 964
948 965 The CPU and wall clock times are printed, and the value of the
949 966 expression (if any) is returned. Note that under Win32, system time
950 967 is always reported as 0, since it can not be measured.
951 968
952 969 This function can be used both as a line and cell magic:
953 970
954 971 - In line mode you can time a single-line statement (though multiple
955 972 ones can be chained with using semicolons).
956 973
957 974 - In cell mode, you can time the cell body (a directly
958 975 following statement raises an error).
959 976
960 977 This function provides very basic timing functionality. Use the timeit
961 978 magic for more controll over the measurement.
962 979
963 980 Examples
964 981 --------
965 982 ::
966 983
967 984 In [1]: %time 2**128
968 985 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
969 986 Wall time: 0.00
970 987 Out[1]: 340282366920938463463374607431768211456L
971 988
972 989 In [2]: n = 1000000
973 990
974 991 In [3]: %time sum(range(n))
975 992 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
976 993 Wall time: 1.37
977 994 Out[3]: 499999500000L
978 995
979 996 In [4]: %time print 'hello world'
980 997 hello world
981 998 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
982 999 Wall time: 0.00
983 1000
984 1001 Note that the time needed by Python to compile the given expression
985 1002 will be reported if it is more than 0.1s. In this example, the
986 1003 actual exponentiation is done by Python at compilation time, so while
987 1004 the expression can take a noticeable amount of time to compute, that
988 1005 time is purely due to the compilation:
989 1006
990 1007 In [5]: %time 3**9999;
991 1008 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
992 1009 Wall time: 0.00 s
993 1010
994 1011 In [6]: %time 3**999999;
995 1012 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
996 1013 Wall time: 0.00 s
997 1014 Compiler : 0.78 s
998 1015 """
999 1016
1000 1017 # fail immediately if the given expression can't be compiled
1001 1018
1002 1019 if line and cell:
1003 1020 raise UsageError("Can't use statement directly after '%%time'!")
1004 1021
1005 1022 if cell:
1006 1023 expr = self.shell.input_transformer_manager.transform_cell(cell)
1007 1024 else:
1008 1025 expr = self.shell.input_transformer_manager.transform_cell(line)
1009 1026
1010 1027 # Minimum time above which parse time will be reported
1011 1028 tp_min = 0.1
1012 1029
1013 1030 t0 = clock()
1014 1031 expr_ast = ast.parse(expr)
1015 1032 tp = clock()-t0
1016 1033
1017 1034 # Apply AST transformations
1018 1035 expr_ast = self.shell.transform_ast(expr_ast)
1019 1036
1020 1037 # Minimum time above which compilation time will be reported
1021 1038 tc_min = 0.1
1022 1039
1023 1040 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1024 1041 mode = 'eval'
1025 1042 source = '<timed eval>'
1026 1043 expr_ast = ast.Expression(expr_ast.body[0].value)
1027 1044 else:
1028 1045 mode = 'exec'
1029 1046 source = '<timed exec>'
1030 1047 t0 = clock()
1031 1048 code = compile(expr_ast, source, mode)
1032 1049 tc = clock()-t0
1033 1050
1034 1051 # skew measurement as little as possible
1035 1052 glob = self.shell.user_ns
1036 1053 wtime = time.time
1037 1054 # time execution
1038 1055 wall_st = wtime()
1039 1056 if mode=='eval':
1040 1057 st = clock2()
1041 1058 out = eval(code, glob, local_ns)
1042 1059 end = clock2()
1043 1060 else:
1044 1061 st = clock2()
1045 1062 exec code in glob, local_ns
1046 1063 end = clock2()
1047 1064 out = None
1048 1065 wall_end = wtime()
1049 1066 # Compute actual times and report
1050 1067 wall_time = wall_end-wall_st
1051 1068 cpu_user = end[0]-st[0]
1052 1069 cpu_sys = end[1]-st[1]
1053 1070 cpu_tot = cpu_user+cpu_sys
1054 1071 # On windows cpu_sys is always zero, so no new information to the next print
1055 1072 if sys.platform != 'win32':
1056 1073 print "CPU times: user %s, sys: %s, total: %s" % \
1057 1074 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
1058 1075 print "Wall time: %s" % _format_time(wall_time)
1059 1076 if tc > tc_min:
1060 1077 print "Compiler : %s" % _format_time(tc)
1061 1078 if tp > tp_min:
1062 1079 print "Parser : %s" % _format_time(tp)
1063 1080 return out
1064 1081
1065 1082 @skip_doctest
1066 1083 @line_magic
1067 1084 def macro(self, parameter_s=''):
1068 1085 """Define a macro for future re-execution. It accepts ranges of history,
1069 1086 filenames or string objects.
1070 1087
1071 1088 Usage:\\
1072 1089 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1073 1090
1074 1091 Options:
1075 1092
1076 1093 -r: use 'raw' input. By default, the 'processed' history is used,
1077 1094 so that magics are loaded in their transformed version to valid
1078 1095 Python. If this option is given, the raw input as typed at the
1079 1096 command line is used instead.
1080 1097
1081 1098 -q: quiet macro definition. By default, a tag line is printed
1082 1099 to indicate the macro has been created, and then the contents of
1083 1100 the macro are printed. If this option is given, then no printout
1084 1101 is produced once the macro is created.
1085 1102
1086 1103 This will define a global variable called `name` which is a string
1087 1104 made of joining the slices and lines you specify (n1,n2,... numbers
1088 1105 above) from your input history into a single string. This variable
1089 1106 acts like an automatic function which re-executes those lines as if
1090 1107 you had typed them. You just type 'name' at the prompt and the code
1091 1108 executes.
1092 1109
1093 1110 The syntax for indicating input ranges is described in %history.
1094 1111
1095 1112 Note: as a 'hidden' feature, you can also use traditional python slice
1096 1113 notation, where N:M means numbers N through M-1.
1097 1114
1098 1115 For example, if your history contains (print using %hist -n )::
1099 1116
1100 1117 44: x=1
1101 1118 45: y=3
1102 1119 46: z=x+y
1103 1120 47: print x
1104 1121 48: a=5
1105 1122 49: print 'x',x,'y',y
1106 1123
1107 1124 you can create a macro with lines 44 through 47 (included) and line 49
1108 1125 called my_macro with::
1109 1126
1110 1127 In [55]: %macro my_macro 44-47 49
1111 1128
1112 1129 Now, typing `my_macro` (without quotes) will re-execute all this code
1113 1130 in one pass.
1114 1131
1115 1132 You don't need to give the line-numbers in order, and any given line
1116 1133 number can appear multiple times. You can assemble macros with any
1117 1134 lines from your input history in any order.
1118 1135
1119 1136 The macro is a simple object which holds its value in an attribute,
1120 1137 but IPython's display system checks for macros and executes them as
1121 1138 code instead of printing them when you type their name.
1122 1139
1123 1140 You can view a macro's contents by explicitly printing it with::
1124 1141
1125 1142 print macro_name
1126 1143
1127 1144 """
1128 1145 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1129 1146 if not args: # List existing macros
1130 1147 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1131 1148 isinstance(v, Macro))
1132 1149 if len(args) == 1:
1133 1150 raise UsageError(
1134 1151 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1135 1152 name, codefrom = args[0], " ".join(args[1:])
1136 1153
1137 1154 #print 'rng',ranges # dbg
1138 1155 try:
1139 1156 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1140 1157 except (ValueError, TypeError) as e:
1141 1158 print e.args[0]
1142 1159 return
1143 1160 macro = Macro(lines)
1144 1161 self.shell.define_macro(name, macro)
1145 1162 if not ( 'q' in opts) :
1146 1163 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1147 1164 print '=== Macro contents: ==='
1148 1165 print macro,
1149 1166
1150 1167 @magic_arguments.magic_arguments()
1151 1168 @magic_arguments.argument('output', type=str, default='', nargs='?',
1152 1169 help="""The name of the variable in which to store output.
1153 1170 This is a utils.io.CapturedIO object with stdout/err attributes
1154 1171 for the text of the captured output.
1155 1172
1156 1173 CapturedOutput also has a show() method for displaying the output,
1157 1174 and __call__ as well, so you can use that to quickly display the
1158 1175 output.
1159 1176
1160 1177 If unspecified, captured output is discarded.
1161 1178 """
1162 1179 )
1163 1180 @magic_arguments.argument('--no-stderr', action="store_true",
1164 1181 help="""Don't capture stderr."""
1165 1182 )
1166 1183 @magic_arguments.argument('--no-stdout', action="store_true",
1167 1184 help="""Don't capture stdout."""
1168 1185 )
1169 1186 @magic_arguments.argument('--no-display', action="store_true",
1170 1187 help="""Don't capture IPython's rich display."""
1171 1188 )
1172 1189 @cell_magic
1173 1190 def capture(self, line, cell):
1174 1191 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1175 1192 args = magic_arguments.parse_argstring(self.capture, line)
1176 1193 out = not args.no_stdout
1177 1194 err = not args.no_stderr
1178 1195 disp = not args.no_display
1179 1196 with capture_output(out, err, disp) as io:
1180 1197 self.shell.run_cell(cell)
1181 1198 if args.output:
1182 1199 self.shell.user_ns[args.output] = io
1183 1200
1184 1201 def parse_breakpoint(text, current_file):
1185 1202 '''Returns (file, line) for file:line and (current_file, line) for line'''
1186 1203 colon = text.find(':')
1187 1204 if colon == -1:
1188 1205 return current_file, int(text)
1189 1206 else:
1190 1207 return text[:colon], int(text[colon+1:])
1191 1208
1192 1209 def _format_time(timespan, precision=3):
1193 1210 """Formats the timespan in a human readable form"""
1194 1211 import math
1195 1212
1196 1213 if timespan >= 60.0:
1197 1214 # we have more than a minute, format that in a human readable form
1198 1215 # Idea from http://snipplr.com/view/5713/
1199 1216 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1200 1217 time = []
1201 1218 leftover = timespan
1202 1219 for suffix, length in parts:
1203 1220 value = int(leftover / length)
1204 1221 if value > 0:
1205 1222 leftover = leftover % length
1206 1223 time.append(u'%s%s' % (str(value), suffix))
1207 1224 if leftover < 1:
1208 1225 break
1209 1226 return " ".join(time)
1210 1227
1211 1228
1212 1229 # Unfortunately the unicode 'micro' symbol can cause problems in
1213 1230 # certain terminals.
1214 1231 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1215 1232 # Try to prevent crashes by being more secure than it needs to
1216 1233 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1217 1234 units = [u"s", u"ms",u'us',"ns"] # the save value
1218 1235 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1219 1236 try:
1220 1237 u'\xb5'.encode(sys.stdout.encoding)
1221 1238 units = [u"s", u"ms",u'\xb5s',"ns"]
1222 1239 except:
1223 1240 pass
1224 1241 scaling = [1, 1e3, 1e6, 1e9]
1225 1242
1226 1243 if timespan > 0.0:
1227 1244 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1228 1245 else:
1229 1246 order = 3
1230 1247 ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1231 1248 return ret
@@ -1,170 +1,184 b''
1 1 """Implementation of magic functions for IPython's own logging.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import os
17 17 import sys
18 18
19 19 # Our own packages
20 20 from IPython.core.magic import Magics, magics_class, line_magic
21 21 from IPython.utils.warn import warn
22 22 from IPython.utils.py3compat import str_to_unicode
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Magic implementation classes
26 26 #-----------------------------------------------------------------------------
27 27
28 28 @magics_class
29 29 class LoggingMagics(Magics):
30 30 """Magics related to all logging machinery."""
31 31
32 32 @line_magic
33 33 def logstart(self, parameter_s=''):
34 34 """Start logging anywhere in a session.
35 35
36 36 %logstart [-o|-r|-t] [log_name [log_mode]]
37 37
38 38 If no name is given, it defaults to a file named 'ipython_log.py' in your
39 39 current directory, in 'rotate' mode (see below).
40 40
41 41 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
42 42 history up to that point and then continues logging.
43 43
44 44 %logstart takes a second optional parameter: logging mode. This can be one
45 of (note that the modes are given unquoted):\\
46 append: well, that says it.\\
47 backup: rename (if exists) to name~ and start name.\\
48 global: single logfile in your home dir, appended to.\\
49 over : overwrite existing log.\\
50 rotate: create rotating logs name.1~, name.2~, etc.
45 of (note that the modes are given unquoted):
46
47 append
48 Keep logging at the end of any existing file.
49
50 backup
51 Rename any existing file to name~ and start name.
52
53 global
54 Append to a single logfile in your home directory.
55
56 over
57 Overwrite any existing log.
58
59 rotate
60 Create rotating logs: name.1~, name.2~, etc.
51 61
52 62 Options:
53 63
54 -o: log also IPython's output. In this mode, all commands which
55 generate an Out[NN] prompt are recorded to the logfile, right after
56 their corresponding input line. The output lines are always
57 prepended with a '#[Out]# ' marker, so that the log remains valid
58 Python code.
64 -o
65 log also IPython's output. In this mode, all commands which
66 generate an Out[NN] prompt are recorded to the logfile, right after
67 their corresponding input line. The output lines are always
68 prepended with a '#[Out]# ' marker, so that the log remains valid
69 Python code.
59 70
60 71 Since this marker is always the same, filtering only the output from
61 72 a log is very easy, using for example a simple awk call::
62 73
63 74 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
64 75
65 -r: log 'raw' input. Normally, IPython's logs contain the processed
66 input, so that user lines are logged in their final form, converted
67 into valid Python. For example, %Exit is logged as
68 _ip.magic("Exit"). If the -r flag is given, all input is logged
69 exactly as typed, with no transformations applied.
70
71 -t: put timestamps before each input line logged (these are put in
72 comments)."""
76 -r
77 log 'raw' input. Normally, IPython's logs contain the processed
78 input, so that user lines are logged in their final form, converted
79 into valid Python. For example, %Exit is logged as
80 _ip.magic("Exit"). If the -r flag is given, all input is logged
81 exactly as typed, with no transformations applied.
82
83 -t
84 put timestamps before each input line logged (these are put in
85 comments).
86 """
73 87
74 88 opts,par = self.parse_options(parameter_s,'ort')
75 89 log_output = 'o' in opts
76 90 log_raw_input = 'r' in opts
77 91 timestamp = 't' in opts
78 92
79 93 logger = self.shell.logger
80 94
81 95 # if no args are given, the defaults set in the logger constructor by
82 96 # ipython remain valid
83 97 if par:
84 98 try:
85 99 logfname,logmode = par.split()
86 100 except:
87 101 logfname = par
88 102 logmode = 'backup'
89 103 else:
90 104 logfname = logger.logfname
91 105 logmode = logger.logmode
92 106 # put logfname into rc struct as if it had been called on the command
93 107 # line, so it ends up saved in the log header Save it in case we need
94 108 # to restore it...
95 109 old_logfile = self.shell.logfile
96 110 if logfname:
97 111 logfname = os.path.expanduser(logfname)
98 112 self.shell.logfile = logfname
99 113
100 114 loghead = u'# IPython log file\n\n'
101 115 try:
102 116 logger.logstart(logfname, loghead, logmode, log_output, timestamp,
103 117 log_raw_input)
104 118 except:
105 119 self.shell.logfile = old_logfile
106 120 warn("Couldn't start log: %s" % sys.exc_info()[1])
107 121 else:
108 122 # log input history up to this point, optionally interleaving
109 123 # output if requested
110 124
111 125 if timestamp:
112 126 # disable timestamping for the previous history, since we've
113 127 # lost those already (no time machine here).
114 128 logger.timestamp = False
115 129
116 130 if log_raw_input:
117 131 input_hist = self.shell.history_manager.input_hist_raw
118 132 else:
119 133 input_hist = self.shell.history_manager.input_hist_parsed
120 134
121 135 if log_output:
122 136 log_write = logger.log_write
123 137 output_hist = self.shell.history_manager.output_hist
124 138 for n in range(1,len(input_hist)-1):
125 139 log_write(input_hist[n].rstrip() + u'\n')
126 140 if n in output_hist:
127 141 log_write(str_to_unicode(repr(output_hist[n])),'output')
128 142 else:
129 143 logger.log_write(u'\n'.join(input_hist[1:]))
130 144 logger.log_write(u'\n')
131 145 if timestamp:
132 146 # re-enable timestamping
133 147 logger.timestamp = True
134 148
135 149 print ('Activating auto-logging. '
136 150 'Current session state plus future input saved.')
137 151 logger.logstate()
138 152
139 153 @line_magic
140 154 def logstop(self, parameter_s=''):
141 155 """Fully stop logging and close log file.
142 156
143 157 In order to start logging again, a new %logstart call needs to be made,
144 158 possibly (though not necessarily) with a new filename, mode and other
145 159 options."""
146 160 self.shell.logger.logstop()
147 161
148 162 @line_magic
149 163 def logoff(self, parameter_s=''):
150 164 """Temporarily stop logging.
151 165
152 166 You must have previously started logging."""
153 167 self.shell.logger.switch_log(0)
154 168
155 169 @line_magic
156 170 def logon(self, parameter_s=''):
157 171 """Restart logging.
158 172
159 173 This function is for restarting logging which you've temporarily
160 174 stopped with %logoff. For starting logging for the first time, you
161 175 must use the %logstart function, which allows you to specify an
162 176 optional log filename."""
163 177
164 178 self.shell.logger.switch_log(1)
165 179
166 180 @line_magic
167 181 def logstate(self, parameter_s=''):
168 182 """Print the status of the logging system."""
169 183
170 184 self.shell.logger.logstate()
@@ -1,704 +1,704 b''
1 1 """Implementation of namespace-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import gc
17 17 import re
18 18 import sys
19 19
20 20 # Our own packages
21 21 from IPython.core import page
22 22 from IPython.core.error import StdinNotImplementedError, UsageError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.testing.skipdoctest import skip_doctest
25 25 from IPython.utils.encoding import DEFAULT_ENCODING
26 26 from IPython.utils.openpy import read_py_file
27 27 from IPython.utils.path import get_py_filename
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Magic implementation classes
31 31 #-----------------------------------------------------------------------------
32 32
33 33 @magics_class
34 34 class NamespaceMagics(Magics):
35 35 """Magics to manage various aspects of the user's namespace.
36 36
37 37 These include listing variables, introspecting into them, etc.
38 38 """
39 39
40 40 @line_magic
41 41 def pinfo(self, parameter_s='', namespaces=None):
42 42 """Provide detailed information about an object.
43 43
44 44 '%pinfo object' is just a synonym for object? or ?object."""
45 45
46 46 #print 'pinfo par: <%s>' % parameter_s # dbg
47 47 # detail_level: 0 -> obj? , 1 -> obj??
48 48 detail_level = 0
49 49 # We need to detect if we got called as 'pinfo pinfo foo', which can
50 50 # happen if the user types 'pinfo foo?' at the cmd line.
51 51 pinfo,qmark1,oname,qmark2 = \
52 52 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
53 53 if pinfo or qmark1 or qmark2:
54 54 detail_level = 1
55 55 if "*" in oname:
56 56 self.psearch(oname)
57 57 else:
58 58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
59 59 namespaces=namespaces)
60 60
61 61 @line_magic
62 62 def pinfo2(self, parameter_s='', namespaces=None):
63 63 """Provide extra detailed information about an object.
64 64
65 65 '%pinfo2 object' is just a synonym for object?? or ??object."""
66 66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
67 67 namespaces=namespaces)
68 68
69 69 @skip_doctest
70 70 @line_magic
71 71 def pdef(self, parameter_s='', namespaces=None):
72 72 """Print the call signature for any callable object.
73 73
74 74 If the object is a class, print the constructor information.
75 75
76 76 Examples
77 77 --------
78 78 ::
79 79
80 80 In [3]: %pdef urllib.urlopen
81 81 urllib.urlopen(url, data=None, proxies=None)
82 82 """
83 83 self.shell._inspect('pdef',parameter_s, namespaces)
84 84
85 85 @line_magic
86 86 def pdoc(self, parameter_s='', namespaces=None):
87 87 """Print the docstring for an object.
88 88
89 89 If the given object is a class, it will print both the class and the
90 90 constructor docstrings."""
91 91 self.shell._inspect('pdoc',parameter_s, namespaces)
92 92
93 93 @line_magic
94 94 def psource(self, parameter_s='', namespaces=None):
95 95 """Print (or run through pager) the source code for an object."""
96 96 if not parameter_s:
97 97 raise UsageError('Missing object name.')
98 98 self.shell._inspect('psource',parameter_s, namespaces)
99 99
100 100 @line_magic
101 101 def pfile(self, parameter_s='', namespaces=None):
102 102 """Print (or run through pager) the file where an object is defined.
103 103
104 104 The file opens at the line where the object definition begins. IPython
105 105 will honor the environment variable PAGER if set, and otherwise will
106 106 do its best to print the file in a convenient form.
107 107
108 108 If the given argument is not an object currently defined, IPython will
109 109 try to interpret it as a filename (automatically adding a .py extension
110 110 if needed). You can thus use %pfile as a syntax highlighting code
111 111 viewer."""
112 112
113 113 # first interpret argument as an object name
114 114 out = self.shell._inspect('pfile',parameter_s, namespaces)
115 115 # if not, try the input as a filename
116 116 if out == 'not found':
117 117 try:
118 118 filename = get_py_filename(parameter_s)
119 119 except IOError as msg:
120 120 print msg
121 121 return
122 122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123 123
124 124 @line_magic
125 125 def psearch(self, parameter_s=''):
126 126 """Search for object in namespaces by wildcard.
127 127
128 128 %psearch [options] PATTERN [OBJECT TYPE]
129 129
130 130 Note: ? can be used as a synonym for %psearch, at the beginning or at
131 131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
132 132 rest of the command line must be unchanged (options come first), so
133 133 for example the following forms are equivalent
134 134
135 135 %psearch -i a* function
136 136 -i a* function?
137 137 ?-i a* function
138 138
139 139 Arguments:
140 140
141 141 PATTERN
142 142
143 143 where PATTERN is a string containing * as a wildcard similar to its
144 144 use in a shell. The pattern is matched in all namespaces on the
145 145 search path. By default objects starting with a single _ are not
146 146 matched, many IPython generated objects have a single
147 147 underscore. The default is case insensitive matching. Matching is
148 148 also done on the attributes of objects and not only on the objects
149 149 in a module.
150 150
151 151 [OBJECT TYPE]
152 152
153 153 Is the name of a python type from the types module. The name is
154 154 given in lowercase without the ending type, ex. StringType is
155 155 written string. By adding a type here only objects matching the
156 156 given type are matched. Using all here makes the pattern match all
157 157 types (this is the default).
158 158
159 159 Options:
160 160
161 161 -a: makes the pattern match even objects whose names start with a
162 162 single underscore. These names are normally omitted from the
163 163 search.
164 164
165 165 -i/-c: make the pattern case insensitive/sensitive. If neither of
166 166 these options are given, the default is read from your configuration
167 167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
168 168 If this option is not specified in your configuration file, IPython's
169 169 internal default is to do a case sensitive search.
170 170
171 171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
172 172 specify can be searched in any of the following namespaces:
173 173 'builtin', 'user', 'user_global','internal', 'alias', where
174 174 'builtin' and 'user' are the search defaults. Note that you should
175 175 not use quotes when specifying namespaces.
176 176
177 177 'Builtin' contains the python module builtin, 'user' contains all
178 178 user data, 'alias' only contain the shell aliases and no python
179 179 objects, 'internal' contains objects used by IPython. The
180 180 'user_global' namespace is only used by embedded IPython instances,
181 181 and it contains module-level globals. You can add namespaces to the
182 182 search with -s or exclude them with -e (these options can be given
183 183 more than once).
184 184
185 185 Examples
186 186 --------
187 187 ::
188 188
189 189 %psearch a* -> objects beginning with an a
190 190 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
191 191 %psearch a* function -> all functions beginning with an a
192 192 %psearch re.e* -> objects beginning with an e in module re
193 193 %psearch r*.e* -> objects that start with e in modules starting in r
194 194 %psearch r*.* string -> all strings in modules beginning with r
195 195
196 196 Case sensitive search::
197 197
198 198 %psearch -c a* list all object beginning with lower case a
199 199
200 200 Show objects beginning with a single _::
201 201
202 202 %psearch -a _* list objects beginning with a single underscore
203 203 """
204 204 try:
205 205 parameter_s.encode('ascii')
206 206 except UnicodeEncodeError:
207 207 print 'Python identifiers can only contain ascii characters.'
208 208 return
209 209
210 210 # default namespaces to be searched
211 211 def_search = ['user_local', 'user_global', 'builtin']
212 212
213 213 # Process options/args
214 214 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
215 215 opt = opts.get
216 216 shell = self.shell
217 217 psearch = shell.inspector.psearch
218 218
219 219 # select case options
220 220 if 'i' in opts:
221 221 ignore_case = True
222 222 elif 'c' in opts:
223 223 ignore_case = False
224 224 else:
225 225 ignore_case = not shell.wildcards_case_sensitive
226 226
227 227 # Build list of namespaces to search from user options
228 228 def_search.extend(opt('s',[]))
229 229 ns_exclude = ns_exclude=opt('e',[])
230 230 ns_search = [nm for nm in def_search if nm not in ns_exclude]
231 231
232 232 # Call the actual search
233 233 try:
234 234 psearch(args,shell.ns_table,ns_search,
235 235 show_all=opt('a'),ignore_case=ignore_case)
236 236 except:
237 237 shell.showtraceback()
238 238
239 239 @skip_doctest
240 240 @line_magic
241 241 def who_ls(self, parameter_s=''):
242 242 """Return a sorted list of all interactive variables.
243 243
244 244 If arguments are given, only variables of types matching these
245 245 arguments are returned.
246 246
247 247 Examples
248 248 --------
249 249
250 250 Define two variables and list them with who_ls::
251 251
252 252 In [1]: alpha = 123
253 253
254 254 In [2]: beta = 'test'
255 255
256 256 In [3]: %who_ls
257 257 Out[3]: ['alpha', 'beta']
258 258
259 259 In [4]: %who_ls int
260 260 Out[4]: ['alpha']
261 261
262 262 In [5]: %who_ls str
263 263 Out[5]: ['beta']
264 264 """
265 265
266 266 user_ns = self.shell.user_ns
267 267 user_ns_hidden = self.shell.user_ns_hidden
268 268 nonmatching = object() # This can never be in user_ns
269 269 out = [ i for i in user_ns
270 270 if not i.startswith('_') \
271 271 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
272 272
273 273 typelist = parameter_s.split()
274 274 if typelist:
275 275 typeset = set(typelist)
276 276 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
277 277
278 278 out.sort()
279 279 return out
280 280
281 281 @skip_doctest
282 282 @line_magic
283 283 def who(self, parameter_s=''):
284 284 """Print all interactive variables, with some minimal formatting.
285 285
286 286 If any arguments are given, only variables whose type matches one of
287 287 these are printed. For example::
288 288
289 289 %who function str
290 290
291 291 will only list functions and strings, excluding all other types of
292 292 variables. To find the proper type names, simply use type(var) at a
293 293 command line to see how python prints type names. For example:
294 294
295 295 ::
296 296
297 297 In [1]: type('hello')\\
298 298 Out[1]: <type 'str'>
299 299
300 300 indicates that the type name for strings is 'str'.
301 301
302 302 ``%who`` always excludes executed names loaded through your configuration
303 303 file and things which are internal to IPython.
304 304
305 305 This is deliberate, as typically you may load many modules and the
306 306 purpose of %who is to show you only what you've manually defined.
307 307
308 308 Examples
309 309 --------
310 310
311 311 Define two variables and list them with who::
312 312
313 313 In [1]: alpha = 123
314 314
315 315 In [2]: beta = 'test'
316 316
317 317 In [3]: %who
318 318 alpha beta
319 319
320 320 In [4]: %who int
321 321 alpha
322 322
323 323 In [5]: %who str
324 324 beta
325 325 """
326 326
327 327 varlist = self.who_ls(parameter_s)
328 328 if not varlist:
329 329 if parameter_s:
330 330 print 'No variables match your requested type.'
331 331 else:
332 332 print 'Interactive namespace is empty.'
333 333 return
334 334
335 335 # if we have variables, move on...
336 336 count = 0
337 337 for i in varlist:
338 338 print i+'\t',
339 339 count += 1
340 340 if count > 8:
341 341 count = 0
342 342 print
343 343 print
344 344
345 345 @skip_doctest
346 346 @line_magic
347 347 def whos(self, parameter_s=''):
348 348 """Like %who, but gives some extra information about each variable.
349 349
350 350 The same type filtering of %who can be applied here.
351 351
352 352 For all variables, the type is printed. Additionally it prints:
353 353
354 354 - For {},[],(): their length.
355 355
356 356 - For numpy arrays, a summary with shape, number of
357 elements, typecode and size in memory.
357 elements, typecode and size in memory.
358 358
359 359 - Everything else: a string representation, snipping their middle if
360 too long.
360 too long.
361 361
362 362 Examples
363 363 --------
364 364
365 365 Define two variables and list them with whos::
366 366
367 367 In [1]: alpha = 123
368 368
369 369 In [2]: beta = 'test'
370 370
371 371 In [3]: %whos
372 372 Variable Type Data/Info
373 373 --------------------------------
374 374 alpha int 123
375 375 beta str test
376 376 """
377 377
378 378 varnames = self.who_ls(parameter_s)
379 379 if not varnames:
380 380 if parameter_s:
381 381 print 'No variables match your requested type.'
382 382 else:
383 383 print 'Interactive namespace is empty.'
384 384 return
385 385
386 386 # if we have variables, move on...
387 387
388 388 # for these types, show len() instead of data:
389 389 seq_types = ['dict', 'list', 'tuple']
390 390
391 391 # for numpy arrays, display summary info
392 392 ndarray_type = None
393 393 if 'numpy' in sys.modules:
394 394 try:
395 395 from numpy import ndarray
396 396 except ImportError:
397 397 pass
398 398 else:
399 399 ndarray_type = ndarray.__name__
400 400
401 401 # Find all variable names and types so we can figure out column sizes
402 402 def get_vars(i):
403 403 return self.shell.user_ns[i]
404 404
405 405 # some types are well known and can be shorter
406 406 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
407 407 def type_name(v):
408 408 tn = type(v).__name__
409 409 return abbrevs.get(tn,tn)
410 410
411 411 varlist = map(get_vars,varnames)
412 412
413 413 typelist = []
414 414 for vv in varlist:
415 415 tt = type_name(vv)
416 416
417 417 if tt=='instance':
418 418 typelist.append( abbrevs.get(str(vv.__class__),
419 419 str(vv.__class__)))
420 420 else:
421 421 typelist.append(tt)
422 422
423 423 # column labels and # of spaces as separator
424 424 varlabel = 'Variable'
425 425 typelabel = 'Type'
426 426 datalabel = 'Data/Info'
427 427 colsep = 3
428 428 # variable format strings
429 429 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
430 430 aformat = "%s: %s elems, type `%s`, %s bytes"
431 431 # find the size of the columns to format the output nicely
432 432 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
433 433 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
434 434 # table header
435 435 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
436 436 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
437 437 # and the table itself
438 438 kb = 1024
439 439 Mb = 1048576 # kb**2
440 440 for vname,var,vtype in zip(varnames,varlist,typelist):
441 441 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
442 442 if vtype in seq_types:
443 443 print "n="+str(len(var))
444 444 elif vtype == ndarray_type:
445 445 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
446 446 if vtype==ndarray_type:
447 447 # numpy
448 448 vsize = var.size
449 449 vbytes = vsize*var.itemsize
450 450 vdtype = var.dtype
451 451
452 452 if vbytes < 100000:
453 453 print aformat % (vshape, vsize, vdtype, vbytes)
454 454 else:
455 455 print aformat % (vshape, vsize, vdtype, vbytes),
456 456 if vbytes < Mb:
457 457 print '(%s kb)' % (vbytes/kb,)
458 458 else:
459 459 print '(%s Mb)' % (vbytes/Mb,)
460 460 else:
461 461 try:
462 462 vstr = str(var)
463 463 except UnicodeEncodeError:
464 464 vstr = unicode(var).encode(DEFAULT_ENCODING,
465 465 'backslashreplace')
466 466 except:
467 467 vstr = "<object with id %d (str() failed)>" % id(var)
468 468 vstr = vstr.replace('\n', '\\n')
469 469 if len(vstr) < 50:
470 470 print vstr
471 471 else:
472 472 print vstr[:25] + "<...>" + vstr[-25:]
473 473
474 474 @line_magic
475 475 def reset(self, parameter_s=''):
476 476 """Resets the namespace by removing all names defined by the user, if
477 477 called without arguments, or by removing some types of objects, such
478 478 as everything currently in IPython's In[] and Out[] containers (see
479 479 the parameters for details).
480 480
481 481 Parameters
482 482 ----------
483 483 -f : force reset without asking for confirmation.
484 484
485 485 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
486 486 References to objects may be kept. By default (without this option),
487 487 we do a 'hard' reset, giving you a new session and removing all
488 488 references to objects from the current session.
489 489
490 490 in : reset input history
491 491
492 492 out : reset output history
493 493
494 494 dhist : reset directory history
495 495
496 496 array : reset only variables that are NumPy arrays
497 497
498 498 See Also
499 499 --------
500 500 magic_reset_selective : invoked as ``%reset_selective``
501 501
502 502 Examples
503 503 --------
504 504 ::
505 505
506 506 In [6]: a = 1
507 507
508 508 In [7]: a
509 509 Out[7]: 1
510 510
511 511 In [8]: 'a' in _ip.user_ns
512 512 Out[8]: True
513 513
514 514 In [9]: %reset -f
515 515
516 516 In [1]: 'a' in _ip.user_ns
517 517 Out[1]: False
518 518
519 519 In [2]: %reset -f in
520 520 Flushing input history
521 521
522 522 In [3]: %reset -f dhist in
523 523 Flushing directory history
524 524 Flushing input history
525 525
526 526 Notes
527 527 -----
528 528 Calling this magic from clients that do not implement standard input,
529 529 such as the ipython notebook interface, will reset the namespace
530 530 without confirmation.
531 531 """
532 532 opts, args = self.parse_options(parameter_s,'sf', mode='list')
533 533 if 'f' in opts:
534 534 ans = True
535 535 else:
536 536 try:
537 537 ans = self.shell.ask_yes_no(
538 538 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
539 539 default='n')
540 540 except StdinNotImplementedError:
541 541 ans = True
542 542 if not ans:
543 543 print 'Nothing done.'
544 544 return
545 545
546 546 if 's' in opts: # Soft reset
547 547 user_ns = self.shell.user_ns
548 548 for i in self.who_ls():
549 549 del(user_ns[i])
550 550 elif len(args) == 0: # Hard reset
551 551 self.shell.reset(new_session = False)
552 552
553 553 # reset in/out/dhist/array: previously extensinions/clearcmd.py
554 554 ip = self.shell
555 555 user_ns = self.shell.user_ns # local lookup, heavily used
556 556
557 557 for target in args:
558 558 target = target.lower() # make matches case insensitive
559 559 if target == 'out':
560 560 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
561 561 self.shell.displayhook.flush()
562 562
563 563 elif target == 'in':
564 564 print "Flushing input history"
565 565 pc = self.shell.displayhook.prompt_count + 1
566 566 for n in range(1, pc):
567 567 key = '_i'+repr(n)
568 568 user_ns.pop(key,None)
569 569 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
570 570 hm = ip.history_manager
571 571 # don't delete these, as %save and %macro depending on the
572 572 # length of these lists to be preserved
573 573 hm.input_hist_parsed[:] = [''] * pc
574 574 hm.input_hist_raw[:] = [''] * pc
575 575 # hm has internal machinery for _i,_ii,_iii, clear it out
576 576 hm._i = hm._ii = hm._iii = hm._i00 = u''
577 577
578 578 elif target == 'array':
579 579 # Support cleaning up numpy arrays
580 580 try:
581 581 from numpy import ndarray
582 582 # This must be done with items and not iteritems because
583 583 # we're going to modify the dict in-place.
584 584 for x,val in user_ns.items():
585 585 if isinstance(val,ndarray):
586 586 del user_ns[x]
587 587 except ImportError:
588 588 print "reset array only works if Numpy is available."
589 589
590 590 elif target == 'dhist':
591 591 print "Flushing directory history"
592 592 del user_ns['_dh'][:]
593 593
594 594 else:
595 595 print "Don't know how to reset ",
596 596 print target + ", please run `%reset?` for details"
597 597
598 598 gc.collect()
599 599
600 600 @line_magic
601 601 def reset_selective(self, parameter_s=''):
602 602 """Resets the namespace by removing names defined by the user.
603 603
604 604 Input/Output history are left around in case you need them.
605 605
606 606 %reset_selective [-f] regex
607 607
608 608 No action is taken if regex is not included
609 609
610 610 Options
611 611 -f : force reset without asking for confirmation.
612 612
613 613 See Also
614 614 --------
615 615 magic_reset : invoked as ``%reset``
616 616
617 617 Examples
618 618 --------
619 619
620 620 We first fully reset the namespace so your output looks identical to
621 621 this example for pedagogical reasons; in practice you do not need a
622 622 full reset::
623 623
624 624 In [1]: %reset -f
625 625
626 626 Now, with a clean namespace we can make a few variables and use
627 627 ``%reset_selective`` to only delete names that match our regexp::
628 628
629 629 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
630 630
631 631 In [3]: who_ls
632 632 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
633 633
634 634 In [4]: %reset_selective -f b[2-3]m
635 635
636 636 In [5]: who_ls
637 637 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
638 638
639 639 In [6]: %reset_selective -f d
640 640
641 641 In [7]: who_ls
642 642 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
643 643
644 644 In [8]: %reset_selective -f c
645 645
646 646 In [9]: who_ls
647 647 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
648 648
649 649 In [10]: %reset_selective -f b
650 650
651 651 In [11]: who_ls
652 652 Out[11]: ['a']
653 653
654 654 Notes
655 655 -----
656 656 Calling this magic from clients that do not implement standard input,
657 657 such as the ipython notebook interface, will reset the namespace
658 658 without confirmation.
659 659 """
660 660
661 661 opts, regex = self.parse_options(parameter_s,'f')
662 662
663 663 if 'f' in opts:
664 664 ans = True
665 665 else:
666 666 try:
667 667 ans = self.shell.ask_yes_no(
668 668 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
669 669 default='n')
670 670 except StdinNotImplementedError:
671 671 ans = True
672 672 if not ans:
673 673 print 'Nothing done.'
674 674 return
675 675 user_ns = self.shell.user_ns
676 676 if not regex:
677 677 print 'No regex pattern specified. Nothing done.'
678 678 return
679 679 else:
680 680 try:
681 681 m = re.compile(regex)
682 682 except TypeError:
683 683 raise TypeError('regex must be a string or compiled pattern')
684 684 for i in self.who_ls():
685 685 if m.search(i):
686 686 del(user_ns[i])
687 687
688 688 @line_magic
689 689 def xdel(self, parameter_s=''):
690 690 """Delete a variable, trying to clear it from anywhere that
691 691 IPython's machinery has references to it. By default, this uses
692 692 the identity of the named object in the user namespace to remove
693 693 references held under other names. The object is also removed
694 694 from the output history.
695 695
696 696 Options
697 697 -n : Delete the specified name from all namespaces, without
698 698 checking their identity.
699 699 """
700 700 opts, varname = self.parse_options(parameter_s,'n')
701 701 try:
702 702 self.shell.del_var(varname, ('n' in opts))
703 703 except (NameError, ValueError) as e:
704 704 print type(e).__name__ +": "+ str(e)
@@ -1,882 +1,882 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16 from __future__ import print_function
17 17
18 18 __all__ = ['Inspector','InspectColors']
19 19
20 20 # stdlib modules
21 21 import inspect
22 22 import linecache
23 23 import os
24 24 import types
25 25 import io as stdlib_io
26 26
27 27 try:
28 28 from itertools import izip_longest
29 29 except ImportError:
30 30 from itertools import zip_longest as izip_longest
31 31
32 32 # IPython's own
33 33 from IPython.core import page
34 34 from IPython.testing.skipdoctest import skip_doctest_py3
35 35 from IPython.utils import PyColorize
36 36 from IPython.utils import io
37 37 from IPython.utils import openpy
38 38 from IPython.utils import py3compat
39 39 from IPython.utils.text import indent
40 40 from IPython.utils.wildcard import list_namespace
41 41 from IPython.utils.coloransi import *
42 42 from IPython.utils.py3compat import cast_unicode
43 43
44 44 #****************************************************************************
45 45 # Builtin color schemes
46 46
47 47 Colors = TermColors # just a shorthand
48 48
49 49 # Build a few color schemes
50 50 NoColor = ColorScheme(
51 51 'NoColor',{
52 52 'header' : Colors.NoColor,
53 53 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
54 54 } )
55 55
56 56 LinuxColors = ColorScheme(
57 57 'Linux',{
58 58 'header' : Colors.LightRed,
59 59 'normal' : Colors.Normal # color off (usu. Colors.Normal)
60 60 } )
61 61
62 62 LightBGColors = ColorScheme(
63 63 'LightBG',{
64 64 'header' : Colors.Red,
65 65 'normal' : Colors.Normal # color off (usu. Colors.Normal)
66 66 } )
67 67
68 68 # Build table of color schemes (needed by the parser)
69 69 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
70 70 'Linux')
71 71
72 72 #****************************************************************************
73 73 # Auxiliary functions and objects
74 74
75 75 # See the messaging spec for the definition of all these fields. This list
76 76 # effectively defines the order of display
77 77 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
78 78 'length', 'file', 'definition', 'docstring', 'source',
79 79 'init_definition', 'class_docstring', 'init_docstring',
80 80 'call_def', 'call_docstring',
81 81 # These won't be printed but will be used to determine how to
82 82 # format the object
83 83 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
84 84 ]
85 85
86 86
87 87 def object_info(**kw):
88 88 """Make an object info dict with all fields present."""
89 89 infodict = dict(izip_longest(info_fields, [None]))
90 90 infodict.update(kw)
91 91 return infodict
92 92
93 93
94 94 def get_encoding(obj):
95 95 """Get encoding for python source file defining obj
96 96
97 97 Returns None if obj is not defined in a sourcefile.
98 98 """
99 99 ofile = find_file(obj)
100 100 # run contents of file through pager starting at line where the object
101 101 # is defined, as long as the file isn't binary and is actually on the
102 102 # filesystem.
103 103 if ofile is None:
104 104 return None
105 105 elif ofile.endswith(('.so', '.dll', '.pyd')):
106 106 return None
107 107 elif not os.path.isfile(ofile):
108 108 return None
109 109 else:
110 110 # Print only text files, not extension binaries. Note that
111 111 # getsourcelines returns lineno with 1-offset and page() uses
112 112 # 0-offset, so we must adjust.
113 113 buffer = stdlib_io.open(ofile, 'rb') # Tweaked to use io.open for Python 2
114 114 encoding, lines = openpy.detect_encoding(buffer.readline)
115 115 return encoding
116 116
117 117 def getdoc(obj):
118 118 """Stable wrapper around inspect.getdoc.
119 119
120 120 This can't crash because of attribute problems.
121 121
122 122 It also attempts to call a getdoc() method on the given object. This
123 123 allows objects which provide their docstrings via non-standard mechanisms
124 124 (like Pyro proxies) to still be inspected by ipython's ? system."""
125 125 # Allow objects to offer customized documentation via a getdoc method:
126 126 try:
127 127 ds = obj.getdoc()
128 128 except Exception:
129 129 pass
130 130 else:
131 131 # if we get extra info, we add it to the normal docstring.
132 132 if isinstance(ds, basestring):
133 133 return inspect.cleandoc(ds)
134 134
135 135 try:
136 136 docstr = inspect.getdoc(obj)
137 137 encoding = get_encoding(obj)
138 138 return py3compat.cast_unicode(docstr, encoding=encoding)
139 139 except Exception:
140 140 # Harden against an inspect failure, which can occur with
141 141 # SWIG-wrapped extensions.
142 142 raise
143 143 return None
144 144
145 145
146 146 def getsource(obj,is_binary=False):
147 147 """Wrapper around inspect.getsource.
148 148
149 149 This can be modified by other projects to provide customized source
150 150 extraction.
151 151
152 152 Inputs:
153 153
154 154 - obj: an object whose source code we will attempt to extract.
155 155
156 156 Optional inputs:
157 157
158 158 - is_binary: whether the object is known to come from a binary source.
159 This implementation will skip returning any output for binary objects, but
160 custom extractors may know how to meaningfully process them."""
159 This implementation will skip returning any output for binary objects, but
160 custom extractors may know how to meaningfully process them."""
161 161
162 162 if is_binary:
163 163 return None
164 164 else:
165 165 # get source if obj was decorated with @decorator
166 166 if hasattr(obj,"__wrapped__"):
167 167 obj = obj.__wrapped__
168 168 try:
169 169 src = inspect.getsource(obj)
170 170 except TypeError:
171 171 if hasattr(obj,'__class__'):
172 172 src = inspect.getsource(obj.__class__)
173 173 encoding = get_encoding(obj)
174 174 return cast_unicode(src, encoding=encoding)
175 175
176 176 def getargspec(obj):
177 177 """Get the names and default values of a function's arguments.
178 178
179 179 A tuple of four things is returned: (args, varargs, varkw, defaults).
180 180 'args' is a list of the argument names (it may contain nested lists).
181 181 'varargs' and 'varkw' are the names of the * and ** arguments or None.
182 182 'defaults' is an n-tuple of the default values of the last n arguments.
183 183
184 184 Modified version of inspect.getargspec from the Python Standard
185 185 Library."""
186 186
187 187 if inspect.isfunction(obj):
188 188 func_obj = obj
189 189 elif inspect.ismethod(obj):
190 190 func_obj = obj.im_func
191 191 elif hasattr(obj, '__call__'):
192 192 func_obj = obj.__call__
193 193 else:
194 194 raise TypeError('arg is not a Python function')
195 195 args, varargs, varkw = inspect.getargs(func_obj.func_code)
196 196 return args, varargs, varkw, func_obj.func_defaults
197 197
198 198
199 199 def format_argspec(argspec):
200 200 """Format argspect, convenience wrapper around inspect's.
201 201
202 202 This takes a dict instead of ordered arguments and calls
203 203 inspect.format_argspec with the arguments in the necessary order.
204 204 """
205 205 return inspect.formatargspec(argspec['args'], argspec['varargs'],
206 206 argspec['varkw'], argspec['defaults'])
207 207
208 208
209 209 def call_tip(oinfo, format_call=True):
210 210 """Extract call tip data from an oinfo dict.
211 211
212 212 Parameters
213 213 ----------
214 214 oinfo : dict
215 215
216 216 format_call : bool, optional
217 217 If True, the call line is formatted and returned as a string. If not, a
218 218 tuple of (name, argspec) is returned.
219 219
220 220 Returns
221 221 -------
222 222 call_info : None, str or (str, dict) tuple.
223 223 When format_call is True, the whole call information is formattted as a
224 224 single string. Otherwise, the object's name and its argspec dict are
225 225 returned. If no call information is available, None is returned.
226 226
227 227 docstring : str or None
228 228 The most relevant docstring for calling purposes is returned, if
229 229 available. The priority is: call docstring for callable instances, then
230 230 constructor docstring for classes, then main object's docstring otherwise
231 231 (regular functions).
232 232 """
233 233 # Get call definition
234 234 argspec = oinfo.get('argspec')
235 235 if argspec is None:
236 236 call_line = None
237 237 else:
238 238 # Callable objects will have 'self' as their first argument, prune
239 239 # it out if it's there for clarity (since users do *not* pass an
240 240 # extra first argument explicitly).
241 241 try:
242 242 has_self = argspec['args'][0] == 'self'
243 243 except (KeyError, IndexError):
244 244 pass
245 245 else:
246 246 if has_self:
247 247 argspec['args'] = argspec['args'][1:]
248 248
249 249 call_line = oinfo['name']+format_argspec(argspec)
250 250
251 251 # Now get docstring.
252 252 # The priority is: call docstring, constructor docstring, main one.
253 253 doc = oinfo.get('call_docstring')
254 254 if doc is None:
255 255 doc = oinfo.get('init_docstring')
256 256 if doc is None:
257 257 doc = oinfo.get('docstring','')
258 258
259 259 return call_line, doc
260 260
261 261 def safe_hasattr(obj, attr):
262 262 """In recent versions of Python, hasattr() only catches AttributeError.
263 263 This catches all errors.
264 264 """
265 265 try:
266 266 getattr(obj, attr)
267 267 return True
268 268 except:
269 269 return False
270 270
271 271
272 272 def find_file(obj):
273 273 """Find the absolute path to the file where an object was defined.
274 274
275 275 This is essentially a robust wrapper around `inspect.getabsfile`.
276 276
277 277 Returns None if no file can be found.
278 278
279 279 Parameters
280 280 ----------
281 281 obj : any Python object
282 282
283 283 Returns
284 284 -------
285 285 fname : str
286 286 The absolute path to the file where the object was defined.
287 287 """
288 288 # get source if obj was decorated with @decorator
289 289 if safe_hasattr(obj, '__wrapped__'):
290 290 obj = obj.__wrapped__
291 291
292 292 fname = None
293 293 try:
294 294 fname = inspect.getabsfile(obj)
295 295 except TypeError:
296 296 # For an instance, the file that matters is where its class was
297 297 # declared.
298 298 if hasattr(obj, '__class__'):
299 299 try:
300 300 fname = inspect.getabsfile(obj.__class__)
301 301 except TypeError:
302 302 # Can happen for builtins
303 303 pass
304 304 except:
305 305 pass
306 306 return cast_unicode(fname)
307 307
308 308
309 309 def find_source_lines(obj):
310 310 """Find the line number in a file where an object was defined.
311 311
312 312 This is essentially a robust wrapper around `inspect.getsourcelines`.
313 313
314 314 Returns None if no file can be found.
315 315
316 316 Parameters
317 317 ----------
318 318 obj : any Python object
319 319
320 320 Returns
321 321 -------
322 322 lineno : int
323 323 The line number where the object definition starts.
324 324 """
325 325 # get source if obj was decorated with @decorator
326 326 if safe_hasattr(obj, '__wrapped__'):
327 327 obj = obj.__wrapped__
328 328
329 329 try:
330 330 try:
331 331 lineno = inspect.getsourcelines(obj)[1]
332 332 except TypeError:
333 333 # For instances, try the class object like getsource() does
334 334 if hasattr(obj, '__class__'):
335 335 lineno = inspect.getsourcelines(obj.__class__)[1]
336 336 else:
337 337 lineno = None
338 338 except:
339 339 return None
340 340
341 341 return lineno
342 342
343 343
344 344 class Inspector:
345 345 def __init__(self, color_table=InspectColors,
346 346 code_color_table=PyColorize.ANSICodeColors,
347 347 scheme='NoColor',
348 348 str_detail_level=0):
349 349 self.color_table = color_table
350 350 self.parser = PyColorize.Parser(code_color_table,out='str')
351 351 self.format = self.parser.format
352 352 self.str_detail_level = str_detail_level
353 353 self.set_active_scheme(scheme)
354 354
355 355 def _getdef(self,obj,oname=''):
356 356 """Return the call signature for any callable object.
357 357
358 358 If any exception is generated, None is returned instead and the
359 359 exception is suppressed."""
360 360
361 361 try:
362 362 hdef = oname + inspect.formatargspec(*getargspec(obj))
363 363 return cast_unicode(hdef)
364 364 except:
365 365 return None
366 366
367 367 def __head(self,h):
368 368 """Return a header string with proper colors."""
369 369 return '%s%s%s' % (self.color_table.active_colors.header,h,
370 370 self.color_table.active_colors.normal)
371 371
372 372 def set_active_scheme(self, scheme):
373 373 self.color_table.set_active_scheme(scheme)
374 374 self.parser.color_table.set_active_scheme(scheme)
375 375
376 376 def noinfo(self, msg, oname):
377 377 """Generic message when no information is found."""
378 378 print('No %s found' % msg, end=' ')
379 379 if oname:
380 380 print('for %s' % oname)
381 381 else:
382 382 print()
383 383
384 384 def pdef(self, obj, oname=''):
385 385 """Print the call signature for any callable object.
386 386
387 387 If the object is a class, print the constructor information."""
388 388
389 389 if not callable(obj):
390 390 print('Object is not callable.')
391 391 return
392 392
393 393 header = ''
394 394
395 395 if inspect.isclass(obj):
396 396 header = self.__head('Class constructor information:\n')
397 397 obj = obj.__init__
398 398 elif (not py3compat.PY3) and type(obj) is types.InstanceType:
399 399 obj = obj.__call__
400 400
401 401 output = self._getdef(obj,oname)
402 402 if output is None:
403 403 self.noinfo('definition header',oname)
404 404 else:
405 405 print(header,self.format(output), end=' ', file=io.stdout)
406 406
407 407 # In Python 3, all classes are new-style, so they all have __init__.
408 408 @skip_doctest_py3
409 409 def pdoc(self,obj,oname='',formatter = None):
410 410 """Print the docstring for any object.
411 411
412 412 Optional:
413 413 -formatter: a function to run the docstring through for specially
414 414 formatted docstrings.
415 415
416 416 Examples
417 417 --------
418 418
419 419 In [1]: class NoInit:
420 420 ...: pass
421 421
422 422 In [2]: class NoDoc:
423 423 ...: def __init__(self):
424 424 ...: pass
425 425
426 426 In [3]: %pdoc NoDoc
427 427 No documentation found for NoDoc
428 428
429 429 In [4]: %pdoc NoInit
430 430 No documentation found for NoInit
431 431
432 432 In [5]: obj = NoInit()
433 433
434 434 In [6]: %pdoc obj
435 435 No documentation found for obj
436 436
437 437 In [5]: obj2 = NoDoc()
438 438
439 439 In [6]: %pdoc obj2
440 440 No documentation found for obj2
441 441 """
442 442
443 443 head = self.__head # For convenience
444 444 lines = []
445 445 ds = getdoc(obj)
446 446 if formatter:
447 447 ds = formatter(ds)
448 448 if ds:
449 449 lines.append(head("Class Docstring:"))
450 450 lines.append(indent(ds))
451 451 if inspect.isclass(obj) and hasattr(obj, '__init__'):
452 452 init_ds = getdoc(obj.__init__)
453 453 if init_ds is not None:
454 454 lines.append(head("Constructor Docstring:"))
455 455 lines.append(indent(init_ds))
456 456 elif hasattr(obj,'__call__'):
457 457 call_ds = getdoc(obj.__call__)
458 458 if call_ds:
459 459 lines.append(head("Calling Docstring:"))
460 460 lines.append(indent(call_ds))
461 461
462 462 if not lines:
463 463 self.noinfo('documentation',oname)
464 464 else:
465 465 page.page('\n'.join(lines))
466 466
467 467 def psource(self,obj,oname=''):
468 468 """Print the source code for an object."""
469 469
470 470 # Flush the source cache because inspect can return out-of-date source
471 471 linecache.checkcache()
472 472 try:
473 473 src = getsource(obj)
474 474 except:
475 475 self.noinfo('source',oname)
476 476 else:
477 477 page.page(self.format(src))
478 478
479 479 def pfile(self, obj, oname=''):
480 480 """Show the whole file where an object was defined."""
481 481
482 482 lineno = find_source_lines(obj)
483 483 if lineno is None:
484 484 self.noinfo('file', oname)
485 485 return
486 486
487 487 ofile = find_file(obj)
488 488 # run contents of file through pager starting at line where the object
489 489 # is defined, as long as the file isn't binary and is actually on the
490 490 # filesystem.
491 491 if ofile.endswith(('.so', '.dll', '.pyd')):
492 492 print('File %r is binary, not printing.' % ofile)
493 493 elif not os.path.isfile(ofile):
494 494 print('File %r does not exist, not printing.' % ofile)
495 495 else:
496 496 # Print only text files, not extension binaries. Note that
497 497 # getsourcelines returns lineno with 1-offset and page() uses
498 498 # 0-offset, so we must adjust.
499 499 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
500 500
501 501 def _format_fields(self, fields, title_width=12):
502 502 """Formats a list of fields for display.
503 503
504 504 Parameters
505 505 ----------
506 506 fields : list
507 507 A list of 2-tuples: (field_title, field_content)
508 508 title_width : int
509 509 How many characters to pad titles to. Default 12.
510 510 """
511 511 out = []
512 512 header = self.__head
513 513 for title, content in fields:
514 514 if len(content.splitlines()) > 1:
515 515 title = header(title + ":") + "\n"
516 516 else:
517 517 title = header((title+":").ljust(title_width))
518 518 out.append(cast_unicode(title) + cast_unicode(content))
519 519 return "\n".join(out)
520 520
521 521 # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict)
522 522 pinfo_fields1 = [("Type", "type_name"),
523 523 ]
524 524
525 525 pinfo_fields2 = [("String Form", "string_form"),
526 526 ]
527 527
528 528 pinfo_fields3 = [("Length", "length"),
529 529 ("File", "file"),
530 530 ("Definition", "definition"),
531 531 ]
532 532
533 533 pinfo_fields_obj = [("Class Docstring", "class_docstring"),
534 534 ("Constructor Docstring","init_docstring"),
535 535 ("Call def", "call_def"),
536 536 ("Call docstring", "call_docstring")]
537 537
538 538 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
539 539 """Show detailed information about an object.
540 540
541 541 Optional arguments:
542 542
543 543 - oname: name of the variable pointing to the object.
544 544
545 545 - formatter: special formatter for docstrings (see pdoc)
546 546
547 547 - info: a structure with some information fields which may have been
548 precomputed already.
548 precomputed already.
549 549
550 550 - detail_level: if set to 1, more information is given.
551 551 """
552 552 info = self.info(obj, oname=oname, formatter=formatter,
553 553 info=info, detail_level=detail_level)
554 554 displayfields = []
555 555 def add_fields(fields):
556 556 for title, key in fields:
557 557 field = info[key]
558 558 if field is not None:
559 559 displayfields.append((title, field.rstrip()))
560 560
561 561 add_fields(self.pinfo_fields1)
562 562
563 563 # Base class for old-style instances
564 564 if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
565 565 displayfields.append(("Base Class", info['base_class'].rstrip()))
566 566
567 567 add_fields(self.pinfo_fields2)
568 568
569 569 # Namespace
570 570 if info['namespace'] != 'Interactive':
571 571 displayfields.append(("Namespace", info['namespace'].rstrip()))
572 572
573 573 add_fields(self.pinfo_fields3)
574 574
575 575 # Source or docstring, depending on detail level and whether
576 576 # source found.
577 577 if detail_level > 0 and info['source'] is not None:
578 578 displayfields.append(("Source",
579 579 self.format(cast_unicode(info['source']))))
580 580 elif info['docstring'] is not None:
581 581 displayfields.append(("Docstring", info["docstring"]))
582 582
583 583 # Constructor info for classes
584 584 if info['isclass']:
585 585 if info['init_definition'] or info['init_docstring']:
586 586 displayfields.append(("Constructor information", ""))
587 587 if info['init_definition'] is not None:
588 588 displayfields.append((" Definition",
589 589 info['init_definition'].rstrip()))
590 590 if info['init_docstring'] is not None:
591 591 displayfields.append((" Docstring",
592 592 indent(info['init_docstring'])))
593 593
594 594 # Info for objects:
595 595 else:
596 596 add_fields(self.pinfo_fields_obj)
597 597
598 598 # Finally send to printer/pager:
599 599 if displayfields:
600 600 page.page(self._format_fields(displayfields))
601 601
602 602 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
603 603 """Compute a dict with detailed information about an object.
604 604
605 605 Optional arguments:
606 606
607 607 - oname: name of the variable pointing to the object.
608 608
609 609 - formatter: special formatter for docstrings (see pdoc)
610 610
611 611 - info: a structure with some information fields which may have been
612 precomputed already.
612 precomputed already.
613 613
614 614 - detail_level: if set to 1, more information is given.
615 615 """
616 616
617 617 obj_type = type(obj)
618 618
619 619 header = self.__head
620 620 if info is None:
621 621 ismagic = 0
622 622 isalias = 0
623 623 ospace = ''
624 624 else:
625 625 ismagic = info.ismagic
626 626 isalias = info.isalias
627 627 ospace = info.namespace
628 628
629 629 # Get docstring, special-casing aliases:
630 630 if isalias:
631 631 if not callable(obj):
632 632 try:
633 633 ds = "Alias to the system command:\n %s" % obj[1]
634 634 except:
635 635 ds = "Alias: " + str(obj)
636 636 else:
637 637 ds = "Alias to " + str(obj)
638 638 if obj.__doc__:
639 639 ds += "\nDocstring:\n" + obj.__doc__
640 640 else:
641 641 ds = getdoc(obj)
642 642 if ds is None:
643 643 ds = '<no docstring>'
644 644 if formatter is not None:
645 645 ds = formatter(ds)
646 646
647 647 # store output in a dict, we initialize it here and fill it as we go
648 648 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
649 649
650 650 string_max = 200 # max size of strings to show (snipped if longer)
651 651 shalf = int((string_max -5)/2)
652 652
653 653 if ismagic:
654 654 obj_type_name = 'Magic function'
655 655 elif isalias:
656 656 obj_type_name = 'System alias'
657 657 else:
658 658 obj_type_name = obj_type.__name__
659 659 out['type_name'] = obj_type_name
660 660
661 661 try:
662 662 bclass = obj.__class__
663 663 out['base_class'] = str(bclass)
664 664 except: pass
665 665
666 666 # String form, but snip if too long in ? form (full in ??)
667 667 if detail_level >= self.str_detail_level:
668 668 try:
669 669 ostr = str(obj)
670 670 str_head = 'string_form'
671 671 if not detail_level and len(ostr)>string_max:
672 672 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
673 673 ostr = ("\n" + " " * len(str_head.expandtabs())).\
674 674 join(q.strip() for q in ostr.split("\n"))
675 675 out[str_head] = ostr
676 676 except:
677 677 pass
678 678
679 679 if ospace:
680 680 out['namespace'] = ospace
681 681
682 682 # Length (for strings and lists)
683 683 try:
684 684 out['length'] = str(len(obj))
685 685 except: pass
686 686
687 687 # Filename where object was defined
688 688 binary_file = False
689 689 fname = find_file(obj)
690 690 if fname is None:
691 691 # if anything goes wrong, we don't want to show source, so it's as
692 692 # if the file was binary
693 693 binary_file = True
694 694 else:
695 695 if fname.endswith(('.so', '.dll', '.pyd')):
696 696 binary_file = True
697 697 elif fname.endswith('<string>'):
698 698 fname = 'Dynamically generated function. No source code available.'
699 699 out['file'] = fname
700 700
701 701 # reconstruct the function definition and print it:
702 702 defln = self._getdef(obj, oname)
703 703 if defln:
704 704 out['definition'] = self.format(defln)
705 705
706 706 # Docstrings only in detail 0 mode, since source contains them (we
707 707 # avoid repetitions). If source fails, we add them back, see below.
708 708 if ds and detail_level == 0:
709 709 out['docstring'] = ds
710 710
711 711 # Original source code for any callable
712 712 if detail_level:
713 713 # Flush the source cache because inspect can return out-of-date
714 714 # source
715 715 linecache.checkcache()
716 716 source = None
717 717 try:
718 718 try:
719 719 source = getsource(obj, binary_file)
720 720 except TypeError:
721 721 if hasattr(obj, '__class__'):
722 722 source = getsource(obj.__class__, binary_file)
723 723 if source is not None:
724 724 out['source'] = source.rstrip()
725 725 except Exception:
726 726 pass
727 727
728 728 if ds and source is None:
729 729 out['docstring'] = ds
730 730
731 731
732 732 # Constructor docstring for classes
733 733 if inspect.isclass(obj):
734 734 out['isclass'] = True
735 735 # reconstruct the function definition and print it:
736 736 try:
737 737 obj_init = obj.__init__
738 738 except AttributeError:
739 739 init_def = init_ds = None
740 740 else:
741 741 init_def = self._getdef(obj_init,oname)
742 742 init_ds = getdoc(obj_init)
743 743 # Skip Python's auto-generated docstrings
744 744 if init_ds and \
745 745 init_ds.startswith('x.__init__(...) initializes'):
746 746 init_ds = None
747 747
748 748 if init_def or init_ds:
749 749 if init_def:
750 750 out['init_definition'] = self.format(init_def)
751 751 if init_ds:
752 752 out['init_docstring'] = init_ds
753 753
754 754 # and class docstring for instances:
755 755 else:
756 756 # First, check whether the instance docstring is identical to the
757 757 # class one, and print it separately if they don't coincide. In
758 758 # most cases they will, but it's nice to print all the info for
759 759 # objects which use instance-customized docstrings.
760 760 if ds:
761 761 try:
762 762 cls = getattr(obj,'__class__')
763 763 except:
764 764 class_ds = None
765 765 else:
766 766 class_ds = getdoc(cls)
767 767 # Skip Python's auto-generated docstrings
768 768 if class_ds and \
769 769 (class_ds.startswith('function(code, globals[,') or \
770 770 class_ds.startswith('instancemethod(function, instance,') or \
771 771 class_ds.startswith('module(name[,') ):
772 772 class_ds = None
773 773 if class_ds and ds != class_ds:
774 774 out['class_docstring'] = class_ds
775 775
776 776 # Next, try to show constructor docstrings
777 777 try:
778 778 init_ds = getdoc(obj.__init__)
779 779 # Skip Python's auto-generated docstrings
780 780 if init_ds and \
781 781 init_ds.startswith('x.__init__(...) initializes'):
782 782 init_ds = None
783 783 except AttributeError:
784 784 init_ds = None
785 785 if init_ds:
786 786 out['init_docstring'] = init_ds
787 787
788 788 # Call form docstring for callable instances
789 789 if safe_hasattr(obj, '__call__'):
790 790 call_def = self._getdef(obj.__call__, oname)
791 791 if call_def is not None:
792 792 out['call_def'] = self.format(call_def)
793 793 call_ds = getdoc(obj.__call__)
794 794 # Skip Python's auto-generated docstrings
795 795 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
796 796 call_ds = None
797 797 if call_ds:
798 798 out['call_docstring'] = call_ds
799 799
800 800 # Compute the object's argspec as a callable. The key is to decide
801 801 # whether to pull it from the object itself, from its __init__ or
802 802 # from its __call__ method.
803 803
804 804 if inspect.isclass(obj):
805 805 # Old-style classes need not have an __init__
806 806 callable_obj = getattr(obj, "__init__", None)
807 807 elif callable(obj):
808 808 callable_obj = obj
809 809 else:
810 810 callable_obj = None
811 811
812 812 if callable_obj:
813 813 try:
814 814 args, varargs, varkw, defaults = getargspec(callable_obj)
815 815 except (TypeError, AttributeError):
816 816 # For extensions/builtins we can't retrieve the argspec
817 817 pass
818 818 else:
819 819 out['argspec'] = dict(args=args, varargs=varargs,
820 820 varkw=varkw, defaults=defaults)
821 821
822 822 return object_info(**out)
823 823
824 824
825 825 def psearch(self,pattern,ns_table,ns_search=[],
826 826 ignore_case=False,show_all=False):
827 827 """Search namespaces with wildcards for objects.
828 828
829 829 Arguments:
830 830
831 831 - pattern: string containing shell-like wildcards to use in namespace
832 searches and optionally a type specification to narrow the search to
833 objects of that type.
832 searches and optionally a type specification to narrow the search to
833 objects of that type.
834 834
835 835 - ns_table: dict of name->namespaces for search.
836 836
837 837 Optional arguments:
838 838
839 839 - ns_search: list of namespace names to include in search.
840 840
841 841 - ignore_case(False): make the search case-insensitive.
842 842
843 843 - show_all(False): show all names, including those starting with
844 underscores.
844 underscores.
845 845 """
846 846 #print 'ps pattern:<%r>' % pattern # dbg
847 847
848 848 # defaults
849 849 type_pattern = 'all'
850 850 filter = ''
851 851
852 852 cmds = pattern.split()
853 853 len_cmds = len(cmds)
854 854 if len_cmds == 1:
855 855 # Only filter pattern given
856 856 filter = cmds[0]
857 857 elif len_cmds == 2:
858 858 # Both filter and type specified
859 859 filter,type_pattern = cmds
860 860 else:
861 861 raise ValueError('invalid argument string for psearch: <%s>' %
862 862 pattern)
863 863
864 864 # filter search namespaces
865 865 for name in ns_search:
866 866 if name not in ns_table:
867 867 raise ValueError('invalid namespace <%s>. Valid names: %s' %
868 868 (name,ns_table.keys()))
869 869
870 870 #print 'type_pattern:',type_pattern # dbg
871 871 search_result, namespaces_seen = set(), set()
872 872 for ns_name in ns_search:
873 873 ns = ns_table[ns_name]
874 874 # Normally, locals and globals are the same, so we just check one.
875 875 if id(ns) in namespaces_seen:
876 876 continue
877 877 namespaces_seen.add(id(ns))
878 878 tmp_res = list_namespace(ns, type_pattern, filter,
879 879 ignore_case=ignore_case, show_all=show_all)
880 880 search_result.update(tmp_res)
881 881
882 882 page.page('\n'.join(sorted(search_result)))
@@ -1,348 +1,350 b''
1 1 # encoding: utf-8
2 2 """
3 3 Paging capabilities for IPython.core
4 4
5 5 Authors:
6 6
7 7 * Brian Granger
8 8 * Fernando Perez
9 9
10 10 Notes
11 11 -----
12 12
13 13 For now this uses ipapi, so it can't be in IPython.utils. If we can get
14 14 rid of that dependency, we could move it there.
15 15 -----
16 16 """
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Copyright (C) 2008-2011 The IPython Development Team
20 20 #
21 21 # Distributed under the terms of the BSD License. The full license is in
22 22 # the file COPYING, distributed as part of this software.
23 23 #-----------------------------------------------------------------------------
24 24
25 25 #-----------------------------------------------------------------------------
26 26 # Imports
27 27 #-----------------------------------------------------------------------------
28 28 from __future__ import print_function
29 29
30 30 import os
31 31 import re
32 32 import sys
33 33 import tempfile
34 34
35 35 from io import UnsupportedOperation
36 36
37 37 from IPython import get_ipython
38 38 from IPython.core.error import TryNext
39 39 from IPython.utils.data import chop
40 40 from IPython.utils import io
41 41 from IPython.utils.process import system
42 42 from IPython.utils.terminal import get_terminal_size
43 43 from IPython.utils import py3compat
44 44
45 45
46 46 #-----------------------------------------------------------------------------
47 47 # Classes and functions
48 48 #-----------------------------------------------------------------------------
49 49
50 50 esc_re = re.compile(r"(\x1b[^m]+m)")
51 51
52 52 def page_dumb(strng, start=0, screen_lines=25):
53 53 """Very dumb 'pager' in Python, for when nothing else works.
54 54
55 55 Only moves forward, same interface as page(), except for pager_cmd and
56 56 mode."""
57 57
58 58 out_ln = strng.splitlines()[start:]
59 59 screens = chop(out_ln,screen_lines-1)
60 60 if len(screens) == 1:
61 61 print(os.linesep.join(screens[0]), file=io.stdout)
62 62 else:
63 63 last_escape = ""
64 64 for scr in screens[0:-1]:
65 65 hunk = os.linesep.join(scr)
66 66 print(last_escape + hunk, file=io.stdout)
67 67 if not page_more():
68 68 return
69 69 esc_list = esc_re.findall(hunk)
70 70 if len(esc_list) > 0:
71 71 last_escape = esc_list[-1]
72 72 print(last_escape + os.linesep.join(screens[-1]), file=io.stdout)
73 73
74 74 def _detect_screen_size(screen_lines_def):
75 75 """Attempt to work out the number of lines on the screen.
76 76
77 77 This is called by page(). It can raise an error (e.g. when run in the
78 78 test suite), so it's separated out so it can easily be called in a try block.
79 79 """
80 80 TERM = os.environ.get('TERM',None)
81 81 if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
82 82 # curses causes problems on many terminals other than xterm, and
83 83 # some termios calls lock up on Sun OS5.
84 84 return screen_lines_def
85 85
86 86 try:
87 87 import termios
88 88 import curses
89 89 except ImportError:
90 90 return screen_lines_def
91 91
92 92 # There is a bug in curses, where *sometimes* it fails to properly
93 93 # initialize, and then after the endwin() call is made, the
94 94 # terminal is left in an unusable state. Rather than trying to
95 95 # check everytime for this (by requesting and comparing termios
96 96 # flags each time), we just save the initial terminal state and
97 97 # unconditionally reset it every time. It's cheaper than making
98 98 # the checks.
99 99 term_flags = termios.tcgetattr(sys.stdout)
100 100
101 101 # Curses modifies the stdout buffer size by default, which messes
102 102 # up Python's normal stdout buffering. This would manifest itself
103 103 # to IPython users as delayed printing on stdout after having used
104 104 # the pager.
105 105 #
106 106 # We can prevent this by manually setting the NCURSES_NO_SETBUF
107 107 # environment variable. For more details, see:
108 108 # http://bugs.python.org/issue10144
109 109 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
110 110 os.environ['NCURSES_NO_SETBUF'] = ''
111 111
112 112 # Proceed with curses initialization
113 113 try:
114 114 scr = curses.initscr()
115 115 except AttributeError:
116 116 # Curses on Solaris may not be complete, so we can't use it there
117 117 return screen_lines_def
118 118
119 119 screen_lines_real,screen_cols = scr.getmaxyx()
120 120 curses.endwin()
121 121
122 122 # Restore environment
123 123 if NCURSES_NO_SETBUF is None:
124 124 del os.environ['NCURSES_NO_SETBUF']
125 125 else:
126 126 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
127 127
128 128 # Restore terminal state in case endwin() didn't.
129 129 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
130 130 # Now we have what we needed: the screen size in rows/columns
131 131 return screen_lines_real
132 132 #print '***Screen size:',screen_lines_real,'lines x',\
133 133 #screen_cols,'columns.' # dbg
134 134
135 135 def page(strng, start=0, screen_lines=0, pager_cmd=None):
136 136 """Print a string, piping through a pager after a certain length.
137 137
138 138 The screen_lines parameter specifies the number of *usable* lines of your
139 139 terminal screen (total lines minus lines you need to reserve to show other
140 140 information).
141 141
142 142 If you set screen_lines to a number <=0, page() will try to auto-determine
143 143 your screen size and will only use up to (screen_size+screen_lines) for
144 144 printing, paging after that. That is, if you want auto-detection but need
145 145 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
146 146 auto-detection without any lines reserved simply use screen_lines = 0.
147 147
148 148 If a string won't fit in the allowed lines, it is sent through the
149 149 specified pager command. If none given, look for PAGER in the environment,
150 150 and ultimately default to less.
151 151
152 152 If no system pager works, the string is sent through a 'dumb pager'
153 153 written in python, very simplistic.
154 154 """
155 155
156 156 # Some routines may auto-compute start offsets incorrectly and pass a
157 157 # negative value. Offset to 0 for robustness.
158 158 start = max(0, start)
159 159
160 160 # first, try the hook
161 161 ip = get_ipython()
162 162 if ip:
163 163 try:
164 164 ip.hooks.show_in_pager(strng)
165 165 return
166 166 except TryNext:
167 167 pass
168 168
169 169 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
170 170 TERM = os.environ.get('TERM','dumb')
171 171 if TERM in ['dumb','emacs'] and os.name != 'nt':
172 172 print(strng)
173 173 return
174 174 # chop off the topmost part of the string we don't want to see
175 175 str_lines = strng.splitlines()[start:]
176 176 str_toprint = os.linesep.join(str_lines)
177 177 num_newlines = len(str_lines)
178 178 len_str = len(str_toprint)
179 179
180 180 # Dumb heuristics to guesstimate number of on-screen lines the string
181 181 # takes. Very basic, but good enough for docstrings in reasonable
182 182 # terminals. If someone later feels like refining it, it's not hard.
183 183 numlines = max(num_newlines,int(len_str/80)+1)
184 184
185 185 screen_lines_def = get_terminal_size()[1]
186 186
187 187 # auto-determine screen size
188 188 if screen_lines <= 0:
189 189 try:
190 190 screen_lines += _detect_screen_size(screen_lines_def)
191 191 except (TypeError, UnsupportedOperation):
192 192 print(str_toprint, file=io.stdout)
193 193 return
194 194
195 195 #print 'numlines',numlines,'screenlines',screen_lines # dbg
196 196 if numlines <= screen_lines :
197 197 #print '*** normal print' # dbg
198 198 print(str_toprint, file=io.stdout)
199 199 else:
200 200 # Try to open pager and default to internal one if that fails.
201 201 # All failure modes are tagged as 'retval=1', to match the return
202 202 # value of a failed system command. If any intermediate attempt
203 203 # sets retval to 1, at the end we resort to our own page_dumb() pager.
204 204 pager_cmd = get_pager_cmd(pager_cmd)
205 205 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
206 206 if os.name == 'nt':
207 207 if pager_cmd.startswith('type'):
208 208 # The default WinXP 'type' command is failing on complex strings.
209 209 retval = 1
210 210 else:
211 211 tmpname = tempfile.mktemp('.txt')
212 212 tmpfile = open(tmpname,'wt')
213 213 tmpfile.write(strng)
214 214 tmpfile.close()
215 215 cmd = "%s < %s" % (pager_cmd,tmpname)
216 216 if os.system(cmd):
217 217 retval = 1
218 218 else:
219 219 retval = None
220 220 os.remove(tmpname)
221 221 else:
222 222 try:
223 223 retval = None
224 224 # if I use popen4, things hang. No idea why.
225 225 #pager,shell_out = os.popen4(pager_cmd)
226 226 pager = os.popen(pager_cmd, 'w')
227 227 try:
228 228 pager_encoding = pager.encoding or sys.stdout.encoding
229 229 pager.write(py3compat.cast_bytes_py2(
230 230 strng, encoding=pager_encoding))
231 231 finally:
232 232 retval = pager.close()
233 233 except IOError as msg: # broken pipe when user quits
234 234 if msg.args == (32, 'Broken pipe'):
235 235 retval = None
236 236 else:
237 237 retval = 1
238 238 except OSError:
239 239 # Other strange problems, sometimes seen in Win2k/cygwin
240 240 retval = 1
241 241 if retval is not None:
242 242 page_dumb(strng,screen_lines=screen_lines)
243 243
244 244
245 245 def page_file(fname, start=0, pager_cmd=None):
246 246 """Page a file, using an optional pager command and starting line.
247 247 """
248 248
249 249 pager_cmd = get_pager_cmd(pager_cmd)
250 250 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
251 251
252 252 try:
253 253 if os.environ['TERM'] in ['emacs','dumb']:
254 254 raise EnvironmentError
255 255 system(pager_cmd + ' ' + fname)
256 256 except:
257 257 try:
258 258 if start > 0:
259 259 start -= 1
260 260 page(open(fname).read(),start)
261 261 except:
262 262 print('Unable to show file',repr(fname))
263 263
264 264
265 265 def get_pager_cmd(pager_cmd=None):
266 266 """Return a pager command.
267 267
268 268 Makes some attempts at finding an OS-correct one.
269 269 """
270 270 if os.name == 'posix':
271 271 default_pager_cmd = 'less -r' # -r for color control sequences
272 272 elif os.name in ['nt','dos']:
273 273 default_pager_cmd = 'type'
274 274
275 275 if pager_cmd is None:
276 276 try:
277 277 pager_cmd = os.environ['PAGER']
278 278 except:
279 279 pager_cmd = default_pager_cmd
280 280 return pager_cmd
281 281
282 282
283 283 def get_pager_start(pager, start):
284 284 """Return the string for paging files with an offset.
285 285
286 286 This is the '+N' argument which less and more (under Unix) accept.
287 287 """
288 288
289 289 if pager in ['less','more']:
290 290 if start:
291 291 start_string = '+' + str(start)
292 292 else:
293 293 start_string = ''
294 294 else:
295 295 start_string = ''
296 296 return start_string
297 297
298 298
299 299 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
300 300 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
301 301 import msvcrt
302 302 def page_more():
303 303 """ Smart pausing between pages
304 304
305 305 @return: True if need print more lines, False if quit
306 306 """
307 307 io.stdout.write('---Return to continue, q to quit--- ')
308 308 ans = msvcrt.getwch()
309 309 if ans in ("q", "Q"):
310 310 result = False
311 311 else:
312 312 result = True
313 313 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
314 314 return result
315 315 else:
316 316 def page_more():
317 317 ans = raw_input('---Return to continue, q to quit--- ')
318 318 if ans.lower().startswith('q'):
319 319 return False
320 320 else:
321 321 return True
322 322
323 323
324 324 def snip_print(str,width = 75,print_full = 0,header = ''):
325 325 """Print a string snipping the midsection to fit in width.
326 326
327 327 print_full: mode control:
328
328 329 - 0: only snip long strings
329 330 - 1: send to page() directly.
330 331 - 2: snip long strings and ask for full length viewing with page()
332
331 333 Return 1 if snipping was necessary, 0 otherwise."""
332 334
333 335 if print_full == 1:
334 336 page(header+str)
335 337 return 0
336 338
337 339 print(header, end=' ')
338 340 if len(str) < width:
339 341 print(str)
340 342 snip = 0
341 343 else:
342 344 whalf = int((width -5)/2)
343 345 print(str[:whalf] + ' <...> ' + str[-whalf:])
344 346 snip = 1
345 347 if snip and print_full == 2:
346 348 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
347 349 page(str)
348 350 return snip
@@ -1,1247 +1,1251 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultratb.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB::
12
12 13 import sys,ultratb
13 14 sys.excepthook = ultratb.ColorTB()
14 15
15 16 * VerboseTB
16 17 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 18 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 19 and intended it for CGI programmers, but why should they have all the fun? I
19 20 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 21 but kind of neat, and maybe useful for long-running programs that you believe
21 22 are bug-free. If a crash *does* occur in that type of program you want details.
22 23 Give it a shot--you'll love it or you'll hate it.
23 24
24 Note:
25 .. note::
25 26
26 27 The Verbose mode prints the variables currently visible where the exception
27 28 happened (shortening their strings if too long). This can potentially be
28 29 very slow, if you happen to have a huge data structure whose string
29 30 representation is complex to compute. Your computer may appear to freeze for
30 31 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 32 with Ctrl-C (maybe hitting it more than once).
32 33
33 34 If you encounter this kind of situation often, you may want to use the
34 35 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 36 variables (but otherwise includes the information and context given by
36 37 Verbose).
37 38
38 39
39 Installation instructions for ColorTB:
40 Installation instructions for ColorTB::
41
40 42 import sys,ultratb
41 43 sys.excepthook = ultratb.VerboseTB()
42 44
43 45 Note: Much of the code in this module was lifted verbatim from the standard
44 46 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 47
46 * Color schemes
48 Color schemes
49 -------------
50
47 51 The colors are defined in the class TBTools through the use of the
48 52 ColorSchemeTable class. Currently the following exist:
49 53
50 54 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
55 escapes are just dummy blank strings).
52 56
53 57 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
58 or very dark background).
55 59
56 60 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
61 in light background terminals.
58 62
59 63 You can implement other color schemes easily, the syntax is fairly
60 64 self-explanatory. Please send back new schemes you develop to the author for
61 65 possible inclusion in future releases.
62 66
63 67 Inheritance diagram:
64 68
65 69 .. inheritance-diagram:: IPython.core.ultratb
66 70 :parts: 3
67 71 """
68 72
69 73 #*****************************************************************************
70 74 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
71 75 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
72 76 #
73 77 # Distributed under the terms of the BSD License. The full license is in
74 78 # the file COPYING, distributed as part of this software.
75 79 #*****************************************************************************
76 80
77 81 from __future__ import unicode_literals
78 82
79 83 import inspect
80 84 import keyword
81 85 import linecache
82 86 import os
83 87 import pydoc
84 88 import re
85 89 import sys
86 90 import time
87 91 import tokenize
88 92 import traceback
89 93 import types
90 94
91 95 try: # Python 2
92 96 generate_tokens = tokenize.generate_tokens
93 97 except AttributeError: # Python 3
94 98 generate_tokens = tokenize.tokenize
95 99
96 100 # For purposes of monkeypatching inspect to fix a bug in it.
97 101 from inspect import getsourcefile, getfile, getmodule,\
98 102 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
99 103
100 104 # IPython's own modules
101 105 # Modified pdb which doesn't damage IPython's readline handling
102 106 from IPython import get_ipython
103 107 from IPython.core import debugger
104 108 from IPython.core.display_trap import DisplayTrap
105 109 from IPython.core.excolors import exception_colors
106 110 from IPython.utils import PyColorize
107 111 from IPython.utils import io
108 112 from IPython.utils import openpy
109 113 from IPython.utils import path as util_path
110 114 from IPython.utils import py3compat
111 115 from IPython.utils import ulinecache
112 116 from IPython.utils.data import uniq_stable
113 117 from IPython.utils.warn import info, error
114 118
115 119 # Globals
116 120 # amount of space to put line numbers before verbose tracebacks
117 121 INDENT_SIZE = 8
118 122
119 123 # Default color scheme. This is used, for example, by the traceback
120 124 # formatter. When running in an actual IPython instance, the user's rc.colors
121 125 # value is used, but havinga module global makes this functionality available
122 126 # to users of ultratb who are NOT running inside ipython.
123 127 DEFAULT_SCHEME = 'NoColor'
124 128
125 129 #---------------------------------------------------------------------------
126 130 # Code begins
127 131
128 132 # Utility functions
129 133 def inspect_error():
130 134 """Print a message about internal inspect errors.
131 135
132 136 These are unfortunately quite common."""
133 137
134 138 error('Internal Python error in the inspect module.\n'
135 139 'Below is the traceback from this internal error.\n')
136 140
137 141 # This function is a monkeypatch we apply to the Python inspect module. We have
138 142 # now found when it's needed (see discussion on issue gh-1456), and we have a
139 143 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
140 144 # the monkeypatch is not applied. TK, Aug 2012.
141 145 def findsource(object):
142 146 """Return the entire source file and starting line number for an object.
143 147
144 148 The argument may be a module, class, method, function, traceback, frame,
145 149 or code object. The source code is returned as a list of all the lines
146 150 in the file and the line number indexes a line in that list. An IOError
147 151 is raised if the source code cannot be retrieved.
148 152
149 153 FIXED version with which we monkeypatch the stdlib to work around a bug."""
150 154
151 155 file = getsourcefile(object) or getfile(object)
152 156 # If the object is a frame, then trying to get the globals dict from its
153 157 # module won't work. Instead, the frame object itself has the globals
154 158 # dictionary.
155 159 globals_dict = None
156 160 if inspect.isframe(object):
157 161 # XXX: can this ever be false?
158 162 globals_dict = object.f_globals
159 163 else:
160 164 module = getmodule(object, file)
161 165 if module:
162 166 globals_dict = module.__dict__
163 167 lines = linecache.getlines(file, globals_dict)
164 168 if not lines:
165 169 raise IOError('could not get source code')
166 170
167 171 if ismodule(object):
168 172 return lines, 0
169 173
170 174 if isclass(object):
171 175 name = object.__name__
172 176 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
173 177 # make some effort to find the best matching class definition:
174 178 # use the one with the least indentation, which is the one
175 179 # that's most probably not inside a function definition.
176 180 candidates = []
177 181 for i in range(len(lines)):
178 182 match = pat.match(lines[i])
179 183 if match:
180 184 # if it's at toplevel, it's already the best one
181 185 if lines[i][0] == 'c':
182 186 return lines, i
183 187 # else add whitespace to candidate list
184 188 candidates.append((match.group(1), i))
185 189 if candidates:
186 190 # this will sort by whitespace, and by line number,
187 191 # less whitespace first
188 192 candidates.sort()
189 193 return lines, candidates[0][1]
190 194 else:
191 195 raise IOError('could not find class definition')
192 196
193 197 if ismethod(object):
194 198 object = object.im_func
195 199 if isfunction(object):
196 200 object = object.func_code
197 201 if istraceback(object):
198 202 object = object.tb_frame
199 203 if isframe(object):
200 204 object = object.f_code
201 205 if iscode(object):
202 206 if not hasattr(object, 'co_firstlineno'):
203 207 raise IOError('could not find function definition')
204 208 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
205 209 pmatch = pat.match
206 210 # fperez - fix: sometimes, co_firstlineno can give a number larger than
207 211 # the length of lines, which causes an error. Safeguard against that.
208 212 lnum = min(object.co_firstlineno,len(lines))-1
209 213 while lnum > 0:
210 214 if pmatch(lines[lnum]): break
211 215 lnum -= 1
212 216
213 217 return lines, lnum
214 218 raise IOError('could not find code object')
215 219
216 220 # Monkeypatch inspect to apply our bugfix. This code only works with Python >= 2.5
217 221 inspect.findsource = findsource
218 222
219 223 def fix_frame_records_filenames(records):
220 224 """Try to fix the filenames in each record from inspect.getinnerframes().
221 225
222 226 Particularly, modules loaded from within zip files have useless filenames
223 227 attached to their code object, and inspect.getinnerframes() just uses it.
224 228 """
225 229 fixed_records = []
226 230 for frame, filename, line_no, func_name, lines, index in records:
227 231 # Look inside the frame's globals dictionary for __file__, which should
228 232 # be better.
229 233 better_fn = frame.f_globals.get('__file__', None)
230 234 if isinstance(better_fn, str):
231 235 # Check the type just in case someone did something weird with
232 236 # __file__. It might also be None if the error occurred during
233 237 # import.
234 238 filename = better_fn
235 239 fixed_records.append((frame, filename, line_no, func_name, lines, index))
236 240 return fixed_records
237 241
238 242
239 243 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
240 244 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
241 245
242 246 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
243 247
244 248 # If the error is at the console, don't build any context, since it would
245 249 # otherwise produce 5 blank lines printed out (there is no file at the
246 250 # console)
247 251 rec_check = records[tb_offset:]
248 252 try:
249 253 rname = rec_check[0][1]
250 254 if rname == '<ipython console>' or rname.endswith('<string>'):
251 255 return rec_check
252 256 except IndexError:
253 257 pass
254 258
255 259 aux = traceback.extract_tb(etb)
256 260 assert len(records) == len(aux)
257 261 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
258 262 maybeStart = lnum-1 - context//2
259 263 start = max(maybeStart, 0)
260 264 end = start + context
261 265 lines = ulinecache.getlines(file)[start:end]
262 266 buf = list(records[i])
263 267 buf[LNUM_POS] = lnum
264 268 buf[INDEX_POS] = lnum - 1 - start
265 269 buf[LINES_POS] = lines
266 270 records[i] = tuple(buf)
267 271 return records[tb_offset:]
268 272
269 273 # Helper function -- largely belongs to VerboseTB, but we need the same
270 274 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
271 275 # can be recognized properly by ipython.el's py-traceback-line-re
272 276 # (SyntaxErrors have to be treated specially because they have no traceback)
273 277
274 278 _parser = PyColorize.Parser()
275 279
276 280 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
277 281 numbers_width = INDENT_SIZE - 1
278 282 res = []
279 283 i = lnum - index
280 284
281 285 # This lets us get fully syntax-highlighted tracebacks.
282 286 if scheme is None:
283 287 ipinst = get_ipython()
284 288 if ipinst is not None:
285 289 scheme = ipinst.colors
286 290 else:
287 291 scheme = DEFAULT_SCHEME
288 292
289 293 _line_format = _parser.format2
290 294
291 295 for line in lines:
292 296 line = py3compat.cast_unicode(line)
293 297
294 298 new_line, err = _line_format(line, 'str', scheme)
295 299 if not err: line = new_line
296 300
297 301 if i == lnum:
298 302 # This is the line with the error
299 303 pad = numbers_width - len(str(i))
300 304 if pad >= 3:
301 305 marker = '-'*(pad-3) + '-> '
302 306 elif pad == 2:
303 307 marker = '> '
304 308 elif pad == 1:
305 309 marker = '>'
306 310 else:
307 311 marker = ''
308 312 num = marker + str(i)
309 313 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
310 314 Colors.line, line, Colors.Normal)
311 315 else:
312 316 num = '%*s' % (numbers_width,i)
313 317 line = '%s%s%s %s' %(Colors.lineno, num,
314 318 Colors.Normal, line)
315 319
316 320 res.append(line)
317 321 if lvals and i == lnum:
318 322 res.append(lvals + '\n')
319 323 i = i + 1
320 324 return res
321 325
322 326
323 327 #---------------------------------------------------------------------------
324 328 # Module classes
325 329 class TBTools(object):
326 330 """Basic tools used by all traceback printer classes."""
327 331
328 332 # Number of frames to skip when reporting tracebacks
329 333 tb_offset = 0
330 334
331 335 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
332 336 # Whether to call the interactive pdb debugger after printing
333 337 # tracebacks or not
334 338 self.call_pdb = call_pdb
335 339
336 340 # Output stream to write to. Note that we store the original value in
337 341 # a private attribute and then make the public ostream a property, so
338 342 # that we can delay accessing io.stdout until runtime. The way
339 343 # things are written now, the io.stdout object is dynamically managed
340 344 # so a reference to it should NEVER be stored statically. This
341 345 # property approach confines this detail to a single location, and all
342 346 # subclasses can simply access self.ostream for writing.
343 347 self._ostream = ostream
344 348
345 349 # Create color table
346 350 self.color_scheme_table = exception_colors()
347 351
348 352 self.set_colors(color_scheme)
349 353 self.old_scheme = color_scheme # save initial value for toggles
350 354
351 355 if call_pdb:
352 356 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
353 357 else:
354 358 self.pdb = None
355 359
356 360 def _get_ostream(self):
357 361 """Output stream that exceptions are written to.
358 362
359 363 Valid values are:
360 364
361 365 - None: the default, which means that IPython will dynamically resolve
362 to io.stdout. This ensures compatibility with most tools, including
363 Windows (where plain stdout doesn't recognize ANSI escapes).
366 to io.stdout. This ensures compatibility with most tools, including
367 Windows (where plain stdout doesn't recognize ANSI escapes).
364 368
365 369 - Any object with 'write' and 'flush' attributes.
366 370 """
367 371 return io.stdout if self._ostream is None else self._ostream
368 372
369 373 def _set_ostream(self, val):
370 374 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
371 375 self._ostream = val
372 376
373 377 ostream = property(_get_ostream, _set_ostream)
374 378
375 379 def set_colors(self,*args,**kw):
376 380 """Shorthand access to the color table scheme selector method."""
377 381
378 382 # Set own color table
379 383 self.color_scheme_table.set_active_scheme(*args,**kw)
380 384 # for convenience, set Colors to the active scheme
381 385 self.Colors = self.color_scheme_table.active_colors
382 386 # Also set colors of debugger
383 387 if hasattr(self,'pdb') and self.pdb is not None:
384 388 self.pdb.set_colors(*args,**kw)
385 389
386 390 def color_toggle(self):
387 391 """Toggle between the currently active color scheme and NoColor."""
388 392
389 393 if self.color_scheme_table.active_scheme_name == 'NoColor':
390 394 self.color_scheme_table.set_active_scheme(self.old_scheme)
391 395 self.Colors = self.color_scheme_table.active_colors
392 396 else:
393 397 self.old_scheme = self.color_scheme_table.active_scheme_name
394 398 self.color_scheme_table.set_active_scheme('NoColor')
395 399 self.Colors = self.color_scheme_table.active_colors
396 400
397 401 def stb2text(self, stb):
398 402 """Convert a structured traceback (a list) to a string."""
399 403 return '\n'.join(stb)
400 404
401 405 def text(self, etype, value, tb, tb_offset=None, context=5):
402 406 """Return formatted traceback.
403 407
404 408 Subclasses may override this if they add extra arguments.
405 409 """
406 410 tb_list = self.structured_traceback(etype, value, tb,
407 411 tb_offset, context)
408 412 return self.stb2text(tb_list)
409 413
410 414 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
411 415 context=5, mode=None):
412 416 """Return a list of traceback frames.
413 417
414 418 Must be implemented by each class.
415 419 """
416 420 raise NotImplementedError()
417 421
418 422
419 423 #---------------------------------------------------------------------------
420 424 class ListTB(TBTools):
421 425 """Print traceback information from a traceback list, with optional color.
422 426
423 427 Calling requires 3 arguments: (etype, evalue, elist)
424 428 as would be obtained by::
425 429
426 430 etype, evalue, tb = sys.exc_info()
427 431 if tb:
428 432 elist = traceback.extract_tb(tb)
429 433 else:
430 434 elist = None
431 435
432 436 It can thus be used by programs which need to process the traceback before
433 437 printing (such as console replacements based on the code module from the
434 438 standard library).
435 439
436 440 Because they are meant to be called without a full traceback (only a
437 441 list), instances of this class can't call the interactive pdb debugger."""
438 442
439 443 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
440 444 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
441 445 ostream=ostream)
442 446
443 447 def __call__(self, etype, value, elist):
444 448 self.ostream.flush()
445 449 self.ostream.write(self.text(etype, value, elist))
446 450 self.ostream.write('\n')
447 451
448 452 def structured_traceback(self, etype, value, elist, tb_offset=None,
449 453 context=5):
450 454 """Return a color formatted string with the traceback info.
451 455
452 456 Parameters
453 457 ----------
454 458 etype : exception type
455 459 Type of the exception raised.
456 460
457 461 value : object
458 462 Data stored in the exception
459 463
460 464 elist : list
461 465 List of frames, see class docstring for details.
462 466
463 467 tb_offset : int, optional
464 468 Number of frames in the traceback to skip. If not given, the
465 469 instance value is used (set in constructor).
466 470
467 471 context : int, optional
468 472 Number of lines of context information to print.
469 473
470 474 Returns
471 475 -------
472 476 String with formatted exception.
473 477 """
474 478 tb_offset = self.tb_offset if tb_offset is None else tb_offset
475 479 Colors = self.Colors
476 480 out_list = []
477 481 if elist:
478 482
479 483 if tb_offset and len(elist) > tb_offset:
480 484 elist = elist[tb_offset:]
481 485
482 486 out_list.append('Traceback %s(most recent call last)%s:' %
483 487 (Colors.normalEm, Colors.Normal) + '\n')
484 488 out_list.extend(self._format_list(elist))
485 489 # The exception info should be a single entry in the list.
486 490 lines = ''.join(self._format_exception_only(etype, value))
487 491 out_list.append(lines)
488 492
489 493 # Note: this code originally read:
490 494
491 495 ## for line in lines[:-1]:
492 496 ## out_list.append(" "+line)
493 497 ## out_list.append(lines[-1])
494 498
495 499 # This means it was indenting everything but the last line by a little
496 500 # bit. I've disabled this for now, but if we see ugliness somewhre we
497 501 # can restore it.
498 502
499 503 return out_list
500 504
501 505 def _format_list(self, extracted_list):
502 506 """Format a list of traceback entry tuples for printing.
503 507
504 508 Given a list of tuples as returned by extract_tb() or
505 509 extract_stack(), return a list of strings ready for printing.
506 510 Each string in the resulting list corresponds to the item with the
507 511 same index in the argument list. Each string ends in a newline;
508 512 the strings may contain internal newlines as well, for those items
509 513 whose source text line is not None.
510 514
511 515 Lifted almost verbatim from traceback.py
512 516 """
513 517
514 518 Colors = self.Colors
515 519 list = []
516 520 for filename, lineno, name, line in extracted_list[:-1]:
517 521 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
518 522 (Colors.filename, filename, Colors.Normal,
519 523 Colors.lineno, lineno, Colors.Normal,
520 524 Colors.name, name, Colors.Normal)
521 525 if line:
522 526 item += ' %s\n' % line.strip()
523 527 list.append(item)
524 528 # Emphasize the last entry
525 529 filename, lineno, name, line = extracted_list[-1]
526 530 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
527 531 (Colors.normalEm,
528 532 Colors.filenameEm, filename, Colors.normalEm,
529 533 Colors.linenoEm, lineno, Colors.normalEm,
530 534 Colors.nameEm, name, Colors.normalEm,
531 535 Colors.Normal)
532 536 if line:
533 537 item += '%s %s%s\n' % (Colors.line, line.strip(),
534 538 Colors.Normal)
535 539 list.append(item)
536 540 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
537 541 return list
538 542
539 543 def _format_exception_only(self, etype, value):
540 544 """Format the exception part of a traceback.
541 545
542 546 The arguments are the exception type and value such as given by
543 547 sys.exc_info()[:2]. The return value is a list of strings, each ending
544 548 in a newline. Normally, the list contains a single string; however,
545 549 for SyntaxError exceptions, it contains several lines that (when
546 550 printed) display detailed information about where the syntax error
547 551 occurred. The message indicating which exception occurred is the
548 552 always last string in the list.
549 553
550 554 Also lifted nearly verbatim from traceback.py
551 555 """
552 556 have_filedata = False
553 557 Colors = self.Colors
554 558 list = []
555 559 stype = Colors.excName + etype.__name__ + Colors.Normal
556 560 if value is None:
557 561 # Not sure if this can still happen in Python 2.6 and above
558 562 list.append( py3compat.cast_unicode(stype) + '\n')
559 563 else:
560 564 if issubclass(etype, SyntaxError):
561 565 have_filedata = True
562 566 #print 'filename is',filename # dbg
563 567 if not value.filename: value.filename = "<string>"
564 568 if value.lineno:
565 569 lineno = value.lineno
566 570 textline = ulinecache.getline(value.filename, value.lineno)
567 571 else:
568 572 lineno = 'unknown'
569 573 textline = ''
570 574 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
571 575 (Colors.normalEm,
572 576 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
573 577 Colors.linenoEm, lineno, Colors.Normal ))
574 578 if textline == '':
575 579 textline = py3compat.cast_unicode(value.text, "utf-8")
576 580
577 581 if textline is not None:
578 582 i = 0
579 583 while i < len(textline) and textline[i].isspace():
580 584 i += 1
581 585 list.append('%s %s%s\n' % (Colors.line,
582 586 textline.strip(),
583 587 Colors.Normal))
584 588 if value.offset is not None:
585 589 s = ' '
586 590 for c in textline[i:value.offset-1]:
587 591 if c.isspace():
588 592 s += c
589 593 else:
590 594 s += ' '
591 595 list.append('%s%s^%s\n' % (Colors.caret, s,
592 596 Colors.Normal) )
593 597
594 598 try:
595 599 s = value.msg
596 600 except Exception:
597 601 s = self._some_str(value)
598 602 if s:
599 603 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
600 604 Colors.Normal, s))
601 605 else:
602 606 list.append('%s\n' % str(stype))
603 607
604 608 # sync with user hooks
605 609 if have_filedata:
606 610 ipinst = get_ipython()
607 611 if ipinst is not None:
608 612 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
609 613
610 614 return list
611 615
612 616 def get_exception_only(self, etype, value):
613 617 """Only print the exception type and message, without a traceback.
614 618
615 619 Parameters
616 620 ----------
617 621 etype : exception type
618 622 value : exception value
619 623 """
620 624 return ListTB.structured_traceback(self, etype, value, [])
621 625
622 626
623 627 def show_exception_only(self, etype, evalue):
624 628 """Only print the exception type and message, without a traceback.
625 629
626 630 Parameters
627 631 ----------
628 632 etype : exception type
629 633 value : exception value
630 634 """
631 635 # This method needs to use __call__ from *this* class, not the one from
632 636 # a subclass whose signature or behavior may be different
633 637 ostream = self.ostream
634 638 ostream.flush()
635 639 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
636 640 ostream.flush()
637 641
638 642 def _some_str(self, value):
639 643 # Lifted from traceback.py
640 644 try:
641 645 return str(value)
642 646 except:
643 647 return '<unprintable %s object>' % type(value).__name__
644 648
645 649 #----------------------------------------------------------------------------
646 650 class VerboseTB(TBTools):
647 651 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
648 652 of HTML. Requires inspect and pydoc. Crazy, man.
649 653
650 654 Modified version which optionally strips the topmost entries from the
651 655 traceback, to be used with alternate interpreters (because their own code
652 656 would appear in the traceback)."""
653 657
654 658 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
655 659 tb_offset=0, long_header=False, include_vars=True,
656 660 check_cache=None):
657 661 """Specify traceback offset, headers and color scheme.
658 662
659 663 Define how many frames to drop from the tracebacks. Calling it with
660 664 tb_offset=1 allows use of this handler in interpreters which will have
661 665 their own code at the top of the traceback (VerboseTB will first
662 666 remove that frame before printing the traceback info)."""
663 667 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
664 668 ostream=ostream)
665 669 self.tb_offset = tb_offset
666 670 self.long_header = long_header
667 671 self.include_vars = include_vars
668 672 # By default we use linecache.checkcache, but the user can provide a
669 673 # different check_cache implementation. This is used by the IPython
670 674 # kernel to provide tracebacks for interactive code that is cached,
671 675 # by a compiler instance that flushes the linecache but preserves its
672 676 # own code cache.
673 677 if check_cache is None:
674 678 check_cache = linecache.checkcache
675 679 self.check_cache = check_cache
676 680
677 681 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
678 682 context=5):
679 683 """Return a nice text document describing the traceback."""
680 684
681 685 tb_offset = self.tb_offset if tb_offset is None else tb_offset
682 686
683 687 # some locals
684 688 try:
685 689 etype = etype.__name__
686 690 except AttributeError:
687 691 pass
688 692 Colors = self.Colors # just a shorthand + quicker name lookup
689 693 ColorsNormal = Colors.Normal # used a lot
690 694 col_scheme = self.color_scheme_table.active_scheme_name
691 695 indent = ' '*INDENT_SIZE
692 696 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
693 697 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
694 698 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
695 699
696 700 # some internal-use functions
697 701 def text_repr(value):
698 702 """Hopefully pretty robust repr equivalent."""
699 703 # this is pretty horrible but should always return *something*
700 704 try:
701 705 return pydoc.text.repr(value)
702 706 except KeyboardInterrupt:
703 707 raise
704 708 except:
705 709 try:
706 710 return repr(value)
707 711 except KeyboardInterrupt:
708 712 raise
709 713 except:
710 714 try:
711 715 # all still in an except block so we catch
712 716 # getattr raising
713 717 name = getattr(value, '__name__', None)
714 718 if name:
715 719 # ick, recursion
716 720 return text_repr(name)
717 721 klass = getattr(value, '__class__', None)
718 722 if klass:
719 723 return '%s instance' % text_repr(klass)
720 724 except KeyboardInterrupt:
721 725 raise
722 726 except:
723 727 return 'UNRECOVERABLE REPR FAILURE'
724 728 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
725 729 def nullrepr(value, repr=text_repr): return ''
726 730
727 731 # meat of the code begins
728 732 try:
729 733 etype = etype.__name__
730 734 except AttributeError:
731 735 pass
732 736
733 737 if self.long_header:
734 738 # Header with the exception type, python version, and date
735 739 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
736 740 date = time.ctime(time.time())
737 741
738 742 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
739 743 exc, ' '*(75-len(str(etype))-len(pyver)),
740 744 pyver, date.rjust(75) )
741 745 head += "\nA problem occured executing Python code. Here is the sequence of function"\
742 746 "\ncalls leading up to the error, with the most recent (innermost) call last."
743 747 else:
744 748 # Simplified header
745 749 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
746 750 'Traceback (most recent call last)'.\
747 751 rjust(75 - len(str(etype)) ) )
748 752 frames = []
749 753 # Flush cache before calling inspect. This helps alleviate some of the
750 754 # problems with python 2.3's inspect.py.
751 755 ##self.check_cache()
752 756 # Drop topmost frames if requested
753 757 try:
754 758 # Try the default getinnerframes and Alex's: Alex's fixes some
755 759 # problems, but it generates empty tracebacks for console errors
756 760 # (5 blanks lines) where none should be returned.
757 761 #records = inspect.getinnerframes(etb, context)[tb_offset:]
758 762 #print 'python records:', records # dbg
759 763 records = _fixed_getinnerframes(etb, context, tb_offset)
760 764 #print 'alex records:', records # dbg
761 765 except:
762 766
763 767 # FIXME: I've been getting many crash reports from python 2.3
764 768 # users, traceable to inspect.py. If I can find a small test-case
765 769 # to reproduce this, I should either write a better workaround or
766 770 # file a bug report against inspect (if that's the real problem).
767 771 # So far, I haven't been able to find an isolated example to
768 772 # reproduce the problem.
769 773 inspect_error()
770 774 traceback.print_exc(file=self.ostream)
771 775 info('\nUnfortunately, your original traceback can not be constructed.\n')
772 776 return ''
773 777
774 778 # build some color string templates outside these nested loops
775 779 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
776 780 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
777 781 ColorsNormal)
778 782 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
779 783 (Colors.vName, Colors.valEm, ColorsNormal)
780 784 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
781 785 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
782 786 Colors.vName, ColorsNormal)
783 787 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
784 788 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
785 789 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
786 790 ColorsNormal)
787 791
788 792 # now, loop over all records printing context and info
789 793 abspath = os.path.abspath
790 794 for frame, file, lnum, func, lines, index in records:
791 795 #print '*** record:',file,lnum,func,lines,index # dbg
792 796 if not file:
793 797 file = '?'
794 798 elif not(file.startswith(str("<")) and file.endswith(str(">"))):
795 799 # Guess that filenames like <string> aren't real filenames, so
796 800 # don't call abspath on them.
797 801 try:
798 802 file = abspath(file)
799 803 except OSError:
800 804 # Not sure if this can still happen: abspath now works with
801 805 # file names like <string>
802 806 pass
803 807 file = py3compat.cast_unicode(file, util_path.fs_encoding)
804 808 link = tpl_link % file
805 809 args, varargs, varkw, locals = inspect.getargvalues(frame)
806 810
807 811 if func == '?':
808 812 call = ''
809 813 else:
810 814 # Decide whether to include variable details or not
811 815 var_repr = self.include_vars and eqrepr or nullrepr
812 816 try:
813 817 call = tpl_call % (func,inspect.formatargvalues(args,
814 818 varargs, varkw,
815 819 locals,formatvalue=var_repr))
816 820 except KeyError:
817 821 # This happens in situations like errors inside generator
818 822 # expressions, where local variables are listed in the
819 823 # line, but can't be extracted from the frame. I'm not
820 824 # 100% sure this isn't actually a bug in inspect itself,
821 825 # but since there's no info for us to compute with, the
822 826 # best we can do is report the failure and move on. Here
823 827 # we must *not* call any traceback construction again,
824 828 # because that would mess up use of %debug later on. So we
825 829 # simply report the failure and move on. The only
826 830 # limitation will be that this frame won't have locals
827 831 # listed in the call signature. Quite subtle problem...
828 832 # I can't think of a good way to validate this in a unit
829 833 # test, but running a script consisting of:
830 834 # dict( (k,v.strip()) for (k,v) in range(10) )
831 835 # will illustrate the error, if this exception catch is
832 836 # disabled.
833 837 call = tpl_call_fail % func
834 838
835 839 # Don't attempt to tokenize binary files.
836 840 if file.endswith(('.so', '.pyd', '.dll')):
837 841 frames.append('%s %s\n' % (link,call))
838 842 continue
839 843 elif file.endswith(('.pyc','.pyo')):
840 844 # Look up the corresponding source file.
841 845 file = openpy.source_from_cache(file)
842 846
843 847 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
844 848 line = getline(file, lnum[0])
845 849 lnum[0] += 1
846 850 return line
847 851
848 852 # Build the list of names on this line of code where the exception
849 853 # occurred.
850 854 try:
851 855 names = []
852 856 name_cont = False
853 857
854 858 for token_type, token, start, end, line in generate_tokens(linereader):
855 859 # build composite names
856 860 if token_type == tokenize.NAME and token not in keyword.kwlist:
857 861 if name_cont:
858 862 # Continuation of a dotted name
859 863 try:
860 864 names[-1].append(token)
861 865 except IndexError:
862 866 names.append([token])
863 867 name_cont = False
864 868 else:
865 869 # Regular new names. We append everything, the caller
866 870 # will be responsible for pruning the list later. It's
867 871 # very tricky to try to prune as we go, b/c composite
868 872 # names can fool us. The pruning at the end is easy
869 873 # to do (or the caller can print a list with repeated
870 874 # names if so desired.
871 875 names.append([token])
872 876 elif token == '.':
873 877 name_cont = True
874 878 elif token_type == tokenize.NEWLINE:
875 879 break
876 880
877 881 except (IndexError, UnicodeDecodeError):
878 882 # signals exit of tokenizer
879 883 pass
880 884 except tokenize.TokenError as msg:
881 885 _m = ("An unexpected error occurred while tokenizing input\n"
882 886 "The following traceback may be corrupted or invalid\n"
883 887 "The error message is: %s\n" % msg)
884 888 error(_m)
885 889
886 890 # Join composite names (e.g. "dict.fromkeys")
887 891 names = ['.'.join(n) for n in names]
888 892 # prune names list of duplicates, but keep the right order
889 893 unique_names = uniq_stable(names)
890 894
891 895 # Start loop over vars
892 896 lvals = []
893 897 if self.include_vars:
894 898 for name_full in unique_names:
895 899 name_base = name_full.split('.',1)[0]
896 900 if name_base in frame.f_code.co_varnames:
897 901 if name_base in locals:
898 902 try:
899 903 value = repr(eval(name_full,locals))
900 904 except:
901 905 value = undefined
902 906 else:
903 907 value = undefined
904 908 name = tpl_local_var % name_full
905 909 else:
906 910 if name_base in frame.f_globals:
907 911 try:
908 912 value = repr(eval(name_full,frame.f_globals))
909 913 except:
910 914 value = undefined
911 915 else:
912 916 value = undefined
913 917 name = tpl_global_var % name_full
914 918 lvals.append(tpl_name_val % (name,value))
915 919 if lvals:
916 920 lvals = '%s%s' % (indent,em_normal.join(lvals))
917 921 else:
918 922 lvals = ''
919 923
920 924 level = '%s %s\n' % (link,call)
921 925
922 926 if index is None:
923 927 frames.append(level)
924 928 else:
925 929 frames.append('%s%s' % (level,''.join(
926 930 _format_traceback_lines(lnum,index,lines,Colors,lvals,
927 931 col_scheme))))
928 932
929 933 # Get (safely) a string form of the exception info
930 934 try:
931 935 etype_str,evalue_str = map(str,(etype,evalue))
932 936 except:
933 937 # User exception is improperly defined.
934 938 etype,evalue = str,sys.exc_info()[:2]
935 939 etype_str,evalue_str = map(str,(etype,evalue))
936 940 # ... and format it
937 941 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
938 942 ColorsNormal, py3compat.cast_unicode(evalue_str))]
939 943 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
940 944 try:
941 945 names = [w for w in dir(evalue) if isinstance(w, basestring)]
942 946 except:
943 947 # Every now and then, an object with funny inernals blows up
944 948 # when dir() is called on it. We do the best we can to report
945 949 # the problem and continue
946 950 _m = '%sException reporting error (object with broken dir())%s:'
947 951 exception.append(_m % (Colors.excName,ColorsNormal))
948 952 etype_str,evalue_str = map(str,sys.exc_info()[:2])
949 953 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
950 954 ColorsNormal, py3compat.cast_unicode(evalue_str)))
951 955 names = []
952 956 for name in names:
953 957 value = text_repr(getattr(evalue, name))
954 958 exception.append('\n%s%s = %s' % (indent, name, value))
955 959
956 960 # vds: >>
957 961 if records:
958 962 filepath, lnum = records[-1][1:3]
959 963 #print "file:", str(file), "linenb", str(lnum) # dbg
960 964 filepath = os.path.abspath(filepath)
961 965 ipinst = get_ipython()
962 966 if ipinst is not None:
963 967 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
964 968 # vds: <<
965 969
966 970 # return all our info assembled as a single string
967 971 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
968 972 return [head] + frames + [''.join(exception[0])]
969 973
970 974 def debugger(self,force=False):
971 975 """Call up the pdb debugger if desired, always clean up the tb
972 976 reference.
973 977
974 978 Keywords:
975 979
976 980 - force(False): by default, this routine checks the instance call_pdb
977 flag and does not actually invoke the debugger if the flag is false.
978 The 'force' option forces the debugger to activate even if the flag
979 is false.
981 flag and does not actually invoke the debugger if the flag is false.
982 The 'force' option forces the debugger to activate even if the flag
983 is false.
980 984
981 985 If the call_pdb flag is set, the pdb interactive debugger is
982 986 invoked. In all cases, the self.tb reference to the current traceback
983 987 is deleted to prevent lingering references which hamper memory
984 988 management.
985 989
986 990 Note that each call to pdb() does an 'import readline', so if your app
987 991 requires a special setup for the readline completers, you'll have to
988 992 fix that by hand after invoking the exception handler."""
989 993
990 994 if force or self.call_pdb:
991 995 if self.pdb is None:
992 996 self.pdb = debugger.Pdb(
993 997 self.color_scheme_table.active_scheme_name)
994 998 # the system displayhook may have changed, restore the original
995 999 # for pdb
996 1000 display_trap = DisplayTrap(hook=sys.__displayhook__)
997 1001 with display_trap:
998 1002 self.pdb.reset()
999 1003 # Find the right frame so we don't pop up inside ipython itself
1000 1004 if hasattr(self,'tb') and self.tb is not None:
1001 1005 etb = self.tb
1002 1006 else:
1003 1007 etb = self.tb = sys.last_traceback
1004 1008 while self.tb is not None and self.tb.tb_next is not None:
1005 1009 self.tb = self.tb.tb_next
1006 1010 if etb and etb.tb_next:
1007 1011 etb = etb.tb_next
1008 1012 self.pdb.botframe = etb.tb_frame
1009 1013 self.pdb.interaction(self.tb.tb_frame, self.tb)
1010 1014
1011 1015 if hasattr(self,'tb'):
1012 1016 del self.tb
1013 1017
1014 1018 def handler(self, info=None):
1015 1019 (etype, evalue, etb) = info or sys.exc_info()
1016 1020 self.tb = etb
1017 1021 ostream = self.ostream
1018 1022 ostream.flush()
1019 1023 ostream.write(self.text(etype, evalue, etb))
1020 1024 ostream.write('\n')
1021 1025 ostream.flush()
1022 1026
1023 1027 # Changed so an instance can just be called as VerboseTB_inst() and print
1024 1028 # out the right info on its own.
1025 1029 def __call__(self, etype=None, evalue=None, etb=None):
1026 1030 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1027 1031 if etb is None:
1028 1032 self.handler()
1029 1033 else:
1030 1034 self.handler((etype, evalue, etb))
1031 1035 try:
1032 1036 self.debugger()
1033 1037 except KeyboardInterrupt:
1034 1038 print "\nKeyboardInterrupt"
1035 1039
1036 1040 #----------------------------------------------------------------------------
1037 1041 class FormattedTB(VerboseTB, ListTB):
1038 1042 """Subclass ListTB but allow calling with a traceback.
1039 1043
1040 1044 It can thus be used as a sys.excepthook for Python > 2.1.
1041 1045
1042 1046 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1043 1047
1044 1048 Allows a tb_offset to be specified. This is useful for situations where
1045 1049 one needs to remove a number of topmost frames from the traceback (such as
1046 1050 occurs with python programs that themselves execute other python code,
1047 1051 like Python shells). """
1048 1052
1049 1053 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1050 1054 ostream=None,
1051 1055 tb_offset=0, long_header=False, include_vars=False,
1052 1056 check_cache=None):
1053 1057
1054 1058 # NEVER change the order of this list. Put new modes at the end:
1055 1059 self.valid_modes = ['Plain','Context','Verbose']
1056 1060 self.verbose_modes = self.valid_modes[1:3]
1057 1061
1058 1062 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1059 1063 ostream=ostream, tb_offset=tb_offset,
1060 1064 long_header=long_header, include_vars=include_vars,
1061 1065 check_cache=check_cache)
1062 1066
1063 1067 # Different types of tracebacks are joined with different separators to
1064 1068 # form a single string. They are taken from this dict
1065 1069 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1066 1070 # set_mode also sets the tb_join_char attribute
1067 1071 self.set_mode(mode)
1068 1072
1069 1073 def _extract_tb(self,tb):
1070 1074 if tb:
1071 1075 return traceback.extract_tb(tb)
1072 1076 else:
1073 1077 return None
1074 1078
1075 1079 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1076 1080 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1077 1081 mode = self.mode
1078 1082 if mode in self.verbose_modes:
1079 1083 # Verbose modes need a full traceback
1080 1084 return VerboseTB.structured_traceback(
1081 1085 self, etype, value, tb, tb_offset, context
1082 1086 )
1083 1087 else:
1084 1088 # We must check the source cache because otherwise we can print
1085 1089 # out-of-date source code.
1086 1090 self.check_cache()
1087 1091 # Now we can extract and format the exception
1088 1092 elist = self._extract_tb(tb)
1089 1093 return ListTB.structured_traceback(
1090 1094 self, etype, value, elist, tb_offset, context
1091 1095 )
1092 1096
1093 1097 def stb2text(self, stb):
1094 1098 """Convert a structured traceback (a list) to a string."""
1095 1099 return self.tb_join_char.join(stb)
1096 1100
1097 1101
1098 1102 def set_mode(self,mode=None):
1099 1103 """Switch to the desired mode.
1100 1104
1101 1105 If mode is not specified, cycles through the available modes."""
1102 1106
1103 1107 if not mode:
1104 1108 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1105 1109 len(self.valid_modes)
1106 1110 self.mode = self.valid_modes[new_idx]
1107 1111 elif mode not in self.valid_modes:
1108 1112 raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n'
1109 1113 'Valid modes: '+str(self.valid_modes))
1110 1114 else:
1111 1115 self.mode = mode
1112 1116 # include variable details only in 'Verbose' mode
1113 1117 self.include_vars = (self.mode == self.valid_modes[2])
1114 1118 # Set the join character for generating text tracebacks
1115 1119 self.tb_join_char = self._join_chars[self.mode]
1116 1120
1117 1121 # some convenient shorcuts
1118 1122 def plain(self):
1119 1123 self.set_mode(self.valid_modes[0])
1120 1124
1121 1125 def context(self):
1122 1126 self.set_mode(self.valid_modes[1])
1123 1127
1124 1128 def verbose(self):
1125 1129 self.set_mode(self.valid_modes[2])
1126 1130
1127 1131 #----------------------------------------------------------------------------
1128 1132 class AutoFormattedTB(FormattedTB):
1129 1133 """A traceback printer which can be called on the fly.
1130 1134
1131 1135 It will find out about exceptions by itself.
1132 1136
1133 1137 A brief example::
1134 1138
1135 1139 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1136 1140 try:
1137 1141 ...
1138 1142 except:
1139 1143 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1140 1144 """
1141 1145
1142 1146 def __call__(self,etype=None,evalue=None,etb=None,
1143 1147 out=None,tb_offset=None):
1144 1148 """Print out a formatted exception traceback.
1145 1149
1146 1150 Optional arguments:
1147 1151 - out: an open file-like object to direct output to.
1148 1152
1149 1153 - tb_offset: the number of frames to skip over in the stack, on a
1150 1154 per-call basis (this overrides temporarily the instance's tb_offset
1151 1155 given at initialization time. """
1152 1156
1153 1157
1154 1158 if out is None:
1155 1159 out = self.ostream
1156 1160 out.flush()
1157 1161 out.write(self.text(etype, evalue, etb, tb_offset))
1158 1162 out.write('\n')
1159 1163 out.flush()
1160 1164 # FIXME: we should remove the auto pdb behavior from here and leave
1161 1165 # that to the clients.
1162 1166 try:
1163 1167 self.debugger()
1164 1168 except KeyboardInterrupt:
1165 1169 print "\nKeyboardInterrupt"
1166 1170
1167 1171 def structured_traceback(self, etype=None, value=None, tb=None,
1168 1172 tb_offset=None, context=5):
1169 1173 if etype is None:
1170 1174 etype,value,tb = sys.exc_info()
1171 1175 self.tb = tb
1172 1176 return FormattedTB.structured_traceback(
1173 1177 self, etype, value, tb, tb_offset, context)
1174 1178
1175 1179 #---------------------------------------------------------------------------
1176 1180
1177 1181 # A simple class to preserve Nathan's original functionality.
1178 1182 class ColorTB(FormattedTB):
1179 1183 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1180 1184 def __init__(self,color_scheme='Linux',call_pdb=0):
1181 1185 FormattedTB.__init__(self,color_scheme=color_scheme,
1182 1186 call_pdb=call_pdb)
1183 1187
1184 1188
1185 1189 class SyntaxTB(ListTB):
1186 1190 """Extension which holds some state: the last exception value"""
1187 1191
1188 1192 def __init__(self,color_scheme = 'NoColor'):
1189 1193 ListTB.__init__(self,color_scheme)
1190 1194 self.last_syntax_error = None
1191 1195
1192 1196 def __call__(self, etype, value, elist):
1193 1197 self.last_syntax_error = value
1194 1198 ListTB.__call__(self,etype,value,elist)
1195 1199
1196 1200 def clear_err_state(self):
1197 1201 """Return the current error state and clear it"""
1198 1202 e = self.last_syntax_error
1199 1203 self.last_syntax_error = None
1200 1204 return e
1201 1205
1202 1206 def stb2text(self, stb):
1203 1207 """Convert a structured traceback (a list) to a string."""
1204 1208 return ''.join(stb)
1205 1209
1206 1210
1207 1211 #----------------------------------------------------------------------------
1208 1212 # module testing (minimal)
1209 1213 if __name__ == "__main__":
1210 1214 def spam(c, d_e):
1211 1215 (d, e) = d_e
1212 1216 x = c + d
1213 1217 y = c * d
1214 1218 foo(x, y)
1215 1219
1216 1220 def foo(a, b, bar=1):
1217 1221 eggs(a, b + bar)
1218 1222
1219 1223 def eggs(f, g, z=globals()):
1220 1224 h = f + g
1221 1225 i = f - g
1222 1226 return h / i
1223 1227
1224 1228 print ''
1225 1229 print '*** Before ***'
1226 1230 try:
1227 1231 print spam(1, (2, 3))
1228 1232 except:
1229 1233 traceback.print_exc()
1230 1234 print ''
1231 1235
1232 1236 handler = ColorTB()
1233 1237 print '*** ColorTB ***'
1234 1238 try:
1235 1239 print spam(1, (2, 3))
1236 1240 except:
1237 1241 handler(*sys.exc_info())
1238 1242 print ''
1239 1243
1240 1244 handler = VerboseTB()
1241 1245 print '*** VerboseTB ***'
1242 1246 try:
1243 1247 print spam(1, (2, 3))
1244 1248 except:
1245 1249 handler(*sys.exc_info())
1246 1250 print ''
1247 1251
@@ -1,582 +1,582 b''
1 1 """Module for interactive demos using IPython.
2 2
3 3 This module implements a few classes for running Python scripts interactively
4 4 in IPython for demonstrations. With very simple markup (a few tags in
5 5 comments), you can control points where the script stops executing and returns
6 6 control to IPython.
7 7
8 8
9 9 Provided classes
10 10 ----------------
11 11
12 12 The classes are (see their docstrings for further details):
13 13
14 14 - Demo: pure python demos
15 15
16 16 - IPythonDemo: demos with input to be processed by IPython as if it had been
17 typed interactively (so magics work, as well as any other special syntax you
18 may have added via input prefilters).
17 typed interactively (so magics work, as well as any other special syntax you
18 may have added via input prefilters).
19 19
20 20 - LineDemo: single-line version of the Demo class. These demos are executed
21 one line at a time, and require no markup.
21 one line at a time, and require no markup.
22 22
23 23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
24 executed a line at a time, but processed via IPython).
24 executed a line at a time, but processed via IPython).
25 25
26 26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
27 27 declares an empty marquee and a pre_cmd that clears the screen before each
28 28 block (see Subclassing below).
29 29
30 30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
31 31 classes.
32 32
33 33 Inheritance diagram:
34 34
35 35 .. inheritance-diagram:: IPython.lib.demo
36 36 :parts: 3
37 37
38 38 Subclassing
39 39 -----------
40 40
41 41 The classes here all include a few methods meant to make customization by
42 42 subclassing more convenient. Their docstrings below have some more details:
43 43
44 44 - marquee(): generates a marquee to provide visible on-screen markers at each
45 45 block start and end.
46 46
47 47 - pre_cmd(): run right before the execution of each block.
48 48
49 49 - post_cmd(): run right after the execution of each block. If the block
50 50 raises an exception, this is NOT called.
51 51
52 52
53 53 Operation
54 54 ---------
55 55
56 56 The file is run in its own empty namespace (though you can pass it a string of
57 57 arguments as if in a command line environment, and it will see those as
58 58 sys.argv). But at each stop, the global IPython namespace is updated with the
59 59 current internal demo namespace, so you can work interactively with the data
60 60 accumulated so far.
61 61
62 62 By default, each block of code is printed (with syntax highlighting) before
63 63 executing it and you have to confirm execution. This is intended to show the
64 64 code to an audience first so you can discuss it, and only proceed with
65 65 execution once you agree. There are a few tags which allow you to modify this
66 66 behavior.
67 67
68 68 The supported tags are:
69 69
70 70 # <demo> stop
71 71
72 72 Defines block boundaries, the points where IPython stops execution of the
73 73 file and returns to the interactive prompt.
74 74
75 75 You can optionally mark the stop tag with extra dashes before and after the
76 76 word 'stop', to help visually distinguish the blocks in a text editor:
77 77
78 78 # <demo> --- stop ---
79 79
80 80
81 81 # <demo> silent
82 82
83 83 Make a block execute silently (and hence automatically). Typically used in
84 84 cases where you have some boilerplate or initialization code which you need
85 85 executed but do not want to be seen in the demo.
86 86
87 87 # <demo> auto
88 88
89 89 Make a block execute automatically, but still being printed. Useful for
90 90 simple code which does not warrant discussion, since it avoids the extra
91 91 manual confirmation.
92 92
93 93 # <demo> auto_all
94 94
95 95 This tag can _only_ be in the first block, and if given it overrides the
96 96 individual auto tags to make the whole demo fully automatic (no block asks
97 97 for confirmation). It can also be given at creation time (or the attribute
98 98 set later) to override what's in the file.
99 99
100 100 While _any_ python file can be run as a Demo instance, if there are no stop
101 101 tags the whole file will run in a single block (no different that calling
102 102 first %pycat and then %run). The minimal markup to make this useful is to
103 103 place a set of stop tags; the other tags are only there to let you fine-tune
104 104 the execution.
105 105
106 106 This is probably best explained with the simple example file below. You can
107 107 copy this into a file named ex_demo.py, and try running it via::
108 108
109 109 from IPython.demo import Demo
110 110 d = Demo('ex_demo.py')
111 111 d()
112 112
113 113 Each time you call the demo object, it runs the next block. The demo object
114 114 has a few useful methods for navigation, like again(), edit(), jump(), seek()
115 115 and back(). It can be reset for a new run via reset() or reloaded from disk
116 116 (in case you've edited the source) via reload(). See their docstrings below.
117 117
118 118 Note: To make this simpler to explore, a file called "demo-exercizer.py" has
119 119 been added to the "docs/examples/core" directory. Just cd to this directory in
120 120 an IPython session, and type::
121 121
122 122 %run demo-exercizer.py
123 123
124 124 and then follow the directions.
125 125
126 126 Example
127 127 -------
128 128
129 129 The following is a very simple example of a valid demo file.
130 130
131 131 ::
132 132
133 133 #################### EXAMPLE DEMO <ex_demo.py> ###############################
134 134 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
135 135
136 136 print 'Hello, welcome to an interactive IPython demo.'
137 137
138 138 # The mark below defines a block boundary, which is a point where IPython will
139 139 # stop execution and return to the interactive prompt. The dashes are actually
140 140 # optional and used only as a visual aid to clearly separate blocks while
141 141 # editing the demo code.
142 142 # <demo> stop
143 143
144 144 x = 1
145 145 y = 2
146 146
147 147 # <demo> stop
148 148
149 149 # the mark below makes this block as silent
150 150 # <demo> silent
151 151
152 152 print 'This is a silent block, which gets executed but not printed.'
153 153
154 154 # <demo> stop
155 155 # <demo> auto
156 156 print 'This is an automatic block.'
157 157 print 'It is executed without asking for confirmation, but printed.'
158 158 z = x+y
159 159
160 160 print 'z=',x
161 161
162 162 # <demo> stop
163 163 # This is just another normal block.
164 164 print 'z is now:', z
165 165
166 166 print 'bye!'
167 167 ################### END EXAMPLE DEMO <ex_demo.py> ############################
168 168 """
169 169
170 170 from __future__ import unicode_literals
171 171
172 172 #*****************************************************************************
173 173 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
174 174 #
175 175 # Distributed under the terms of the BSD License. The full license is in
176 176 # the file COPYING, distributed as part of this software.
177 177 #
178 178 #*****************************************************************************
179 179 from __future__ import print_function
180 180
181 181 import os
182 182 import re
183 183 import shlex
184 184 import sys
185 185
186 186 from IPython.utils import io
187 187 from IPython.utils.text import marquee
188 188 from IPython.utils import openpy
189 189 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
190 190
191 191 class DemoError(Exception): pass
192 192
193 193 def re_mark(mark):
194 194 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
195 195
196 196 class Demo(object):
197 197
198 198 re_stop = re_mark('-*\s?stop\s?-*')
199 199 re_silent = re_mark('silent')
200 200 re_auto = re_mark('auto')
201 201 re_auto_all = re_mark('auto_all')
202 202
203 203 def __init__(self,src,title='',arg_str='',auto_all=None):
204 204 """Make a new demo object. To run the demo, simply call the object.
205 205
206 206 See the module docstring for full details and an example (you can use
207 207 IPython.Demo? in IPython to see it).
208 208
209 209 Inputs:
210 210
211 211 - src is either a file, or file-like object, or a
212 212 string that can be resolved to a filename.
213 213
214 214 Optional inputs:
215 215
216 216 - title: a string to use as the demo name. Of most use when the demo
217 you are making comes from an object that has no filename, or if you
218 want an alternate denotation distinct from the filename.
217 you are making comes from an object that has no filename, or if you
218 want an alternate denotation distinct from the filename.
219 219
220 220 - arg_str(''): a string of arguments, internally converted to a list
221 just like sys.argv, so the demo script can see a similar
222 environment.
221 just like sys.argv, so the demo script can see a similar
222 environment.
223 223
224 224 - auto_all(None): global flag to run all blocks automatically without
225 confirmation. This attribute overrides the block-level tags and
226 applies to the whole demo. It is an attribute of the object, and
227 can be changed at runtime simply by reassigning it to a boolean
228 value.
225 confirmation. This attribute overrides the block-level tags and
226 applies to the whole demo. It is an attribute of the object, and
227 can be changed at runtime simply by reassigning it to a boolean
228 value.
229 229 """
230 230 if hasattr(src, "read"):
231 231 # It seems to be a file or a file-like object
232 232 self.fname = "from a file-like object"
233 233 if title == '':
234 234 self.title = "from a file-like object"
235 235 else:
236 236 self.title = title
237 237 else:
238 238 # Assume it's a string or something that can be converted to one
239 239 self.fname = src
240 240 if title == '':
241 241 (filepath, filename) = os.path.split(src)
242 242 self.title = filename
243 243 else:
244 244 self.title = title
245 245 self.sys_argv = [src] + shlex.split(arg_str)
246 246 self.auto_all = auto_all
247 247 self.src = src
248 248
249 249 # get a few things from ipython. While it's a bit ugly design-wise,
250 250 # it ensures that things like color scheme and the like are always in
251 251 # sync with the ipython mode being used. This class is only meant to
252 252 # be used inside ipython anyways, so it's OK.
253 253 ip = get_ipython() # this is in builtins whenever IPython is running
254 254 self.ip_ns = ip.user_ns
255 255 self.ip_colorize = ip.pycolorize
256 256 self.ip_showtb = ip.showtraceback
257 257 self.ip_run_cell = ip.run_cell
258 258 self.shell = ip
259 259
260 260 # load user data and initialize data structures
261 261 self.reload()
262 262
263 263 def fload(self):
264 264 """Load file object."""
265 265 # read data and parse into blocks
266 266 if hasattr(self, 'fobj') and self.fobj is not None:
267 267 self.fobj.close()
268 268 if hasattr(self.src, "read"):
269 269 # It seems to be a file or a file-like object
270 270 self.fobj = self.src
271 271 else:
272 272 # Assume it's a string or something that can be converted to one
273 273 self.fobj = openpy.open(self.fname)
274 274
275 275 def reload(self):
276 276 """Reload source from disk and initialize state."""
277 277 self.fload()
278 278
279 279 self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
280 280 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
281 281 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
282 282 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
283 283
284 284 # if auto_all is not given (def. None), we read it from the file
285 285 if self.auto_all is None:
286 286 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
287 287 else:
288 288 self.auto_all = bool(self.auto_all)
289 289
290 290 # Clean the sources from all markup so it doesn't get displayed when
291 291 # running the demo
292 292 src_blocks = []
293 293 auto_strip = lambda s: self.re_auto.sub('',s)
294 294 for i,b in enumerate(src_b):
295 295 if self._auto[i]:
296 296 src_blocks.append(auto_strip(b))
297 297 else:
298 298 src_blocks.append(b)
299 299 # remove the auto_all marker
300 300 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
301 301
302 302 self.nblocks = len(src_blocks)
303 303 self.src_blocks = src_blocks
304 304
305 305 # also build syntax-highlighted source
306 306 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
307 307
308 308 # ensure clean namespace and seek offset
309 309 self.reset()
310 310
311 311 def reset(self):
312 312 """Reset the namespace and seek pointer to restart the demo"""
313 313 self.user_ns = {}
314 314 self.finished = False
315 315 self.block_index = 0
316 316
317 317 def _validate_index(self,index):
318 318 if index<0 or index>=self.nblocks:
319 319 raise ValueError('invalid block index %s' % index)
320 320
321 321 def _get_index(self,index):
322 322 """Get the current block index, validating and checking status.
323 323
324 324 Returns None if the demo is finished"""
325 325
326 326 if index is None:
327 327 if self.finished:
328 328 print('Demo finished. Use <demo_name>.reset() if you want to rerun it.', file=io.stdout)
329 329 return None
330 330 index = self.block_index
331 331 else:
332 332 self._validate_index(index)
333 333 return index
334 334
335 335 def seek(self,index):
336 336 """Move the current seek pointer to the given block.
337 337
338 338 You can use negative indices to seek from the end, with identical
339 339 semantics to those of Python lists."""
340 340 if index<0:
341 341 index = self.nblocks + index
342 342 self._validate_index(index)
343 343 self.block_index = index
344 344 self.finished = False
345 345
346 346 def back(self,num=1):
347 347 """Move the seek pointer back num blocks (default is 1)."""
348 348 self.seek(self.block_index-num)
349 349
350 350 def jump(self,num=1):
351 351 """Jump a given number of blocks relative to the current one.
352 352
353 353 The offset can be positive or negative, defaults to 1."""
354 354 self.seek(self.block_index+num)
355 355
356 356 def again(self):
357 357 """Move the seek pointer back one block and re-execute."""
358 358 self.back(1)
359 359 self()
360 360
361 361 def edit(self,index=None):
362 362 """Edit a block.
363 363
364 364 If no number is given, use the last block executed.
365 365
366 366 This edits the in-memory copy of the demo, it does NOT modify the
367 367 original source file. If you want to do that, simply open the file in
368 368 an editor and use reload() when you make changes to the file. This
369 369 method is meant to let you change a block during a demonstration for
370 370 explanatory purposes, without damaging your original script."""
371 371
372 372 index = self._get_index(index)
373 373 if index is None:
374 374 return
375 375 # decrease the index by one (unless we're at the very beginning), so
376 376 # that the default demo.edit() call opens up the sblock we've last run
377 377 if index>0:
378 378 index -= 1
379 379
380 380 filename = self.shell.mktempfile(self.src_blocks[index])
381 381 self.shell.hooks.editor(filename,1)
382 382 with open(filename, 'r') as f:
383 383 new_block = f.read()
384 384 # update the source and colored block
385 385 self.src_blocks[index] = new_block
386 386 self.src_blocks_colored[index] = self.ip_colorize(new_block)
387 387 self.block_index = index
388 388 # call to run with the newly edited index
389 389 self()
390 390
391 391 def show(self,index=None):
392 392 """Show a single block on screen"""
393 393
394 394 index = self._get_index(index)
395 395 if index is None:
396 396 return
397 397
398 398 print(self.marquee('<%s> block # %s (%s remaining)' %
399 399 (self.title,index,self.nblocks-index-1)), file=io.stdout)
400 400 print((self.src_blocks_colored[index]), file=io.stdout)
401 401 sys.stdout.flush()
402 402
403 403 def show_all(self):
404 404 """Show entire demo on screen, block by block"""
405 405
406 406 fname = self.title
407 407 title = self.title
408 408 nblocks = self.nblocks
409 409 silent = self._silent
410 410 marquee = self.marquee
411 411 for index,block in enumerate(self.src_blocks_colored):
412 412 if silent[index]:
413 413 print(marquee('<%s> SILENT block # %s (%s remaining)' %
414 414 (title,index,nblocks-index-1)), file=io.stdout)
415 415 else:
416 416 print(marquee('<%s> block # %s (%s remaining)' %
417 417 (title,index,nblocks-index-1)), file=io.stdout)
418 418 print(block, end=' ', file=io.stdout)
419 419 sys.stdout.flush()
420 420
421 421 def run_cell(self,source):
422 422 """Execute a string with one or more lines of code"""
423 423
424 424 exec source in self.user_ns
425 425
426 426 def __call__(self,index=None):
427 427 """run a block of the demo.
428 428
429 429 If index is given, it should be an integer >=1 and <= nblocks. This
430 430 means that the calling convention is one off from typical Python
431 431 lists. The reason for the inconsistency is that the demo always
432 432 prints 'Block n/N, and N is the total, so it would be very odd to use
433 433 zero-indexing here."""
434 434
435 435 index = self._get_index(index)
436 436 if index is None:
437 437 return
438 438 try:
439 439 marquee = self.marquee
440 440 next_block = self.src_blocks[index]
441 441 self.block_index += 1
442 442 if self._silent[index]:
443 443 print(marquee('Executing silent block # %s (%s remaining)' %
444 444 (index,self.nblocks-index-1)), file=io.stdout)
445 445 else:
446 446 self.pre_cmd()
447 447 self.show(index)
448 448 if self.auto_all or self._auto[index]:
449 449 print(marquee('output:'), file=io.stdout)
450 450 else:
451 451 print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ', file=io.stdout)
452 452 ans = raw_input().strip()
453 453 if ans:
454 454 print(marquee('Block NOT executed'), file=io.stdout)
455 455 return
456 456 try:
457 457 save_argv = sys.argv
458 458 sys.argv = self.sys_argv
459 459 self.run_cell(next_block)
460 460 self.post_cmd()
461 461 finally:
462 462 sys.argv = save_argv
463 463
464 464 except:
465 465 self.ip_showtb(filename=self.fname)
466 466 else:
467 467 self.ip_ns.update(self.user_ns)
468 468
469 469 if self.block_index == self.nblocks:
470 470 mq1 = self.marquee('END OF DEMO')
471 471 if mq1:
472 472 # avoid spurious print >>io.stdout,s if empty marquees are used
473 473 print(file=io.stdout)
474 474 print(mq1, file=io.stdout)
475 475 print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'), file=io.stdout)
476 476 self.finished = True
477 477
478 478 # These methods are meant to be overridden by subclasses who may wish to
479 479 # customize the behavior of of their demos.
480 480 def marquee(self,txt='',width=78,mark='*'):
481 481 """Return the input string centered in a 'marquee'."""
482 482 return marquee(txt,width,mark)
483 483
484 484 def pre_cmd(self):
485 485 """Method called before executing each block."""
486 486 pass
487 487
488 488 def post_cmd(self):
489 489 """Method called after executing each block."""
490 490 pass
491 491
492 492
493 493 class IPythonDemo(Demo):
494 494 """Class for interactive demos with IPython's input processing applied.
495 495
496 496 This subclasses Demo, but instead of executing each block by the Python
497 497 interpreter (via exec), it actually calls IPython on it, so that any input
498 498 filters which may be in place are applied to the input block.
499 499
500 500 If you have an interactive environment which exposes special input
501 501 processing, you can use this class instead to write demo scripts which
502 502 operate exactly as if you had typed them interactively. The default Demo
503 503 class requires the input to be valid, pure Python code.
504 504 """
505 505
506 506 def run_cell(self,source):
507 507 """Execute a string with one or more lines of code"""
508 508
509 509 self.shell.run_cell(source)
510 510
511 511 class LineDemo(Demo):
512 512 """Demo where each line is executed as a separate block.
513 513
514 514 The input script should be valid Python code.
515 515
516 516 This class doesn't require any markup at all, and it's meant for simple
517 517 scripts (with no nesting or any kind of indentation) which consist of
518 518 multiple lines of input to be executed, one at a time, as if they had been
519 519 typed in the interactive prompt.
520 520
521 521 Note: the input can not have *any* indentation, which means that only
522 522 single-lines of input are accepted, not even function definitions are
523 523 valid."""
524 524
525 525 def reload(self):
526 526 """Reload source from disk and initialize state."""
527 527 # read data and parse into blocks
528 528 self.fload()
529 529 lines = self.fobj.readlines()
530 530 src_b = [l for l in lines if l.strip()]
531 531 nblocks = len(src_b)
532 532 self.src = ''.join(lines)
533 533 self._silent = [False]*nblocks
534 534 self._auto = [True]*nblocks
535 535 self.auto_all = True
536 536 self.nblocks = nblocks
537 537 self.src_blocks = src_b
538 538
539 539 # also build syntax-highlighted source
540 540 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
541 541
542 542 # ensure clean namespace and seek offset
543 543 self.reset()
544 544
545 545
546 546 class IPythonLineDemo(IPythonDemo,LineDemo):
547 547 """Variant of the LineDemo class whose input is processed by IPython."""
548 548 pass
549 549
550 550
551 551 class ClearMixin(object):
552 552 """Use this mixin to make Demo classes with less visual clutter.
553 553
554 554 Demos using this mixin will clear the screen before every block and use
555 555 blank marquees.
556 556
557 557 Note that in order for the methods defined here to actually override those
558 558 of the classes it's mixed with, it must go /first/ in the inheritance
559 559 tree. For example:
560 560
561 561 class ClearIPDemo(ClearMixin,IPythonDemo): pass
562 562
563 563 will provide an IPythonDemo class with the mixin's features.
564 564 """
565 565
566 566 def marquee(self,txt='',width=78,mark='*'):
567 567 """Blank marquee that returns '' no matter what the input."""
568 568 return ''
569 569
570 570 def pre_cmd(self):
571 571 """Method called before executing each block.
572 572
573 573 This one simply clears the screen."""
574 574 from IPython.utils.terminal import term_clear
575 575 term_clear()
576 576
577 577 class ClearDemo(ClearMixin,Demo):
578 578 pass
579 579
580 580
581 581 class ClearIPDemo(ClearMixin,IPythonDemo):
582 582 pass
@@ -1,445 +1,445 b''
1 1 #!/usr/bin/env python
2 2 """Module for interactively running scripts.
3 3
4 4 This module implements classes for interactively running scripts written for
5 5 any system with a prompt which can be matched by a regexp suitable for
6 6 pexpect. It can be used to run as if they had been typed up interactively, an
7 7 arbitrary series of commands for the target system.
8 8
9 9 The module includes classes ready for IPython (with the default prompts),
10 10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 11 simply run the module as a script:
12 12
13 13 ./irunner.py --help
14 14
15 15
16 16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 17 contributed on the ipython-user list:
18 18
19 19 http://mail.scipy.org/pipermail/ipython-user/2006-May/003539.html
20 20
21 21 Notes
22 22 -----
23 23
24 24 - This module requires pexpect, available in most linux distros, or which can
25 25 be downloaded from http://pexpect.sourceforge.net
26 26
27 27 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
28 28 limitations. This means that it will NOT work under native windows Python.
29 29 """
30 30 from __future__ import print_function
31 31
32 32 # Stdlib imports
33 33 import optparse
34 34 import os
35 35 import sys
36 36
37 37 # Third-party modules: we carry a copy of pexpect to reduce the need for
38 38 # external dependencies, but our import checks for a system version first.
39 39 from IPython.external import pexpect
40 40 from IPython.utils import py3compat
41 41
42 42 # Global usage strings, to avoid indentation issues when typing it below.
43 43 USAGE = """
44 44 Interactive script runner, type: %s
45 45
46 46 runner [opts] script_name
47 47 """
48 48
49 49 def pexpect_monkeypatch():
50 50 """Patch pexpect to prevent unhandled exceptions at VM teardown.
51 51
52 52 Calling this function will monkeypatch the pexpect.spawn class and modify
53 53 its __del__ method to make it more robust in the face of failures that can
54 54 occur if it is called when the Python VM is shutting down.
55 55
56 56 Since Python may fire __del__ methods arbitrarily late, it's possible for
57 57 them to execute during the teardown of the Python VM itself. At this
58 58 point, various builtin modules have been reset to None. Thus, the call to
59 59 self.close() will trigger an exception because it tries to call os.close(),
60 60 and os is now None.
61 61 """
62 62
63 63 if pexpect.__version__[:3] >= '2.2':
64 64 # No need to patch, fix is already the upstream version.
65 65 return
66 66
67 67 def __del__(self):
68 68 """This makes sure that no system resources are left open.
69 69 Python only garbage collects Python objects. OS file descriptors
70 70 are not Python objects, so they must be handled explicitly.
71 71 If the child file descriptor was opened outside of this class
72 72 (passed to the constructor) then this does not close it.
73 73 """
74 74 if not self.closed:
75 75 try:
76 76 self.close()
77 77 except AttributeError:
78 78 pass
79 79
80 80 pexpect.spawn.__del__ = __del__
81 81
82 82 pexpect_monkeypatch()
83 83
84 84 # The generic runner class
85 85 class InteractiveRunner(object):
86 86 """Class to run a sequence of commands through an interactive program."""
87 87
88 88 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
89 89 """Construct a runner.
90 90
91 91 Inputs:
92 92
93 93 - program: command to execute the given program.
94 94
95 95 - prompts: a list of patterns to match as valid prompts, in the
96 format used by pexpect. This basically means that it can be either
97 a string (to be compiled as a regular expression) or a list of such
98 (it must be a true list, as pexpect does type checks).
96 format used by pexpect. This basically means that it can be either
97 a string (to be compiled as a regular expression) or a list of such
98 (it must be a true list, as pexpect does type checks).
99 99
100 100 If more than one prompt is given, the first is treated as the main
101 101 program prompt and the others as 'continuation' prompts, like
102 102 python's. This means that blank lines in the input source are
103 103 ommitted when the first prompt is matched, but are NOT ommitted when
104 104 the continuation one matches, since this is how python signals the
105 105 end of multiline input interactively.
106 106
107 107 Optional inputs:
108 108
109 109 - args(None): optional list of strings to pass as arguments to the
110 child program.
110 child program.
111 111
112 112 - out(sys.stdout): if given, an output stream to be used when writing
113 output. The only requirement is that it must have a .write() method.
113 output. The only requirement is that it must have a .write() method.
114 114
115 115 Public members not parameterized in the constructor:
116 116
117 117 - delaybeforesend(0): Newer versions of pexpect have a delay before
118 sending each new input. For our purposes here, it's typically best
119 to just set this to zero, but if you encounter reliability problems
120 or want an interactive run to pause briefly at each prompt, just
121 increase this value (it is measured in seconds). Note that this
122 variable is not honored at all by older versions of pexpect.
118 sending each new input. For our purposes here, it's typically best
119 to just set this to zero, but if you encounter reliability problems
120 or want an interactive run to pause briefly at each prompt, just
121 increase this value (it is measured in seconds). Note that this
122 variable is not honored at all by older versions of pexpect.
123 123 """
124 124
125 125 self.program = program
126 126 self.prompts = prompts
127 127 if args is None: args = []
128 128 self.args = args
129 129 self.out = out
130 130 self.echo = echo
131 131 # Other public members which we don't make as parameters, but which
132 132 # users may occasionally want to tweak
133 133 self.delaybeforesend = 0
134 134
135 135 # Create child process and hold on to it so we don't have to re-create
136 136 # for every single execution call
137 137 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
138 138 c.delaybeforesend = self.delaybeforesend
139 139 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
140 140 # This causes problems because any line longer than 80 characters gets
141 141 # completely overwrapped on the printed outptut (even though
142 142 # internally the code runs fine). We reset this to 99 rows X 200
143 143 # columns (arbitrarily chosen), which should avoid problems in all
144 144 # reasonable cases.
145 145 c.setwinsize(99,200)
146 146
147 147 def close(self):
148 148 """close child process"""
149 149
150 150 self.child.close()
151 151
152 152 def run_file(self,fname,interact=False,get_output=False):
153 153 """Run the given file interactively.
154 154
155 155 Inputs:
156 156
157 -fname: name of the file to execute.
157 - fname: name of the file to execute.
158 158
159 159 See the run_source docstring for the meaning of the optional
160 160 arguments."""
161 161
162 162 fobj = open(fname,'r')
163 163 try:
164 164 out = self.run_source(fobj,interact,get_output)
165 165 finally:
166 166 fobj.close()
167 167 if get_output:
168 168 return out
169 169
170 170 def run_source(self,source,interact=False,get_output=False):
171 171 """Run the given source code interactively.
172 172
173 173 Inputs:
174 174
175 175 - source: a string of code to be executed, or an open file object we
176 can iterate over.
176 can iterate over.
177 177
178 178 Optional inputs:
179 179
180 180 - interact(False): if true, start to interact with the running
181 program at the end of the script. Otherwise, just exit.
181 program at the end of the script. Otherwise, just exit.
182 182
183 183 - get_output(False): if true, capture the output of the child process
184 (filtering the input commands out) and return it as a string.
184 (filtering the input commands out) and return it as a string.
185 185
186 186 Returns:
187 187 A string containing the process output, but only if requested.
188 188 """
189 189
190 190 # if the source is a string, chop it up in lines so we can iterate
191 191 # over it just as if it were an open file.
192 192 if isinstance(source, basestring):
193 193 source = source.splitlines(True)
194 194
195 195 if self.echo:
196 196 # normalize all strings we write to use the native OS line
197 197 # separators.
198 198 linesep = os.linesep
199 199 stdwrite = self.out.write
200 200 write = lambda s: stdwrite(s.replace('\r\n',linesep))
201 201 else:
202 202 # Quiet mode, all writes are no-ops
203 203 write = lambda s: None
204 204
205 205 c = self.child
206 206 prompts = c.compile_pattern_list(self.prompts)
207 207 prompt_idx = c.expect_list(prompts)
208 208
209 209 # Flag whether the script ends normally or not, to know whether we can
210 210 # do anything further with the underlying process.
211 211 end_normal = True
212 212
213 213 # If the output was requested, store it in a list for return at the end
214 214 if get_output:
215 215 output = []
216 216 store_output = output.append
217 217
218 218 for cmd in source:
219 219 # skip blank lines for all matches to the 'main' prompt, while the
220 220 # secondary prompts do not
221 221 if prompt_idx==0 and \
222 222 (cmd.isspace() or cmd.lstrip().startswith('#')):
223 223 write(cmd)
224 224 continue
225 225
226 226 # write('AFTER: '+c.after) # dbg
227 227 write(c.after)
228 228 c.send(cmd)
229 229 try:
230 230 prompt_idx = c.expect_list(prompts)
231 231 except pexpect.EOF:
232 232 # this will happen if the child dies unexpectedly
233 233 write(c.before)
234 234 end_normal = False
235 235 break
236 236
237 237 write(c.before)
238 238
239 239 # With an echoing process, the output we get in c.before contains
240 240 # the command sent, a newline, and then the actual process output
241 241 if get_output:
242 242 store_output(c.before[len(cmd+'\n'):])
243 243 #write('CMD: <<%s>>' % cmd) # dbg
244 244 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
245 245
246 246 self.out.flush()
247 247 if end_normal:
248 248 if interact:
249 249 c.send('\n')
250 250 print('<< Starting interactive mode >>', end=' ')
251 251 try:
252 252 c.interact()
253 253 except OSError:
254 254 # This is what fires when the child stops. Simply print a
255 255 # newline so the system prompt is aligned. The extra
256 256 # space is there to make sure it gets printed, otherwise
257 257 # OS buffering sometimes just suppresses it.
258 258 write(' \n')
259 259 self.out.flush()
260 260 else:
261 261 if interact:
262 262 e="Further interaction is not possible: child process is dead."
263 263 print(e, file=sys.stderr)
264 264
265 265 # Leave the child ready for more input later on, otherwise select just
266 266 # hangs on the second invocation.
267 267 if c.isalive():
268 268 c.send('\n')
269 269
270 270 # Return any requested output
271 271 if get_output:
272 272 return ''.join(output)
273 273
274 274 def main(self,argv=None):
275 275 """Run as a command-line script."""
276 276
277 277 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
278 278 newopt = parser.add_option
279 279 newopt('-i','--interact',action='store_true',default=False,
280 280 help='Interact with the program after the script is run.')
281 281
282 282 opts,args = parser.parse_args(argv)
283 283
284 284 if len(args) != 1:
285 285 print("You must supply exactly one file to run.", file=sys.stderr)
286 286 sys.exit(1)
287 287
288 288 self.run_file(args[0],opts.interact)
289 289
290 290
291 291 # Specific runners for particular programs
292 292 class IPythonRunner(InteractiveRunner):
293 293 """Interactive IPython runner.
294 294
295 295 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
296 296 avoid having to write a regexp that matches ANSI sequences, though pexpect
297 297 does support them. If anyone contributes patches for ANSI color support,
298 298 they will be welcome.
299 299
300 300 It also sets the prompts manually, since the prompt regexps for
301 301 pexpect need to be matched to the actual prompts, so user-customized
302 302 prompts would break this.
303 303 """
304 304
305 305 def __init__(self, program='<ipython>', args=None, out=sys.stdout, echo=True):
306 306 """New runner, optionally passing the ipython command to use."""
307 307 args0 = ['--colors=NoColor',
308 308 '--no-term-title',
309 309 '--no-autoindent',
310 310 # '--quick' is important, to prevent loading default config:
311 311 '--quick']
312 312 args = args0 + (args or [])
313 313
314 314 # Special case to launch IPython with current interpreter
315 315 if program == '<ipython>':
316 316 program = sys.executable
317 317 args = ['-m', 'IPython'] + args
318 318
319 319 prompts = [r'In \[\d+\]: ',r' \.*: ']
320 320 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
321 321
322 322
323 323 class PythonRunner(InteractiveRunner):
324 324 """Interactive Python runner."""
325 325
326 326 def __init__(self,program=sys.executable, args=None, out=sys.stdout, echo=True):
327 327 """New runner, optionally passing the python command to use."""
328 328
329 329 prompts = [r'>>> ',r'\.\.\. ']
330 330 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
331 331
332 332
333 333 class SAGERunner(InteractiveRunner):
334 334 """Interactive SAGE runner.
335 335
336 336 WARNING: this runner only works if you manually adjust your SAGE
337 337 configuration so that the 'color' option in the configuration file is set to
338 338 'NoColor', because currently the prompt matching regexp does not identify
339 339 color sequences."""
340 340
341 341 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
342 342 """New runner, optionally passing the sage command to use."""
343 343
344 344 prompts = ['sage: ',r'\s*\.\.\. ']
345 345 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
346 346
347 347
348 348 class RunnerFactory(object):
349 349 """Code runner factory.
350 350
351 351 This class provides an IPython code runner, but enforces that only one
352 352 runner is ever instantiated. The runner is created based on the extension
353 353 of the first file to run, and it raises an exception if a runner is later
354 354 requested for a different extension type.
355 355
356 356 This ensures that we don't generate example files for doctest with a mix of
357 357 python and ipython syntax.
358 358 """
359 359
360 360 def __init__(self,out=sys.stdout):
361 361 """Instantiate a code runner."""
362 362
363 363 self.out = out
364 364 self.runner = None
365 365 self.runnerClass = None
366 366
367 367 def _makeRunner(self,runnerClass):
368 368 self.runnerClass = runnerClass
369 369 self.runner = runnerClass(out=self.out)
370 370 return self.runner
371 371
372 372 def __call__(self,fname):
373 373 """Return a runner for the given filename."""
374 374
375 375 if fname.endswith('.py'):
376 376 runnerClass = PythonRunner
377 377 elif fname.endswith('.ipy'):
378 378 runnerClass = IPythonRunner
379 379 else:
380 380 raise ValueError('Unknown file type for Runner: %r' % fname)
381 381
382 382 if self.runner is None:
383 383 return self._makeRunner(runnerClass)
384 384 else:
385 385 if runnerClass==self.runnerClass:
386 386 return self.runner
387 387 else:
388 388 e='A runner of type %r can not run file %r' % \
389 389 (self.runnerClass,fname)
390 390 raise ValueError(e)
391 391
392 392
393 393 # Global usage string, to avoid indentation issues if typed in a function def.
394 394 MAIN_USAGE = """
395 395 %prog [options] file_to_run
396 396
397 397 This is an interface to the various interactive runners available in this
398 398 module. If you want to pass specific options to one of the runners, you need
399 399 to first terminate the main options with a '--', and then provide the runner's
400 400 options. For example:
401 401
402 402 irunner.py --python -- --help
403 403
404 404 will pass --help to the python runner. Similarly,
405 405
406 406 irunner.py --ipython -- --interact script.ipy
407 407
408 408 will run the script.ipy file under the IPython runner, and then will start to
409 409 interact with IPython at the end of the script (instead of exiting).
410 410
411 411 The already implemented runners are listed below; adding one for a new program
412 412 is a trivial task, see the source for examples.
413 413 """
414 414
415 415 def main():
416 416 """Run as a command-line script."""
417 417
418 418 parser = optparse.OptionParser(usage=MAIN_USAGE)
419 419 newopt = parser.add_option
420 420 newopt('--ipython',action='store_const',dest='mode',const='ipython',
421 421 help='IPython interactive runner (default).')
422 422 newopt('--python',action='store_const',dest='mode',const='python',
423 423 help='Python interactive runner.')
424 424 newopt('--sage',action='store_const',dest='mode',const='sage',
425 425 help='SAGE interactive runner.')
426 426
427 427 opts,args = parser.parse_args()
428 428 runners = dict(ipython=IPythonRunner,
429 429 python=PythonRunner,
430 430 sage=SAGERunner)
431 431
432 432 try:
433 433 ext = os.path.splitext(args[0])[-1]
434 434 except IndexError:
435 435 ext = ''
436 436 modes = {'.ipy':'ipython',
437 437 '.py':'python',
438 438 '.sage':'sage'}
439 439 mode = modes.get(ext,"ipython")
440 440 if opts.mode:
441 441 mode = opts.mode
442 442 runners[mode]().main(args)
443 443
444 444 if __name__ == '__main__':
445 445 main()
@@ -1,75 +1,76 b''
1 1 """Module that allows latex output notebooks to be conditioned before
2 2 they are converted. Exposes a decorator (@cell_preprocessor) in
3 3 addition to the coalesce_streams pre-proccessor.
4 4 """
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (c) 2013, the IPython Development Team.
7 7 #
8 8 # Distributed under the terms of the Modified BSD License.
9 9 #
10 10 # The full license is in the file COPYING.txt, distributed with this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Functions
15 15 #-----------------------------------------------------------------------------
16 16
17 17 def cell_preprocessor(function):
18 18 """
19 19 Wrap a function to be executed on all cells of a notebook
20 20
21 21 Wrapped Parameters
22 ----------
22 ------------------
23
23 24 cell : NotebookNode cell
24 25 Notebook cell being processed
25 26 resources : dictionary
26 27 Additional resources used in the conversion process. Allows
27 28 preprocessors to pass variables into the Jinja engine.
28 29 index : int
29 30 Index of the cell being processed
30 31 """
31 32
32 33 def wrappedfunc(nb, resources):
33 34 for worksheet in nb.worksheets :
34 35 for index, cell in enumerate(worksheet.cells):
35 36 worksheet.cells[index], resources = function(cell, resources, index)
36 37 return nb, resources
37 38 return wrappedfunc
38 39
39 40
40 41 @cell_preprocessor
41 42 def coalesce_streams(cell, resources, index):
42 43 """
43 44 Merge consecutive sequences of stream output into single stream
44 45 to prevent extra newlines inserted at flush calls
45 46
46 47 Parameters
47 48 ----------
48 49 cell : NotebookNode cell
49 50 Notebook cell being processed
50 51 resources : dictionary
51 52 Additional resources used in the conversion process. Allows
52 53 transformers to pass variables into the Jinja engine.
53 54 index : int
54 55 Index of the cell being processed
55 56 """
56 57
57 58 outputs = cell.get('outputs', [])
58 59 if not outputs:
59 60 return cell, resources
60 61
61 62 last = outputs[0]
62 63 new_outputs = [last]
63 64
64 65 for output in outputs[1:]:
65 66 if (output.output_type == 'stream' and
66 67 last.output_type == 'stream' and
67 68 last.stream == output.stream
68 69 ):
69 70 last.text += output.text
70 71 else:
71 72 new_outputs.append(output)
72 73 last = output
73 74
74 75 cell.outputs = new_outputs
75 76 return cell, resources
@@ -1,187 +1,187 b''
1 1 """Windows-specific implementation of process utilities.
2 2
3 3 This file is only meant to be imported by process.py, not by end-users.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010-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 from __future__ import print_function
17 17
18 18 # stdlib
19 19 import os
20 20 import sys
21 21 import ctypes
22 22
23 23 from ctypes import c_int, POINTER
24 24 from ctypes.wintypes import LPCWSTR, HLOCAL
25 25 from subprocess import STDOUT
26 26
27 27 # our own imports
28 28 from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split
29 29 from . import py3compat
30 30 from .encoding import DEFAULT_ENCODING
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Function definitions
34 34 #-----------------------------------------------------------------------------
35 35
36 36 class AvoidUNCPath(object):
37 37 """A context manager to protect command execution from UNC paths.
38 38
39 39 In the Win32 API, commands can't be invoked with the cwd being a UNC path.
40 40 This context manager temporarily changes directory to the 'C:' drive on
41 41 entering, and restores the original working directory on exit.
42 42
43 43 The context manager returns the starting working directory *if* it made a
44 44 change and None otherwise, so that users can apply the necessary adjustment
45 45 to their system calls in the event of a change.
46 46
47 Example
48 -------
47 Examples
48 --------
49 49 ::
50 50 cmd = 'dir'
51 51 with AvoidUNCPath() as path:
52 52 if path is not None:
53 53 cmd = '"pushd %s &&"%s' % (path, cmd)
54 54 os.system(cmd)
55 55 """
56 56 def __enter__(self):
57 57 self.path = os.getcwdu()
58 58 self.is_unc_path = self.path.startswith(r"\\")
59 59 if self.is_unc_path:
60 60 # change to c drive (as cmd.exe cannot handle UNC addresses)
61 61 os.chdir("C:")
62 62 return self.path
63 63 else:
64 64 # We return None to signal that there was no change in the working
65 65 # directory
66 66 return None
67 67
68 68 def __exit__(self, exc_type, exc_value, traceback):
69 69 if self.is_unc_path:
70 70 os.chdir(self.path)
71 71
72 72
73 73 def _find_cmd(cmd):
74 74 """Find the full path to a .bat or .exe using the win32api module."""
75 75 try:
76 76 from win32api import SearchPath
77 77 except ImportError:
78 78 raise ImportError('you need to have pywin32 installed for this to work')
79 79 else:
80 80 PATH = os.environ['PATH']
81 81 extensions = ['.exe', '.com', '.bat', '.py']
82 82 path = None
83 83 for ext in extensions:
84 84 try:
85 85 path = SearchPath(PATH, cmd, ext)[0]
86 86 except:
87 87 pass
88 88 if path is None:
89 89 raise OSError("command %r not found" % cmd)
90 90 else:
91 91 return path
92 92
93 93
94 94 def _system_body(p):
95 95 """Callback for _system."""
96 96 enc = DEFAULT_ENCODING
97 97 for line in read_no_interrupt(p.stdout).splitlines():
98 98 line = line.decode(enc, 'replace')
99 99 print(line, file=sys.stdout)
100 100 for line in read_no_interrupt(p.stderr).splitlines():
101 101 line = line.decode(enc, 'replace')
102 102 print(line, file=sys.stderr)
103 103
104 104 # Wait to finish for returncode
105 105 return p.wait()
106 106
107 107
108 108 def system(cmd):
109 109 """Win32 version of os.system() that works with network shares.
110 110
111 111 Note that this implementation returns None, as meant for use in IPython.
112 112
113 113 Parameters
114 114 ----------
115 115 cmd : str
116 116 A command to be executed in the system shell.
117 117
118 118 Returns
119 119 -------
120 120 None : we explicitly do NOT return the subprocess status code, as this
121 121 utility is meant to be used extensively in IPython, where any return value
122 122 would trigger :func:`sys.displayhook` calls.
123 123 """
124 124 # The controller provides interactivity with both
125 125 # stdin and stdout
126 126 #import _process_win32_controller
127 127 #_process_win32_controller.system(cmd)
128 128
129 129 with AvoidUNCPath() as path:
130 130 if path is not None:
131 131 cmd = '"pushd %s &&"%s' % (path, cmd)
132 132 return process_handler(cmd, _system_body)
133 133
134 134 def getoutput(cmd):
135 135 """Return standard output of executing cmd in a shell.
136 136
137 137 Accepts the same arguments as os.system().
138 138
139 139 Parameters
140 140 ----------
141 141 cmd : str
142 142 A command to be executed in the system shell.
143 143
144 144 Returns
145 145 -------
146 146 stdout : str
147 147 """
148 148
149 149 with AvoidUNCPath() as path:
150 150 if path is not None:
151 151 cmd = '"pushd %s &&"%s' % (path, cmd)
152 152 out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
153 153
154 154 if out is None:
155 155 out = b''
156 156 return py3compat.bytes_to_str(out)
157 157
158 158 try:
159 159 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
160 160 CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)]
161 161 CommandLineToArgvW.restype = POINTER(LPCWSTR)
162 162 LocalFree = ctypes.windll.kernel32.LocalFree
163 163 LocalFree.res_type = HLOCAL
164 164 LocalFree.arg_types = [HLOCAL]
165 165
166 166 def arg_split(commandline, posix=False, strict=True):
167 167 """Split a command line's arguments in a shell-like manner.
168 168
169 169 This is a special version for windows that use a ctypes call to CommandLineToArgvW
170 170 to do the argv splitting. The posix paramter is ignored.
171 171
172 172 If strict=False, process_common.arg_split(...strict=False) is used instead.
173 173 """
174 174 #CommandLineToArgvW returns path to executable if called with empty string.
175 175 if commandline.strip() == "":
176 176 return []
177 177 if not strict:
178 178 # not really a cl-arg, fallback on _process_common
179 179 return py_arg_split(commandline, posix=posix, strict=strict)
180 180 argvn = c_int()
181 181 result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
182 182 result_array_type = LPCWSTR * argvn.value
183 183 result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))]
184 184 retval = LocalFree(result_pointer)
185 185 return result
186 186 except AttributeError:
187 187 arg_split = py_arg_split
@@ -1,574 +1,574 b''
1 1 """Windows-specific implementation of process utilities with direct WinAPI.
2 2
3 3 This file is meant to be used by process.py
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010-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 from __future__ import print_function
14 14
15 15 # stdlib
16 16 import os, sys, threading
17 17 import ctypes, msvcrt
18 18
19 19 # Win32 API types needed for the API calls
20 20 from ctypes import POINTER
21 21 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
22 22 ULONG, LPCWSTR
23 23 LPDWORD = POINTER(DWORD)
24 24 LPHANDLE = POINTER(HANDLE)
25 25 ULONG_PTR = POINTER(ULONG)
26 26 class SECURITY_ATTRIBUTES(ctypes.Structure):
27 27 _fields_ = [("nLength", DWORD),
28 28 ("lpSecurityDescriptor", LPVOID),
29 29 ("bInheritHandle", BOOL)]
30 30 LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES)
31 31 class STARTUPINFO(ctypes.Structure):
32 32 _fields_ = [("cb", DWORD),
33 33 ("lpReserved", LPCWSTR),
34 34 ("lpDesktop", LPCWSTR),
35 35 ("lpTitle", LPCWSTR),
36 36 ("dwX", DWORD),
37 37 ("dwY", DWORD),
38 38 ("dwXSize", DWORD),
39 39 ("dwYSize", DWORD),
40 40 ("dwXCountChars", DWORD),
41 41 ("dwYCountChars", DWORD),
42 42 ("dwFillAttribute", DWORD),
43 43 ("dwFlags", DWORD),
44 44 ("wShowWindow", WORD),
45 45 ("cbReserved2", WORD),
46 46 ("lpReserved2", LPVOID),
47 47 ("hStdInput", HANDLE),
48 48 ("hStdOutput", HANDLE),
49 49 ("hStdError", HANDLE)]
50 50 LPSTARTUPINFO = POINTER(STARTUPINFO)
51 51 class PROCESS_INFORMATION(ctypes.Structure):
52 52 _fields_ = [("hProcess", HANDLE),
53 53 ("hThread", HANDLE),
54 54 ("dwProcessId", DWORD),
55 55 ("dwThreadId", DWORD)]
56 56 LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
57 57
58 58 # Win32 API constants needed
59 59 ERROR_HANDLE_EOF = 38
60 60 ERROR_BROKEN_PIPE = 109
61 61 ERROR_NO_DATA = 232
62 62 HANDLE_FLAG_INHERIT = 0x0001
63 63 STARTF_USESTDHANDLES = 0x0100
64 64 CREATE_SUSPENDED = 0x0004
65 65 CREATE_NEW_CONSOLE = 0x0010
66 66 CREATE_NO_WINDOW = 0x08000000
67 67 STILL_ACTIVE = 259
68 68 WAIT_TIMEOUT = 0x0102
69 69 WAIT_FAILED = 0xFFFFFFFF
70 70 INFINITE = 0xFFFFFFFF
71 71 DUPLICATE_SAME_ACCESS = 0x00000002
72 72 ENABLE_ECHO_INPUT = 0x0004
73 73 ENABLE_LINE_INPUT = 0x0002
74 74 ENABLE_PROCESSED_INPUT = 0x0001
75 75
76 76 # Win32 API functions needed
77 77 GetLastError = ctypes.windll.kernel32.GetLastError
78 78 GetLastError.argtypes = []
79 79 GetLastError.restype = DWORD
80 80
81 81 CreateFile = ctypes.windll.kernel32.CreateFileW
82 82 CreateFile.argtypes = [LPCWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
83 83 CreateFile.restype = HANDLE
84 84
85 85 CreatePipe = ctypes.windll.kernel32.CreatePipe
86 86 CreatePipe.argtypes = [POINTER(HANDLE), POINTER(HANDLE),
87 87 LPSECURITY_ATTRIBUTES, DWORD]
88 88 CreatePipe.restype = BOOL
89 89
90 90 CreateProcess = ctypes.windll.kernel32.CreateProcessW
91 91 CreateProcess.argtypes = [LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES,
92 92 LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFO,
93 93 LPPROCESS_INFORMATION]
94 94 CreateProcess.restype = BOOL
95 95
96 96 GetExitCodeProcess = ctypes.windll.kernel32.GetExitCodeProcess
97 97 GetExitCodeProcess.argtypes = [HANDLE, LPDWORD]
98 98 GetExitCodeProcess.restype = BOOL
99 99
100 100 GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
101 101 GetCurrentProcess.argtypes = []
102 102 GetCurrentProcess.restype = HANDLE
103 103
104 104 ResumeThread = ctypes.windll.kernel32.ResumeThread
105 105 ResumeThread.argtypes = [HANDLE]
106 106 ResumeThread.restype = DWORD
107 107
108 108 ReadFile = ctypes.windll.kernel32.ReadFile
109 109 ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPVOID]
110 110 ReadFile.restype = BOOL
111 111
112 112 WriteFile = ctypes.windll.kernel32.WriteFile
113 113 WriteFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPVOID]
114 114 WriteFile.restype = BOOL
115 115
116 116 GetConsoleMode = ctypes.windll.kernel32.GetConsoleMode
117 117 GetConsoleMode.argtypes = [HANDLE, LPDWORD]
118 118 GetConsoleMode.restype = BOOL
119 119
120 120 SetConsoleMode = ctypes.windll.kernel32.SetConsoleMode
121 121 SetConsoleMode.argtypes = [HANDLE, DWORD]
122 122 SetConsoleMode.restype = BOOL
123 123
124 124 FlushConsoleInputBuffer = ctypes.windll.kernel32.FlushConsoleInputBuffer
125 125 FlushConsoleInputBuffer.argtypes = [HANDLE]
126 126 FlushConsoleInputBuffer.restype = BOOL
127 127
128 128 WaitForSingleObject = ctypes.windll.kernel32.WaitForSingleObject
129 129 WaitForSingleObject.argtypes = [HANDLE, DWORD]
130 130 WaitForSingleObject.restype = DWORD
131 131
132 132 DuplicateHandle = ctypes.windll.kernel32.DuplicateHandle
133 133 DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPHANDLE,
134 134 DWORD, BOOL, DWORD]
135 135 DuplicateHandle.restype = BOOL
136 136
137 137 SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation
138 138 SetHandleInformation.argtypes = [HANDLE, DWORD, DWORD]
139 139 SetHandleInformation.restype = BOOL
140 140
141 141 CloseHandle = ctypes.windll.kernel32.CloseHandle
142 142 CloseHandle.argtypes = [HANDLE]
143 143 CloseHandle.restype = BOOL
144 144
145 145 CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
146 146 CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(ctypes.c_int)]
147 147 CommandLineToArgvW.restype = POINTER(LPCWSTR)
148 148
149 149 LocalFree = ctypes.windll.kernel32.LocalFree
150 150 LocalFree.argtypes = [HLOCAL]
151 151 LocalFree.restype = HLOCAL
152 152
153 153 class AvoidUNCPath(object):
154 154 """A context manager to protect command execution from UNC paths.
155 155
156 156 In the Win32 API, commands can't be invoked with the cwd being a UNC path.
157 157 This context manager temporarily changes directory to the 'C:' drive on
158 158 entering, and restores the original working directory on exit.
159 159
160 160 The context manager returns the starting working directory *if* it made a
161 161 change and None otherwise, so that users can apply the necessary adjustment
162 162 to their system calls in the event of a change.
163 163
164 Example
165 -------
164 Examples
165 --------
166 166 ::
167 167 cmd = 'dir'
168 168 with AvoidUNCPath() as path:
169 169 if path is not None:
170 170 cmd = '"pushd %s &&"%s' % (path, cmd)
171 171 os.system(cmd)
172 172 """
173 173 def __enter__(self):
174 174 self.path = os.getcwdu()
175 175 self.is_unc_path = self.path.startswith(r"\\")
176 176 if self.is_unc_path:
177 177 # change to c drive (as cmd.exe cannot handle UNC addresses)
178 178 os.chdir("C:")
179 179 return self.path
180 180 else:
181 181 # We return None to signal that there was no change in the working
182 182 # directory
183 183 return None
184 184
185 185 def __exit__(self, exc_type, exc_value, traceback):
186 186 if self.is_unc_path:
187 187 os.chdir(self.path)
188 188
189 189
190 190 class Win32ShellCommandController(object):
191 191 """Runs a shell command in a 'with' context.
192 192
193 193 This implementation is Win32-specific.
194 194
195 195 Example:
196 196 # Runs the command interactively with default console stdin/stdout
197 197 with ShellCommandController('python -i') as scc:
198 198 scc.run()
199 199
200 200 # Runs the command using the provided functions for stdin/stdout
201 201 def my_stdout_func(s):
202 202 # print or save the string 's'
203 203 write_to_stdout(s)
204 204 def my_stdin_func():
205 205 # If input is available, return it as a string.
206 206 if input_available():
207 207 return get_input()
208 208 # If no input available, return None after a short delay to
209 209 # keep from blocking.
210 210 else:
211 211 time.sleep(0.01)
212 212 return None
213 213
214 214 with ShellCommandController('python -i') as scc:
215 215 scc.run(my_stdout_func, my_stdin_func)
216 216 """
217 217
218 218 def __init__(self, cmd, mergeout = True):
219 219 """Initializes the shell command controller.
220 220
221 221 The cmd is the program to execute, and mergeout is
222 222 whether to blend stdout and stderr into one output
223 223 in stdout. Merging them together in this fashion more
224 224 reliably keeps stdout and stderr in the correct order
225 225 especially for interactive shell usage.
226 226 """
227 227 self.cmd = cmd
228 228 self.mergeout = mergeout
229 229
230 230 def __enter__(self):
231 231 cmd = self.cmd
232 232 mergeout = self.mergeout
233 233
234 234 self.hstdout, self.hstdin, self.hstderr = None, None, None
235 235 self.piProcInfo = None
236 236 try:
237 237 p_hstdout, c_hstdout, p_hstderr, \
238 238 c_hstderr, p_hstdin, c_hstdin = [None]*6
239 239
240 240 # SECURITY_ATTRIBUTES with inherit handle set to True
241 241 saAttr = SECURITY_ATTRIBUTES()
242 242 saAttr.nLength = ctypes.sizeof(saAttr)
243 243 saAttr.bInheritHandle = True
244 244 saAttr.lpSecurityDescriptor = None
245 245
246 246 def create_pipe(uninherit):
247 247 """Creates a Windows pipe, which consists of two handles.
248 248
249 249 The 'uninherit' parameter controls which handle is not
250 250 inherited by the child process.
251 251 """
252 252 handles = HANDLE(), HANDLE()
253 253 if not CreatePipe(ctypes.byref(handles[0]),
254 254 ctypes.byref(handles[1]), ctypes.byref(saAttr), 0):
255 255 raise ctypes.WinError()
256 256 if not SetHandleInformation(handles[uninherit],
257 257 HANDLE_FLAG_INHERIT, 0):
258 258 raise ctypes.WinError()
259 259 return handles[0].value, handles[1].value
260 260
261 261 p_hstdout, c_hstdout = create_pipe(uninherit=0)
262 262 # 'mergeout' signals that stdout and stderr should be merged.
263 263 # We do that by using one pipe for both of them.
264 264 if mergeout:
265 265 c_hstderr = HANDLE()
266 266 if not DuplicateHandle(GetCurrentProcess(), c_hstdout,
267 267 GetCurrentProcess(), ctypes.byref(c_hstderr),
268 268 0, True, DUPLICATE_SAME_ACCESS):
269 269 raise ctypes.WinError()
270 270 else:
271 271 p_hstderr, c_hstderr = create_pipe(uninherit=0)
272 272 c_hstdin, p_hstdin = create_pipe(uninherit=1)
273 273
274 274 # Create the process object
275 275 piProcInfo = PROCESS_INFORMATION()
276 276 siStartInfo = STARTUPINFO()
277 277 siStartInfo.cb = ctypes.sizeof(siStartInfo)
278 278 siStartInfo.hStdInput = c_hstdin
279 279 siStartInfo.hStdOutput = c_hstdout
280 280 siStartInfo.hStdError = c_hstderr
281 281 siStartInfo.dwFlags = STARTF_USESTDHANDLES
282 282 dwCreationFlags = CREATE_SUSPENDED | CREATE_NO_WINDOW # | CREATE_NEW_CONSOLE
283 283
284 284 if not CreateProcess(None,
285 285 u"cmd.exe /c " + cmd,
286 286 None, None, True, dwCreationFlags,
287 287 None, None, ctypes.byref(siStartInfo),
288 288 ctypes.byref(piProcInfo)):
289 289 raise ctypes.WinError()
290 290
291 291 # Close this process's versions of the child handles
292 292 CloseHandle(c_hstdin)
293 293 c_hstdin = None
294 294 CloseHandle(c_hstdout)
295 295 c_hstdout = None
296 296 if c_hstderr != None:
297 297 CloseHandle(c_hstderr)
298 298 c_hstderr = None
299 299
300 300 # Transfer ownership of the parent handles to the object
301 301 self.hstdin = p_hstdin
302 302 p_hstdin = None
303 303 self.hstdout = p_hstdout
304 304 p_hstdout = None
305 305 if not mergeout:
306 306 self.hstderr = p_hstderr
307 307 p_hstderr = None
308 308 self.piProcInfo = piProcInfo
309 309
310 310 finally:
311 311 if p_hstdin:
312 312 CloseHandle(p_hstdin)
313 313 if c_hstdin:
314 314 CloseHandle(c_hstdin)
315 315 if p_hstdout:
316 316 CloseHandle(p_hstdout)
317 317 if c_hstdout:
318 318 CloseHandle(c_hstdout)
319 319 if p_hstderr:
320 320 CloseHandle(p_hstderr)
321 321 if c_hstderr:
322 322 CloseHandle(c_hstderr)
323 323
324 324 return self
325 325
326 326 def _stdin_thread(self, handle, hprocess, func, stdout_func):
327 327 exitCode = DWORD()
328 328 bytesWritten = DWORD(0)
329 329 while True:
330 330 #print("stdin thread loop start")
331 331 # Get the input string (may be bytes or unicode)
332 332 data = func()
333 333
334 334 # None signals to poll whether the process has exited
335 335 if data is None:
336 336 #print("checking for process completion")
337 337 if not GetExitCodeProcess(hprocess, ctypes.byref(exitCode)):
338 338 raise ctypes.WinError()
339 339 if exitCode.value != STILL_ACTIVE:
340 340 return
341 341 # TESTING: Does zero-sized writefile help?
342 342 if not WriteFile(handle, "", 0,
343 343 ctypes.byref(bytesWritten), None):
344 344 raise ctypes.WinError()
345 345 continue
346 346 #print("\nGot str %s\n" % repr(data), file=sys.stderr)
347 347
348 348 # Encode the string to the console encoding
349 349 if isinstance(data, unicode): #FIXME: Python3
350 350 data = data.encode('utf_8')
351 351
352 352 # What we have now must be a string of bytes
353 353 if not isinstance(data, str): #FIXME: Python3
354 354 raise RuntimeError("internal stdin function string error")
355 355
356 356 # An empty string signals EOF
357 357 if len(data) == 0:
358 358 return
359 359
360 360 # In a windows console, sometimes the input is echoed,
361 361 # but sometimes not. How do we determine when to do this?
362 362 stdout_func(data)
363 363 # WriteFile may not accept all the data at once.
364 364 # Loop until everything is processed
365 365 while len(data) != 0:
366 366 #print("Calling writefile")
367 367 if not WriteFile(handle, data, len(data),
368 368 ctypes.byref(bytesWritten), None):
369 369 # This occurs at exit
370 370 if GetLastError() == ERROR_NO_DATA:
371 371 return
372 372 raise ctypes.WinError()
373 373 #print("Called writefile")
374 374 data = data[bytesWritten.value:]
375 375
376 376 def _stdout_thread(self, handle, func):
377 377 # Allocate the output buffer
378 378 data = ctypes.create_string_buffer(4096)
379 379 while True:
380 380 bytesRead = DWORD(0)
381 381 if not ReadFile(handle, data, 4096,
382 382 ctypes.byref(bytesRead), None):
383 383 le = GetLastError()
384 384 if le == ERROR_BROKEN_PIPE:
385 385 return
386 386 else:
387 387 raise ctypes.WinError()
388 388 # FIXME: Python3
389 389 s = data.value[0:bytesRead.value]
390 390 #print("\nv: %s" % repr(s), file=sys.stderr)
391 391 func(s.decode('utf_8', 'replace'))
392 392
393 393 def run(self, stdout_func = None, stdin_func = None, stderr_func = None):
394 394 """Runs the process, using the provided functions for I/O.
395 395
396 396 The function stdin_func should return strings whenever a
397 397 character or characters become available.
398 398 The functions stdout_func and stderr_func are called whenever
399 399 something is printed to stdout or stderr, respectively.
400 400 These functions are called from different threads (but not
401 401 concurrently, because of the GIL).
402 402 """
403 403 if stdout_func == None and stdin_func == None and stderr_func == None:
404 404 return self._run_stdio()
405 405
406 406 if stderr_func != None and self.mergeout:
407 407 raise RuntimeError("Shell command was initiated with "
408 408 "merged stdin/stdout, but a separate stderr_func "
409 409 "was provided to the run() method")
410 410
411 411 # Create a thread for each input/output handle
412 412 stdin_thread = None
413 413 threads = []
414 414 if stdin_func:
415 415 stdin_thread = threading.Thread(target=self._stdin_thread,
416 416 args=(self.hstdin, self.piProcInfo.hProcess,
417 417 stdin_func, stdout_func))
418 418 threads.append(threading.Thread(target=self._stdout_thread,
419 419 args=(self.hstdout, stdout_func)))
420 420 if not self.mergeout:
421 421 if stderr_func == None:
422 422 stderr_func = stdout_func
423 423 threads.append(threading.Thread(target=self._stdout_thread,
424 424 args=(self.hstderr, stderr_func)))
425 425 # Start the I/O threads and the process
426 426 if ResumeThread(self.piProcInfo.hThread) == 0xFFFFFFFF:
427 427 raise ctypes.WinError()
428 428 if stdin_thread is not None:
429 429 stdin_thread.start()
430 430 for thread in threads:
431 431 thread.start()
432 432 # Wait for the process to complete
433 433 if WaitForSingleObject(self.piProcInfo.hProcess, INFINITE) == \
434 434 WAIT_FAILED:
435 435 raise ctypes.WinError()
436 436 # Wait for the I/O threads to complete
437 437 for thread in threads:
438 438 thread.join()
439 439
440 440 # Wait for the stdin thread to complete
441 441 if stdin_thread is not None:
442 442 stdin_thread.join()
443 443
444 444 def _stdin_raw_nonblock(self):
445 445 """Use the raw Win32 handle of sys.stdin to do non-blocking reads"""
446 446 # WARNING: This is experimental, and produces inconsistent results.
447 447 # It's possible for the handle not to be appropriate for use
448 448 # with WaitForSingleObject, among other things.
449 449 handle = msvcrt.get_osfhandle(sys.stdin.fileno())
450 450 result = WaitForSingleObject(handle, 100)
451 451 if result == WAIT_FAILED:
452 452 raise ctypes.WinError()
453 453 elif result == WAIT_TIMEOUT:
454 454 print(".", end='')
455 455 return None
456 456 else:
457 457 data = ctypes.create_string_buffer(256)
458 458 bytesRead = DWORD(0)
459 459 print('?', end='')
460 460
461 461 if not ReadFile(handle, data, 256,
462 462 ctypes.byref(bytesRead), None):
463 463 raise ctypes.WinError()
464 464 # This ensures the non-blocking works with an actual console
465 465 # Not checking the error, so the processing will still work with
466 466 # other handle types
467 467 FlushConsoleInputBuffer(handle)
468 468
469 469 data = data.value
470 470 data = data.replace('\r\n', '\n')
471 471 data = data.replace('\r', '\n')
472 472 print(repr(data) + " ", end='')
473 473 return data
474 474
475 475 def _stdin_raw_block(self):
476 476 """Use a blocking stdin read"""
477 477 # The big problem with the blocking read is that it doesn't
478 478 # exit when it's supposed to in all contexts. An extra
479 479 # key-press may be required to trigger the exit.
480 480 try:
481 481 data = sys.stdin.read(1)
482 482 data = data.replace('\r', '\n')
483 483 return data
484 484 except WindowsError as we:
485 485 if we.winerror == ERROR_NO_DATA:
486 486 # This error occurs when the pipe is closed
487 487 return None
488 488 else:
489 489 # Otherwise let the error propagate
490 490 raise we
491 491
492 492 def _stdout_raw(self, s):
493 493 """Writes the string to stdout"""
494 494 print(s, end='', file=sys.stdout)
495 495 sys.stdout.flush()
496 496
497 497 def _stderr_raw(self, s):
498 498 """Writes the string to stdout"""
499 499 print(s, end='', file=sys.stderr)
500 500 sys.stderr.flush()
501 501
502 502 def _run_stdio(self):
503 503 """Runs the process using the system standard I/O.
504 504
505 505 IMPORTANT: stdin needs to be asynchronous, so the Python
506 506 sys.stdin object is not used. Instead,
507 507 msvcrt.kbhit/getwch are used asynchronously.
508 508 """
509 509 # Disable Line and Echo mode
510 510 #lpMode = DWORD()
511 511 #handle = msvcrt.get_osfhandle(sys.stdin.fileno())
512 512 #if GetConsoleMode(handle, ctypes.byref(lpMode)):
513 513 # set_console_mode = True
514 514 # if not SetConsoleMode(handle, lpMode.value &
515 515 # ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT)):
516 516 # raise ctypes.WinError()
517 517
518 518 if self.mergeout:
519 519 return self.run(stdout_func = self._stdout_raw,
520 520 stdin_func = self._stdin_raw_block)
521 521 else:
522 522 return self.run(stdout_func = self._stdout_raw,
523 523 stdin_func = self._stdin_raw_block,
524 524 stderr_func = self._stderr_raw)
525 525
526 526 # Restore the previous console mode
527 527 #if set_console_mode:
528 528 # if not SetConsoleMode(handle, lpMode.value):
529 529 # raise ctypes.WinError()
530 530
531 531 def __exit__(self, exc_type, exc_value, traceback):
532 532 if self.hstdin:
533 533 CloseHandle(self.hstdin)
534 534 self.hstdin = None
535 535 if self.hstdout:
536 536 CloseHandle(self.hstdout)
537 537 self.hstdout = None
538 538 if self.hstderr:
539 539 CloseHandle(self.hstderr)
540 540 self.hstderr = None
541 541 if self.piProcInfo != None:
542 542 CloseHandle(self.piProcInfo.hProcess)
543 543 CloseHandle(self.piProcInfo.hThread)
544 544 self.piProcInfo = None
545 545
546 546
547 547 def system(cmd):
548 548 """Win32 version of os.system() that works with network shares.
549 549
550 550 Note that this implementation returns None, as meant for use in IPython.
551 551
552 552 Parameters
553 553 ----------
554 554 cmd : str
555 555 A command to be executed in the system shell.
556 556
557 557 Returns
558 558 -------
559 559 None : we explicitly do NOT return the subprocess status code, as this
560 560 utility is meant to be used extensively in IPython, where any return value
561 561 would trigger :func:`sys.displayhook` calls.
562 562 """
563 563 with AvoidUNCPath() as path:
564 564 if path is not None:
565 565 cmd = '"pushd %s &&"%s' % (path, cmd)
566 566 with Win32ShellCommandController(cmd) as scc:
567 567 scc.run()
568 568
569 569
570 570 if __name__ == "__main__":
571 571 print("Test starting!")
572 572 #system("cmd")
573 573 system("python -i")
574 574 print("Test finished!")
@@ -1,173 +1,173 b''
1 1 # encoding: utf-8
2 2 """
3 3 IO capturing utilities.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2013 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 from __future__ import print_function
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import sys
19 19 from StringIO import StringIO
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Classes and functions
23 23 #-----------------------------------------------------------------------------
24 24
25 25
26 26 class RichOutput(object):
27 27 def __init__(self, source="", data=None, metadata=None):
28 28 self.source = source
29 29 self.data = data or {}
30 30 self.metadata = metadata or {}
31 31
32 32 def display(self):
33 33 from IPython.display import publish_display_data
34 34 publish_display_data(self.source, self.data, self.metadata)
35 35
36 36 def _repr_mime_(self, mime):
37 37 if mime not in self.data:
38 38 return
39 39 data = self.data[mime]
40 40 if mime in self.metadata:
41 41 return data, self.metadata[mime]
42 42 else:
43 43 return data
44 44
45 45 def _repr_html_(self):
46 46 return self._repr_mime_("text/html")
47 47
48 48 def _repr_latex_(self):
49 49 return self._repr_mime_("text/latex")
50 50
51 51 def _repr_json_(self):
52 52 return self._repr_mime_("application/json")
53 53
54 54 def _repr_javascript_(self):
55 55 return self._repr_mime_("application/javascript")
56 56
57 57 def _repr_png_(self):
58 58 return self._repr_mime_("image/png")
59 59
60 60 def _repr_jpeg_(self):
61 61 return self._repr_mime_("image/jpeg")
62 62
63 63 def _repr_svg_(self):
64 64 return self._repr_mime_("image/svg+xml")
65 65
66 66
67 67 class CapturedIO(object):
68 68 """Simple object for containing captured stdout/err and rich display StringIO objects
69 69
70 70 Each instance `c` has three attributes:
71 71
72 c.stdout : standard output as a string
73 c.stderr : standard error as a string
74 c.outputs: a list of rich display outputs
72 - ``c.stdout`` : standard output as a string
73 - ``c.stderr`` : standard error as a string
74 - ``c.outputs``: a list of rich display outputs
75 75
76 Additionally, there's a `c.show()` method which will print all of the
77 above in the same order, and can be invoked simply via `c()`.
76 Additionally, there's a ``c.show()`` method which will print all of the
77 above in the same order, and can be invoked simply via ``c()``.
78 78 """
79 79
80 80 def __init__(self, stdout, stderr, outputs=None):
81 81 self._stdout = stdout
82 82 self._stderr = stderr
83 83 if outputs is None:
84 84 outputs = []
85 85 self._outputs = outputs
86 86
87 87 def __str__(self):
88 88 return self.stdout
89 89
90 90 @property
91 91 def stdout(self):
92 92 "Captured standard output"
93 93 if not self._stdout:
94 94 return ''
95 95 return self._stdout.getvalue()
96 96
97 97 @property
98 98 def stderr(self):
99 99 "Captured standard error"
100 100 if not self._stderr:
101 101 return ''
102 102 return self._stderr.getvalue()
103 103
104 104 @property
105 105 def outputs(self):
106 106 """A list of the captured rich display outputs, if any.
107 107
108 If you have a CapturedIO object `c`, these can be displayed in IPython
109 using:
108 If you have a CapturedIO object ``c``, these can be displayed in IPython
109 using::
110 110
111 111 from IPython.display import display
112 112 for o in c.outputs:
113 113 display(o)
114 114 """
115 115 return [ RichOutput(s, d, md) for s, d, md in self._outputs ]
116 116
117 117 def show(self):
118 118 """write my output to sys.stdout/err as appropriate"""
119 119 sys.stdout.write(self.stdout)
120 120 sys.stderr.write(self.stderr)
121 121 sys.stdout.flush()
122 122 sys.stderr.flush()
123 123 for source, data, metadata in self._outputs:
124 124 RichOutput(source, data, metadata).display()
125 125
126 126 __call__ = show
127 127
128 128
129 129 class capture_output(object):
130 130 """context manager for capturing stdout/err"""
131 131 stdout = True
132 132 stderr = True
133 133 display = True
134 134
135 135 def __init__(self, stdout=True, stderr=True, display=True):
136 136 self.stdout = stdout
137 137 self.stderr = stderr
138 138 self.display = display
139 139 self.shell = None
140 140
141 141 def __enter__(self):
142 142 from IPython.core.getipython import get_ipython
143 143 from IPython.core.displaypub import CapturingDisplayPublisher
144 144
145 145 self.sys_stdout = sys.stdout
146 146 self.sys_stderr = sys.stderr
147 147
148 148 if self.display:
149 149 self.shell = get_ipython()
150 150 if self.shell is None:
151 151 self.save_display_pub = None
152 152 self.display = False
153 153
154 154 stdout = stderr = outputs = None
155 155 if self.stdout:
156 156 stdout = sys.stdout = StringIO()
157 157 if self.stderr:
158 158 stderr = sys.stderr = StringIO()
159 159 if self.display:
160 160 self.save_display_pub = self.shell.display_pub
161 161 self.shell.display_pub = CapturingDisplayPublisher()
162 162 outputs = self.shell.display_pub.outputs
163 163
164 164
165 165 return CapturedIO(stdout, stderr, outputs)
166 166
167 167 def __exit__(self, exc_type, exc_value, traceback):
168 168 sys.stdout = self.sys_stdout
169 169 sys.stderr = self.sys_stderr
170 170 if self.display and self.shell:
171 171 self.shell.display_pub = self.save_display_pub
172 172
173 173
@@ -1,71 +1,71 b''
1 1 # encoding: utf-8
2 2 """
3 3 Context managers for temporarily updating dictionaries.
4 4
5 5 Authors:
6 6
7 7 * Bradley Froehle
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2012 The IPython Development Team
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #-----------------------------------------------------------------------------
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Code
19 19 #-----------------------------------------------------------------------------
20 20
21 21 class preserve_keys(object):
22 22 """Preserve a set of keys in a dictionary.
23 23
24 24 Upon entering the context manager the current values of the keys
25 25 will be saved. Upon exiting, the dictionary will be updated to
26 26 restore the original value of the preserved keys. Preserved keys
27 27 which did not exist when entering the context manager will be
28 28 deleted.
29 29
30 Example
31 -------
30 Examples
31 --------
32 32
33 33 >>> d = {'a': 1, 'b': 2, 'c': 3}
34 34 >>> with preserve_keys(d, 'b', 'c', 'd'):
35 35 ... del d['a']
36 36 ... del d['b'] # will be reset to 2
37 37 ... d['c'] = None # will be reset to 3
38 38 ... d['d'] = 4 # will be deleted
39 39 ... d['e'] = 5
40 40 ... print(sorted(d.items()))
41 41 ...
42 42 [('c', None), ('d', 4), ('e', 5)]
43 43 >>> print(sorted(d.items()))
44 44 [('b', 2), ('c', 3), ('e', 5)]
45 45 """
46 46
47 47 def __init__(self, dictionary, *keys):
48 48 self.dictionary = dictionary
49 49 self.keys = keys
50 50
51 51 def __enter__(self):
52 52 # Actions to perform upon exiting.
53 53 to_delete = []
54 54 to_update = {}
55 55
56 56 d = self.dictionary
57 57 for k in self.keys:
58 58 if k in d:
59 59 to_update[k] = d[k]
60 60 else:
61 61 to_delete.append(k)
62 62
63 63 self.to_delete = to_delete
64 64 self.to_update = to_update
65 65
66 66 def __exit__(self, *exc_info):
67 67 d = self.dictionary
68 68
69 69 for k in self.to_delete:
70 70 d.pop(k, None)
71 71 d.update(self.to_update)
@@ -1,167 +1,169 b''
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for getting information about IPython and the system it's running in.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
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 import os
18 18 import platform
19 19 import pprint
20 20 import sys
21 21 import subprocess
22 22
23 23 from IPython.core import release
24 24 from IPython.utils import py3compat, _sysinfo, encoding
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Code
28 28 #-----------------------------------------------------------------------------
29 29
30 30 def pkg_commit_hash(pkg_path):
31 31 """Get short form of commit hash given directory `pkg_path`
32 32
33 33 We get the commit hash from (in order of preference):
34 34
35 35 * IPython.utils._sysinfo.commit
36 36 * git output, if we are in a git repository
37 37
38 38 If these fail, we return a not-found placeholder tuple
39 39
40 40 Parameters
41 41 ----------
42 42 pkg_path : str
43 43 directory containing package
44 44 only used for getting commit from active repo
45 45
46 46 Returns
47 47 -------
48 48 hash_from : str
49 49 Where we got the hash from - description
50 50 hash_str : str
51 51 short form of hash
52 52 """
53 53 # Try and get commit from written commit text file
54 54 if _sysinfo.commit:
55 55 return "installation", _sysinfo.commit
56 56
57 57 # maybe we are in a repository
58 58 proc = subprocess.Popen('git rev-parse --short HEAD',
59 59 stdout=subprocess.PIPE,
60 60 stderr=subprocess.PIPE,
61 61 cwd=pkg_path, shell=True)
62 62 repo_commit, _ = proc.communicate()
63 63 if repo_commit:
64 64 return 'repository', repo_commit.strip()
65 65 return '(none found)', '<not found>'
66 66
67 67
68 68 def pkg_info(pkg_path):
69 69 """Return dict describing the context of this package
70 70
71 71 Parameters
72 72 ----------
73 73 pkg_path : str
74 74 path containing __init__.py for package
75 75
76 76 Returns
77 77 -------
78 78 context : dict
79 79 with named parameters of interest
80 80 """
81 81 src, hsh = pkg_commit_hash(pkg_path)
82 82 return dict(
83 83 ipython_version=release.version,
84 84 ipython_path=pkg_path,
85 85 codename=release.codename,
86 86 commit_source=src,
87 87 commit_hash=hsh,
88 88 sys_version=sys.version,
89 89 sys_executable=sys.executable,
90 90 sys_platform=sys.platform,
91 91 platform=platform.platform(),
92 92 os_name=os.name,
93 93 default_encoding=encoding.DEFAULT_ENCODING,
94 94 )
95 95
96 96
97 97 @py3compat.doctest_refactor_print
98 98 def sys_info():
99 99 """Return useful information about IPython and the system, as a string.
100 100
101 Example
102 -------
103 In [2]: print sys_info()
104 {'commit_hash': '144fdae', # random
105 'commit_source': 'repository',
106 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
107 'ipython_version': '0.11.dev',
108 'os_name': 'posix',
109 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick',
110 'sys_executable': '/usr/bin/python',
111 'sys_platform': 'linux2',
112 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
101 Examples
102 --------
103 ::
104
105 In [2]: print sys_info()
106 {'commit_hash': '144fdae', # random
107 'commit_source': 'repository',
108 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
109 'ipython_version': '0.11.dev',
110 'os_name': 'posix',
111 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick',
112 'sys_executable': '/usr/bin/python',
113 'sys_platform': 'linux2',
114 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}
113 115 """
114 116 p = os.path
115 117 path = p.dirname(p.abspath(p.join(__file__, '..')))
116 118 return pprint.pformat(pkg_info(path))
117 119
118 120
119 121 def _num_cpus_unix():
120 122 """Return the number of active CPUs on a Unix system."""
121 123 return os.sysconf("SC_NPROCESSORS_ONLN")
122 124
123 125
124 126 def _num_cpus_darwin():
125 127 """Return the number of active CPUs on a Darwin system."""
126 128 p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
127 129 return p.stdout.read()
128 130
129 131
130 132 def _num_cpus_windows():
131 133 """Return the number of active CPUs on a Windows system."""
132 134 return os.environ.get("NUMBER_OF_PROCESSORS")
133 135
134 136
135 137 def num_cpus():
136 138 """Return the effective number of CPUs in the system as an integer.
137 139
138 140 This cross-platform function makes an attempt at finding the total number of
139 141 available CPUs in the system, as returned by various underlying system and
140 142 python calls.
141 143
142 144 If it can't find a sensible answer, it returns 1 (though an error *may* make
143 145 it return a large positive number that's actually incorrect).
144 146 """
145 147
146 148 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
147 149 # for the names of the keys we needed to look up for this function. This
148 150 # code was inspired by their equivalent function.
149 151
150 152 ncpufuncs = {'Linux':_num_cpus_unix,
151 153 'Darwin':_num_cpus_darwin,
152 154 'Windows':_num_cpus_windows,
153 155 # On Vista, python < 2.5.2 has a bug and returns 'Microsoft'
154 156 # See http://bugs.python.org/issue1082 for details.
155 157 'Microsoft':_num_cpus_windows,
156 158 }
157 159
158 160 ncpufunc = ncpufuncs.get(platform.system(),
159 161 # default to unix version (Solaris, AIX, etc)
160 162 _num_cpus_unix)
161 163
162 164 try:
163 165 ncpus = max(1,int(ncpufunc()))
164 166 except:
165 167 ncpus = 1
166 168 return ncpus
167 169
General Comments 0
You need to be logged in to leave comments. Login now