##// END OF EJS Templates
filter out some python 2.6 deprecationwarnings
Ville M. Vainio -
Show More
@@ -1,970 +1,973 b''
1 1 """ path.py - An object representing a path to a file or directory.
2 2
3 3 Example:
4 4
5 5 from IPython.external.path import path
6 6 d = path('/home/guido/bin')
7 7 for f in d.files('*.py'):
8 8 f.chmod(0755)
9 9
10 10 This module requires Python 2.2 or later.
11 11
12 12
13 13 URL: http://www.jorendorff.com/articles/python/path
14 14 Author: Jason Orendorff <jason.orendorff\x40gmail\x2ecom> (and others - see the url!)
15 15 Date: 9 Mar 2007
16 16 """
17 17
18 18
19 19 # TODO
20 20 # - Tree-walking functions don't avoid symlink loops. Matt Harrison
21 21 # sent me a patch for this.
22 22 # - Bug in write_text(). It doesn't support Universal newline mode.
23 23 # - Better error message in listdir() when self isn't a
24 24 # directory. (On Windows, the error message really sucks.)
25 25 # - Make sure everything has a good docstring.
26 26 # - Add methods for regex find and replace.
27 27 # - guess_content_type() method?
28 28 # - Perhaps support arguments to touch().
29 29
30 30 from __future__ import generators
31 31
32 import sys, warnings, os, fnmatch, glob, shutil, codecs, md5
32 import sys, warnings, os, fnmatch, glob, shutil, codecs
33 # deprecated in python 2.6
34 warnings.filterwarnings('ignore', r'.*md5.*')
35 import md5
33 36
34 37 __version__ = '2.2'
35 38 __all__ = ['path']
36 39
37 40 # Platform-specific support for path.owner
38 41 if os.name == 'nt':
39 42 try:
40 43 import win32security
41 44 except ImportError:
42 45 win32security = None
43 46 else:
44 47 try:
45 48 import pwd
46 49 except ImportError:
47 50 pwd = None
48 51
49 52 # Pre-2.3 support. Are unicode filenames supported?
50 53 _base = str
51 54 _getcwd = os.getcwd
52 55 try:
53 56 if os.path.supports_unicode_filenames:
54 57 _base = unicode
55 58 _getcwd = os.getcwdu
56 59 except AttributeError:
57 60 pass
58 61
59 62 # Pre-2.3 workaround for booleans
60 63 try:
61 64 True, False
62 65 except NameError:
63 66 True, False = 1, 0
64 67
65 68 # Pre-2.3 workaround for basestring.
66 69 try:
67 70 basestring
68 71 except NameError:
69 72 basestring = (str, unicode)
70 73
71 74 # Universal newline support
72 75 _textmode = 'r'
73 76 if hasattr(file, 'newlines'):
74 77 _textmode = 'U'
75 78
76 79
77 80 class TreeWalkWarning(Warning):
78 81 pass
79 82
80 83 class path(_base):
81 84 """ Represents a filesystem path.
82 85
83 86 For documentation on individual methods, consult their
84 87 counterparts in os.path.
85 88 """
86 89
87 90 # --- Special Python methods.
88 91
89 92 def __repr__(self):
90 93 return 'path(%s)' % _base.__repr__(self)
91 94
92 95 # Adding a path and a string yields a path.
93 96 def __add__(self, more):
94 97 try:
95 98 resultStr = _base.__add__(self, more)
96 99 except TypeError: #Python bug
97 100 resultStr = NotImplemented
98 101 if resultStr is NotImplemented:
99 102 return resultStr
100 103 return self.__class__(resultStr)
101 104
102 105 def __radd__(self, other):
103 106 if isinstance(other, basestring):
104 107 return self.__class__(other.__add__(self))
105 108 else:
106 109 return NotImplemented
107 110
108 111 # The / operator joins paths.
109 112 def __div__(self, rel):
110 113 """ fp.__div__(rel) == fp / rel == fp.joinpath(rel)
111 114
112 115 Join two path components, adding a separator character if
113 116 needed.
114 117 """
115 118 return self.__class__(os.path.join(self, rel))
116 119
117 120 # Make the / operator work even when true division is enabled.
118 121 __truediv__ = __div__
119 122
120 123 def getcwd(cls):
121 124 """ Return the current working directory as a path object. """
122 125 return cls(_getcwd())
123 126 getcwd = classmethod(getcwd)
124 127
125 128
126 129 # --- Operations on path strings.
127 130
128 131 isabs = os.path.isabs
129 132 def abspath(self): return self.__class__(os.path.abspath(self))
130 133 def normcase(self): return self.__class__(os.path.normcase(self))
131 134 def normpath(self): return self.__class__(os.path.normpath(self))
132 135 def realpath(self): return self.__class__(os.path.realpath(self))
133 136 def expanduser(self): return self.__class__(os.path.expanduser(self))
134 137 def expandvars(self): return self.__class__(os.path.expandvars(self))
135 138 def dirname(self): return self.__class__(os.path.dirname(self))
136 139 basename = os.path.basename
137 140
138 141 def expand(self):
139 142 """ Clean up a filename by calling expandvars(),
140 143 expanduser(), and normpath() on it.
141 144
142 145 This is commonly everything needed to clean up a filename
143 146 read from a configuration file, for example.
144 147 """
145 148 return self.expandvars().expanduser().normpath()
146 149
147 150 def _get_namebase(self):
148 151 base, ext = os.path.splitext(self.name)
149 152 return base
150 153
151 154 def _get_ext(self):
152 155 f, ext = os.path.splitext(_base(self))
153 156 return ext
154 157
155 158 def _get_drive(self):
156 159 drive, r = os.path.splitdrive(self)
157 160 return self.__class__(drive)
158 161
159 162 parent = property(
160 163 dirname, None, None,
161 164 """ This path's parent directory, as a new path object.
162 165
163 166 For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
164 167 """)
165 168
166 169 name = property(
167 170 basename, None, None,
168 171 """ The name of this file or directory without the full path.
169 172
170 173 For example, path('/usr/local/lib/libpython.so').name == 'libpython.so'
171 174 """)
172 175
173 176 namebase = property(
174 177 _get_namebase, None, None,
175 178 """ The same as path.name, but with one file extension stripped off.
176 179
177 180 For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz',
178 181 but path('/home/guido/python.tar.gz').namebase == 'python.tar'
179 182 """)
180 183
181 184 ext = property(
182 185 _get_ext, None, None,
183 186 """ The file extension, for example '.py'. """)
184 187
185 188 drive = property(
186 189 _get_drive, None, None,
187 190 """ The drive specifier, for example 'C:'.
188 191 This is always empty on systems that don't use drive specifiers.
189 192 """)
190 193
191 194 def splitpath(self):
192 195 """ p.splitpath() -> Return (p.parent, p.name). """
193 196 parent, child = os.path.split(self)
194 197 return self.__class__(parent), child
195 198
196 199 def splitdrive(self):
197 200 """ p.splitdrive() -> Return (p.drive, <the rest of p>).
198 201
199 202 Split the drive specifier from this path. If there is
200 203 no drive specifier, p.drive is empty, so the return value
201 204 is simply (path(''), p). This is always the case on Unix.
202 205 """
203 206 drive, rel = os.path.splitdrive(self)
204 207 return self.__class__(drive), rel
205 208
206 209 def splitext(self):
207 210 """ p.splitext() -> Return (p.stripext(), p.ext).
208 211
209 212 Split the filename extension from this path and return
210 213 the two parts. Either part may be empty.
211 214
212 215 The extension is everything from '.' to the end of the
213 216 last path segment. This has the property that if
214 217 (a, b) == p.splitext(), then a + b == p.
215 218 """
216 219 filename, ext = os.path.splitext(self)
217 220 return self.__class__(filename), ext
218 221
219 222 def stripext(self):
220 223 """ p.stripext() -> Remove one file extension from the path.
221 224
222 225 For example, path('/home/guido/python.tar.gz').stripext()
223 226 returns path('/home/guido/python.tar').
224 227 """
225 228 return self.splitext()[0]
226 229
227 230 if hasattr(os.path, 'splitunc'):
228 231 def splitunc(self):
229 232 unc, rest = os.path.splitunc(self)
230 233 return self.__class__(unc), rest
231 234
232 235 def _get_uncshare(self):
233 236 unc, r = os.path.splitunc(self)
234 237 return self.__class__(unc)
235 238
236 239 uncshare = property(
237 240 _get_uncshare, None, None,
238 241 """ The UNC mount point for this path.
239 242 This is empty for paths on local drives. """)
240 243
241 244 def joinpath(self, *args):
242 245 """ Join two or more path components, adding a separator
243 246 character (os.sep) if needed. Returns a new path
244 247 object.
245 248 """
246 249 return self.__class__(os.path.join(self, *args))
247 250
248 251 def splitall(self):
249 252 r""" Return a list of the path components in this path.
250 253
251 254 The first item in the list will be a path. Its value will be
252 255 either os.curdir, os.pardir, empty, or the root directory of
253 256 this path (for example, '/' or 'C:\\'). The other items in
254 257 the list will be strings.
255 258
256 259 path.path.joinpath(*result) will yield the original path.
257 260 """
258 261 parts = []
259 262 loc = self
260 263 while loc != os.curdir and loc != os.pardir:
261 264 prev = loc
262 265 loc, child = prev.splitpath()
263 266 if loc == prev:
264 267 break
265 268 parts.append(child)
266 269 parts.append(loc)
267 270 parts.reverse()
268 271 return parts
269 272
270 273 def relpath(self):
271 274 """ Return this path as a relative path,
272 275 based from the current working directory.
273 276 """
274 277 cwd = self.__class__(os.getcwd())
275 278 return cwd.relpathto(self)
276 279
277 280 def relpathto(self, dest):
278 281 """ Return a relative path from self to dest.
279 282
280 283 If there is no relative path from self to dest, for example if
281 284 they reside on different drives in Windows, then this returns
282 285 dest.abspath().
283 286 """
284 287 origin = self.abspath()
285 288 dest = self.__class__(dest).abspath()
286 289
287 290 orig_list = origin.normcase().splitall()
288 291 # Don't normcase dest! We want to preserve the case.
289 292 dest_list = dest.splitall()
290 293
291 294 if orig_list[0] != os.path.normcase(dest_list[0]):
292 295 # Can't get here from there.
293 296 return dest
294 297
295 298 # Find the location where the two paths start to differ.
296 299 i = 0
297 300 for start_seg, dest_seg in zip(orig_list, dest_list):
298 301 if start_seg != os.path.normcase(dest_seg):
299 302 break
300 303 i += 1
301 304
302 305 # Now i is the point where the two paths diverge.
303 306 # Need a certain number of "os.pardir"s to work up
304 307 # from the origin to the point of divergence.
305 308 segments = [os.pardir] * (len(orig_list) - i)
306 309 # Need to add the diverging part of dest_list.
307 310 segments += dest_list[i:]
308 311 if len(segments) == 0:
309 312 # If they happen to be identical, use os.curdir.
310 313 relpath = os.curdir
311 314 else:
312 315 relpath = os.path.join(*segments)
313 316 return self.__class__(relpath)
314 317
315 318 # --- Listing, searching, walking, and matching
316 319
317 320 def listdir(self, pattern=None):
318 321 """ D.listdir() -> List of items in this directory.
319 322
320 323 Use D.files() or D.dirs() instead if you want a listing
321 324 of just files or just subdirectories.
322 325
323 326 The elements of the list are path objects.
324 327
325 328 With the optional 'pattern' argument, this only lists
326 329 items whose names match the given pattern.
327 330 """
328 331 names = os.listdir(self)
329 332 if pattern is not None:
330 333 names = fnmatch.filter(names, pattern)
331 334 return [self / child for child in names]
332 335
333 336 def dirs(self, pattern=None):
334 337 """ D.dirs() -> List of this directory's subdirectories.
335 338
336 339 The elements of the list are path objects.
337 340 This does not walk recursively into subdirectories
338 341 (but see path.walkdirs).
339 342
340 343 With the optional 'pattern' argument, this only lists
341 344 directories whose names match the given pattern. For
342 345 example, d.dirs('build-*').
343 346 """
344 347 return [p for p in self.listdir(pattern) if p.isdir()]
345 348
346 349 def files(self, pattern=None):
347 350 """ D.files() -> List of the files in this directory.
348 351
349 352 The elements of the list are path objects.
350 353 This does not walk into subdirectories (see path.walkfiles).
351 354
352 355 With the optional 'pattern' argument, this only lists files
353 356 whose names match the given pattern. For example,
354 357 d.files('*.pyc').
355 358 """
356 359
357 360 return [p for p in self.listdir(pattern) if p.isfile()]
358 361
359 362 def walk(self, pattern=None, errors='strict'):
360 363 """ D.walk() -> iterator over files and subdirs, recursively.
361 364
362 365 The iterator yields path objects naming each child item of
363 366 this directory and its descendants. This requires that
364 367 D.isdir().
365 368
366 369 This performs a depth-first traversal of the directory tree.
367 370 Each directory is returned just before all its children.
368 371
369 372 The errors= keyword argument controls behavior when an
370 373 error occurs. The default is 'strict', which causes an
371 374 exception. The other allowed values are 'warn', which
372 375 reports the error via warnings.warn(), and 'ignore'.
373 376 """
374 377 if errors not in ('strict', 'warn', 'ignore'):
375 378 raise ValueError("invalid errors parameter")
376 379
377 380 try:
378 381 childList = self.listdir()
379 382 except Exception:
380 383 if errors == 'ignore':
381 384 return
382 385 elif errors == 'warn':
383 386 warnings.warn(
384 387 "Unable to list directory '%s': %s"
385 388 % (self, sys.exc_info()[1]),
386 389 TreeWalkWarning)
387 390 return
388 391 else:
389 392 raise
390 393
391 394 for child in childList:
392 395 if pattern is None or child.fnmatch(pattern):
393 396 yield child
394 397 try:
395 398 isdir = child.isdir()
396 399 except Exception:
397 400 if errors == 'ignore':
398 401 isdir = False
399 402 elif errors == 'warn':
400 403 warnings.warn(
401 404 "Unable to access '%s': %s"
402 405 % (child, sys.exc_info()[1]),
403 406 TreeWalkWarning)
404 407 isdir = False
405 408 else:
406 409 raise
407 410
408 411 if isdir:
409 412 for item in child.walk(pattern, errors):
410 413 yield item
411 414
412 415 def walkdirs(self, pattern=None, errors='strict'):
413 416 """ D.walkdirs() -> iterator over subdirs, recursively.
414 417
415 418 With the optional 'pattern' argument, this yields only
416 419 directories whose names match the given pattern. For
417 420 example, mydir.walkdirs('*test') yields only directories
418 421 with names ending in 'test'.
419 422
420 423 The errors= keyword argument controls behavior when an
421 424 error occurs. The default is 'strict', which causes an
422 425 exception. The other allowed values are 'warn', which
423 426 reports the error via warnings.warn(), and 'ignore'.
424 427 """
425 428 if errors not in ('strict', 'warn', 'ignore'):
426 429 raise ValueError("invalid errors parameter")
427 430
428 431 try:
429 432 dirs = self.dirs()
430 433 except Exception:
431 434 if errors == 'ignore':
432 435 return
433 436 elif errors == 'warn':
434 437 warnings.warn(
435 438 "Unable to list directory '%s': %s"
436 439 % (self, sys.exc_info()[1]),
437 440 TreeWalkWarning)
438 441 return
439 442 else:
440 443 raise
441 444
442 445 for child in dirs:
443 446 if pattern is None or child.fnmatch(pattern):
444 447 yield child
445 448 for subsubdir in child.walkdirs(pattern, errors):
446 449 yield subsubdir
447 450
448 451 def walkfiles(self, pattern=None, errors='strict'):
449 452 """ D.walkfiles() -> iterator over files in D, recursively.
450 453
451 454 The optional argument, pattern, limits the results to files
452 455 with names that match the pattern. For example,
453 456 mydir.walkfiles('*.tmp') yields only files with the .tmp
454 457 extension.
455 458 """
456 459 if errors not in ('strict', 'warn', 'ignore'):
457 460 raise ValueError("invalid errors parameter")
458 461
459 462 try:
460 463 childList = self.listdir()
461 464 except Exception:
462 465 if errors == 'ignore':
463 466 return
464 467 elif errors == 'warn':
465 468 warnings.warn(
466 469 "Unable to list directory '%s': %s"
467 470 % (self, sys.exc_info()[1]),
468 471 TreeWalkWarning)
469 472 return
470 473 else:
471 474 raise
472 475
473 476 for child in childList:
474 477 try:
475 478 isfile = child.isfile()
476 479 isdir = not isfile and child.isdir()
477 480 except:
478 481 if errors == 'ignore':
479 482 continue
480 483 elif errors == 'warn':
481 484 warnings.warn(
482 485 "Unable to access '%s': %s"
483 486 % (self, sys.exc_info()[1]),
484 487 TreeWalkWarning)
485 488 continue
486 489 else:
487 490 raise
488 491
489 492 if isfile:
490 493 if pattern is None or child.fnmatch(pattern):
491 494 yield child
492 495 elif isdir:
493 496 for f in child.walkfiles(pattern, errors):
494 497 yield f
495 498
496 499 def fnmatch(self, pattern):
497 500 """ Return True if self.name matches the given pattern.
498 501
499 502 pattern - A filename pattern with wildcards,
500 503 for example '*.py'.
501 504 """
502 505 return fnmatch.fnmatch(self.name, pattern)
503 506
504 507 def glob(self, pattern):
505 508 """ Return a list of path objects that match the pattern.
506 509
507 510 pattern - a path relative to this directory, with wildcards.
508 511
509 512 For example, path('/users').glob('*/bin/*') returns a list
510 513 of all the files users have in their bin directories.
511 514 """
512 515 cls = self.__class__
513 516 return [cls(s) for s in glob.glob(_base(self / pattern))]
514 517
515 518
516 519 # --- Reading or writing an entire file at once.
517 520
518 521 def open(self, mode='r'):
519 522 """ Open this file. Return a file object. """
520 523 return file(self, mode)
521 524
522 525 def bytes(self):
523 526 """ Open this file, read all bytes, return them as a string. """
524 527 f = self.open('rb')
525 528 try:
526 529 return f.read()
527 530 finally:
528 531 f.close()
529 532
530 533 def write_bytes(self, bytes, append=False):
531 534 """ Open this file and write the given bytes to it.
532 535
533 536 Default behavior is to overwrite any existing file.
534 537 Call p.write_bytes(bytes, append=True) to append instead.
535 538 """
536 539 if append:
537 540 mode = 'ab'
538 541 else:
539 542 mode = 'wb'
540 543 f = self.open(mode)
541 544 try:
542 545 f.write(bytes)
543 546 finally:
544 547 f.close()
545 548
546 549 def text(self, encoding=None, errors='strict'):
547 550 r""" Open this file, read it in, return the content as a string.
548 551
549 552 This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
550 553 are automatically translated to '\n'.
551 554
552 555 Optional arguments:
553 556
554 557 encoding - The Unicode encoding (or character set) of
555 558 the file. If present, the content of the file is
556 559 decoded and returned as a unicode object; otherwise
557 560 it is returned as an 8-bit str.
558 561 errors - How to handle Unicode errors; see help(str.decode)
559 562 for the options. Default is 'strict'.
560 563 """
561 564 if encoding is None:
562 565 # 8-bit
563 566 f = self.open(_textmode)
564 567 try:
565 568 return f.read()
566 569 finally:
567 570 f.close()
568 571 else:
569 572 # Unicode
570 573 f = codecs.open(self, 'r', encoding, errors)
571 574 # (Note - Can't use 'U' mode here, since codecs.open
572 575 # doesn't support 'U' mode, even in Python 2.3.)
573 576 try:
574 577 t = f.read()
575 578 finally:
576 579 f.close()
577 580 return (t.replace(u'\r\n', u'\n')
578 581 .replace(u'\r\x85', u'\n')
579 582 .replace(u'\r', u'\n')
580 583 .replace(u'\x85', u'\n')
581 584 .replace(u'\u2028', u'\n'))
582 585
583 586 def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False):
584 587 r""" Write the given text to this file.
585 588
586 589 The default behavior is to overwrite any existing file;
587 590 to append instead, use the 'append=True' keyword argument.
588 591
589 592 There are two differences between path.write_text() and
590 593 path.write_bytes(): newline handling and Unicode handling.
591 594 See below.
592 595
593 596 Parameters:
594 597
595 598 - text - str/unicode - The text to be written.
596 599
597 600 - encoding - str - The Unicode encoding that will be used.
598 601 This is ignored if 'text' isn't a Unicode string.
599 602
600 603 - errors - str - How to handle Unicode encoding errors.
601 604 Default is 'strict'. See help(unicode.encode) for the
602 605 options. This is ignored if 'text' isn't a Unicode
603 606 string.
604 607
605 608 - linesep - keyword argument - str/unicode - The sequence of
606 609 characters to be used to mark end-of-line. The default is
607 610 os.linesep. You can also specify None; this means to
608 611 leave all newlines as they are in 'text'.
609 612
610 613 - append - keyword argument - bool - Specifies what to do if
611 614 the file already exists (True: append to the end of it;
612 615 False: overwrite it.) The default is False.
613 616
614 617
615 618 --- Newline handling.
616 619
617 620 write_text() converts all standard end-of-line sequences
618 621 ('\n', '\r', and '\r\n') to your platform's default end-of-line
619 622 sequence (see os.linesep; on Windows, for example, the
620 623 end-of-line marker is '\r\n').
621 624
622 625 If you don't like your platform's default, you can override it
623 626 using the 'linesep=' keyword argument. If you specifically want
624 627 write_text() to preserve the newlines as-is, use 'linesep=None'.
625 628
626 629 This applies to Unicode text the same as to 8-bit text, except
627 630 there are three additional standard Unicode end-of-line sequences:
628 631 u'\x85', u'\r\x85', and u'\u2028'.
629 632
630 633 (This is slightly different from when you open a file for
631 634 writing with fopen(filename, "w") in C or file(filename, 'w')
632 635 in Python.)
633 636
634 637
635 638 --- Unicode
636 639
637 640 If 'text' isn't Unicode, then apart from newline handling, the
638 641 bytes are written verbatim to the file. The 'encoding' and
639 642 'errors' arguments are not used and must be omitted.
640 643
641 644 If 'text' is Unicode, it is first converted to bytes using the
642 645 specified 'encoding' (or the default encoding if 'encoding'
643 646 isn't specified). The 'errors' argument applies only to this
644 647 conversion.
645 648
646 649 """
647 650 if isinstance(text, unicode):
648 651 if linesep is not None:
649 652 # Convert all standard end-of-line sequences to
650 653 # ordinary newline characters.
651 654 text = (text.replace(u'\r\n', u'\n')
652 655 .replace(u'\r\x85', u'\n')
653 656 .replace(u'\r', u'\n')
654 657 .replace(u'\x85', u'\n')
655 658 .replace(u'\u2028', u'\n'))
656 659 text = text.replace(u'\n', linesep)
657 660 if encoding is None:
658 661 encoding = sys.getdefaultencoding()
659 662 bytes = text.encode(encoding, errors)
660 663 else:
661 664 # It is an error to specify an encoding if 'text' is
662 665 # an 8-bit string.
663 666 assert encoding is None
664 667
665 668 if linesep is not None:
666 669 text = (text.replace('\r\n', '\n')
667 670 .replace('\r', '\n'))
668 671 bytes = text.replace('\n', linesep)
669 672
670 673 self.write_bytes(bytes, append)
671 674
672 675 def lines(self, encoding=None, errors='strict', retain=True):
673 676 r""" Open this file, read all lines, return them in a list.
674 677
675 678 Optional arguments:
676 679 encoding - The Unicode encoding (or character set) of
677 680 the file. The default is None, meaning the content
678 681 of the file is read as 8-bit characters and returned
679 682 as a list of (non-Unicode) str objects.
680 683 errors - How to handle Unicode errors; see help(str.decode)
681 684 for the options. Default is 'strict'
682 685 retain - If true, retain newline characters; but all newline
683 686 character combinations ('\r', '\n', '\r\n') are
684 687 translated to '\n'. If false, newline characters are
685 688 stripped off. Default is True.
686 689
687 690 This uses 'U' mode in Python 2.3 and later.
688 691 """
689 692 if encoding is None and retain:
690 693 f = self.open(_textmode)
691 694 try:
692 695 return f.readlines()
693 696 finally:
694 697 f.close()
695 698 else:
696 699 return self.text(encoding, errors).splitlines(retain)
697 700
698 701 def write_lines(self, lines, encoding=None, errors='strict',
699 702 linesep=os.linesep, append=False):
700 703 r""" Write the given lines of text to this file.
701 704
702 705 By default this overwrites any existing file at this path.
703 706
704 707 This puts a platform-specific newline sequence on every line.
705 708 See 'linesep' below.
706 709
707 710 lines - A list of strings.
708 711
709 712 encoding - A Unicode encoding to use. This applies only if
710 713 'lines' contains any Unicode strings.
711 714
712 715 errors - How to handle errors in Unicode encoding. This
713 716 also applies only to Unicode strings.
714 717
715 718 linesep - The desired line-ending. This line-ending is
716 719 applied to every line. If a line already has any
717 720 standard line ending ('\r', '\n', '\r\n', u'\x85',
718 721 u'\r\x85', u'\u2028'), that will be stripped off and
719 722 this will be used instead. The default is os.linesep,
720 723 which is platform-dependent ('\r\n' on Windows, '\n' on
721 724 Unix, etc.) Specify None to write the lines as-is,
722 725 like file.writelines().
723 726
724 727 Use the keyword argument append=True to append lines to the
725 728 file. The default is to overwrite the file. Warning:
726 729 When you use this with Unicode data, if the encoding of the
727 730 existing data in the file is different from the encoding
728 731 you specify with the encoding= parameter, the result is
729 732 mixed-encoding data, which can really confuse someone trying
730 733 to read the file later.
731 734 """
732 735 if append:
733 736 mode = 'ab'
734 737 else:
735 738 mode = 'wb'
736 739 f = self.open(mode)
737 740 try:
738 741 for line in lines:
739 742 isUnicode = isinstance(line, unicode)
740 743 if linesep is not None:
741 744 # Strip off any existing line-end and add the
742 745 # specified linesep string.
743 746 if isUnicode:
744 747 if line[-2:] in (u'\r\n', u'\x0d\x85'):
745 748 line = line[:-2]
746 749 elif line[-1:] in (u'\r', u'\n',
747 750 u'\x85', u'\u2028'):
748 751 line = line[:-1]
749 752 else:
750 753 if line[-2:] == '\r\n':
751 754 line = line[:-2]
752 755 elif line[-1:] in ('\r', '\n'):
753 756 line = line[:-1]
754 757 line += linesep
755 758 if isUnicode:
756 759 if encoding is None:
757 760 encoding = sys.getdefaultencoding()
758 761 line = line.encode(encoding, errors)
759 762 f.write(line)
760 763 finally:
761 764 f.close()
762 765
763 766 def read_md5(self):
764 767 """ Calculate the md5 hash for this file.
765 768
766 769 This reads through the entire file.
767 770 """
768 771 f = self.open('rb')
769 772 try:
770 773 m = md5.new()
771 774 while True:
772 775 d = f.read(8192)
773 776 if not d:
774 777 break
775 778 m.update(d)
776 779 finally:
777 780 f.close()
778 781 return m.digest()
779 782
780 783 # --- Methods for querying the filesystem.
781 784
782 785 exists = os.path.exists
783 786 isdir = os.path.isdir
784 787 isfile = os.path.isfile
785 788 islink = os.path.islink
786 789 ismount = os.path.ismount
787 790
788 791 if hasattr(os.path, 'samefile'):
789 792 samefile = os.path.samefile
790 793
791 794 getatime = os.path.getatime
792 795 atime = property(
793 796 getatime, None, None,
794 797 """ Last access time of the file. """)
795 798
796 799 getmtime = os.path.getmtime
797 800 mtime = property(
798 801 getmtime, None, None,
799 802 """ Last-modified time of the file. """)
800 803
801 804 if hasattr(os.path, 'getctime'):
802 805 getctime = os.path.getctime
803 806 ctime = property(
804 807 getctime, None, None,
805 808 """ Creation time of the file. """)
806 809
807 810 getsize = os.path.getsize
808 811 size = property(
809 812 getsize, None, None,
810 813 """ Size of the file, in bytes. """)
811 814
812 815 if hasattr(os, 'access'):
813 816 def access(self, mode):
814 817 """ Return true if current user has access to this path.
815 818
816 819 mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK
817 820 """
818 821 return os.access(self, mode)
819 822
820 823 def stat(self):
821 824 """ Perform a stat() system call on this path. """
822 825 return os.stat(self)
823 826
824 827 def lstat(self):
825 828 """ Like path.stat(), but do not follow symbolic links. """
826 829 return os.lstat(self)
827 830
828 831 def get_owner(self):
829 832 r""" Return the name of the owner of this file or directory.
830 833
831 834 This follows symbolic links.
832 835
833 836 On Windows, this returns a name of the form ur'DOMAIN\User Name'.
834 837 On Windows, a group can own a file or directory.
835 838 """
836 839 if os.name == 'nt':
837 840 if win32security is None:
838 841 raise Exception("path.owner requires win32all to be installed")
839 842 desc = win32security.GetFileSecurity(
840 843 self, win32security.OWNER_SECURITY_INFORMATION)
841 844 sid = desc.GetSecurityDescriptorOwner()
842 845 account, domain, typecode = win32security.LookupAccountSid(None, sid)
843 846 return domain + u'\\' + account
844 847 else:
845 848 if pwd is None:
846 849 raise NotImplementedError("path.owner is not implemented on this platform.")
847 850 st = self.stat()
848 851 return pwd.getpwuid(st.st_uid).pw_name
849 852
850 853 owner = property(
851 854 get_owner, None, None,
852 855 """ Name of the owner of this file or directory. """)
853 856
854 857 if hasattr(os, 'statvfs'):
855 858 def statvfs(self):
856 859 """ Perform a statvfs() system call on this path. """
857 860 return os.statvfs(self)
858 861
859 862 if hasattr(os, 'pathconf'):
860 863 def pathconf(self, name):
861 864 return os.pathconf(self, name)
862 865
863 866
864 867 # --- Modifying operations on files and directories
865 868
866 869 def utime(self, times):
867 870 """ Set the access and modified times of this file. """
868 871 os.utime(self, times)
869 872
870 873 def chmod(self, mode):
871 874 os.chmod(self, mode)
872 875
873 876 if hasattr(os, 'chown'):
874 877 def chown(self, uid, gid):
875 878 os.chown(self, uid, gid)
876 879
877 880 def rename(self, new):
878 881 os.rename(self, new)
879 882
880 883 def renames(self, new):
881 884 os.renames(self, new)
882 885
883 886
884 887 # --- Create/delete operations on directories
885 888
886 889 def mkdir(self, mode=0777):
887 890 os.mkdir(self, mode)
888 891
889 892 def makedirs(self, mode=0777):
890 893 os.makedirs(self, mode)
891 894
892 895 def rmdir(self):
893 896 os.rmdir(self)
894 897
895 898 def removedirs(self):
896 899 os.removedirs(self)
897 900
898 901
899 902 # --- Modifying operations on files
900 903
901 904 def touch(self):
902 905 """ Set the access/modified times of this file to the current time.
903 906 Create the file if it does not exist.
904 907 """
905 908 fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
906 909 os.close(fd)
907 910 os.utime(self, None)
908 911
909 912 def remove(self):
910 913 os.remove(self)
911 914
912 915 def unlink(self):
913 916 os.unlink(self)
914 917
915 918
916 919 # --- Links
917 920
918 921 if hasattr(os, 'link'):
919 922 def link(self, newpath):
920 923 """ Create a hard link at 'newpath', pointing to this file. """
921 924 os.link(self, newpath)
922 925
923 926 if hasattr(os, 'symlink'):
924 927 def symlink(self, newlink):
925 928 """ Create a symbolic link at 'newlink', pointing here. """
926 929 os.symlink(self, newlink)
927 930
928 931 if hasattr(os, 'readlink'):
929 932 def readlink(self):
930 933 """ Return the path to which this symbolic link points.
931 934
932 935 The result may be an absolute or a relative path.
933 936 """
934 937 return self.__class__(os.readlink(self))
935 938
936 939 def readlinkabs(self):
937 940 """ Return the path to which this symbolic link points.
938 941
939 942 The result is always an absolute path.
940 943 """
941 944 p = self.readlink()
942 945 if p.isabs():
943 946 return p
944 947 else:
945 948 return (self.parent / p).abspath()
946 949
947 950
948 951 # --- High-level functions from shutil
949 952
950 953 copyfile = shutil.copyfile
951 954 copymode = shutil.copymode
952 955 copystat = shutil.copystat
953 956 copy = shutil.copy
954 957 copy2 = shutil.copy2
955 958 copytree = shutil.copytree
956 959 if hasattr(shutil, 'move'):
957 960 move = shutil.move
958 961 rmtree = shutil.rmtree
959 962
960 963
961 964 # --- Special stuff from os
962 965
963 966 if hasattr(os, 'chroot'):
964 967 def chroot(self):
965 968 os.chroot(self)
966 969
967 970 if hasattr(os, 'startfile'):
968 971 def startfile(self):
969 972 os.startfile(self)
970 973
@@ -1,2681 +1,2683 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.3 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 9 """
10 10
11 11 #*****************************************************************************
12 12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #
18 18 # Note: this code originally subclassed code.InteractiveConsole from the
19 19 # Python standard library. Over time, all of that class has been copied
20 20 # verbatim here for modifications which could not be accomplished by
21 21 # subclassing. At this point, there are no dependencies at all on the code
22 22 # module anymore (it is not even imported). The Python License (sec. 2)
23 23 # allows for this, but it's always nice to acknowledge credit where credit is
24 24 # due.
25 25 #*****************************************************************************
26 26
27 27 #****************************************************************************
28 28 # Modules and globals
29 29
30 30 from IPython import Release
31 31 __author__ = '%s <%s>\n%s <%s>' % \
32 32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 33 __license__ = Release.license
34 34 __version__ = Release.version
35 35
36 36 # Python standard modules
37 37 import __main__
38 38 import __builtin__
39 39 import StringIO
40 40 import bdb
41 41 import cPickle as pickle
42 42 import codeop
43 43 import exceptions
44 44 import glob
45 45 import inspect
46 46 import keyword
47 47 import new
48 48 import os
49 49 import pydoc
50 50 import re
51 51 import shutil
52 52 import string
53 53 import sys
54 54 import tempfile
55 55 import traceback
56 56 import types
57 import warnings
58 warnings.filterwarnings('ignore', r'.*sets module*')
57 59 from sets import Set
58 60 from pprint import pprint, pformat
59 61
60 62 # IPython's own modules
61 63 #import IPython
62 64 from IPython import Debugger,OInspect,PyColorize,ultraTB
63 65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
64 66 from IPython.Extensions import pickleshare
65 67 from IPython.FakeModule import FakeModule
66 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
67 69 from IPython.Logger import Logger
68 70 from IPython.Magic import Magic
69 71 from IPython.Prompts import CachedOutput
70 72 from IPython.ipstruct import Struct
71 73 from IPython.background_jobs import BackgroundJobManager
72 74 from IPython.usage import cmd_line_usage,interactive_usage
73 75 from IPython.genutils import *
74 76 from IPython.strdispatch import StrDispatch
75 77 import IPython.ipapi
76 78 import IPython.history
77 79 import IPython.prefilter as prefilter
78 80 import IPython.shadowns
79 81 # Globals
80 82
81 83 # store the builtin raw_input globally, and use this always, in case user code
82 84 # overwrites it (like wx.py.PyShell does)
83 85 raw_input_original = raw_input
84 86
85 87 # compiled regexps for autoindent management
86 88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 89
88 90
89 91 #****************************************************************************
90 92 # Some utility function definitions
91 93
92 94 ini_spaces_re = re.compile(r'^(\s+)')
93 95
94 96 def num_ini_spaces(strng):
95 97 """Return the number of initial spaces in a string"""
96 98
97 99 ini_spaces = ini_spaces_re.match(strng)
98 100 if ini_spaces:
99 101 return ini_spaces.end()
100 102 else:
101 103 return 0
102 104
103 105 def softspace(file, newvalue):
104 106 """Copied from code.py, to remove the dependency"""
105 107
106 108 oldvalue = 0
107 109 try:
108 110 oldvalue = file.softspace
109 111 except AttributeError:
110 112 pass
111 113 try:
112 114 file.softspace = newvalue
113 115 except (AttributeError, TypeError):
114 116 # "attribute-less object" or "read-only attributes"
115 117 pass
116 118 return oldvalue
117 119
118 120
119 121 #****************************************************************************
120 122 # Local use exceptions
121 123 class SpaceInInput(exceptions.Exception): pass
122 124
123 125
124 126 #****************************************************************************
125 127 # Local use classes
126 128 class Bunch: pass
127 129
128 130 class Undefined: pass
129 131
130 132 class Quitter(object):
131 133 """Simple class to handle exit, similar to Python 2.5's.
132 134
133 135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
134 136 doesn't do (obviously, since it doesn't know about ipython)."""
135 137
136 138 def __init__(self,shell,name):
137 139 self.shell = shell
138 140 self.name = name
139 141
140 142 def __repr__(self):
141 143 return 'Type %s() to exit.' % self.name
142 144 __str__ = __repr__
143 145
144 146 def __call__(self):
145 147 self.shell.exit()
146 148
147 149 class InputList(list):
148 150 """Class to store user input.
149 151
150 152 It's basically a list, but slices return a string instead of a list, thus
151 153 allowing things like (assuming 'In' is an instance):
152 154
153 155 exec In[4:7]
154 156
155 157 or
156 158
157 159 exec In[5:9] + In[14] + In[21:25]"""
158 160
159 161 def __getslice__(self,i,j):
160 162 return ''.join(list.__getslice__(self,i,j))
161 163
162 164 class SyntaxTB(ultraTB.ListTB):
163 165 """Extension which holds some state: the last exception value"""
164 166
165 167 def __init__(self,color_scheme = 'NoColor'):
166 168 ultraTB.ListTB.__init__(self,color_scheme)
167 169 self.last_syntax_error = None
168 170
169 171 def __call__(self, etype, value, elist):
170 172 self.last_syntax_error = value
171 173 ultraTB.ListTB.__call__(self,etype,value,elist)
172 174
173 175 def clear_err_state(self):
174 176 """Return the current error state and clear it"""
175 177 e = self.last_syntax_error
176 178 self.last_syntax_error = None
177 179 return e
178 180
179 181 #****************************************************************************
180 182 # Main IPython class
181 183
182 184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
183 185 # until a full rewrite is made. I've cleaned all cross-class uses of
184 186 # attributes and methods, but too much user code out there relies on the
185 187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
186 188 #
187 189 # But at least now, all the pieces have been separated and we could, in
188 190 # principle, stop using the mixin. This will ease the transition to the
189 191 # chainsaw branch.
190 192
191 193 # For reference, the following is the list of 'self.foo' uses in the Magic
192 194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
193 195 # class, to prevent clashes.
194 196
195 197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
196 198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
197 199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
198 200 # 'self.value']
199 201
200 202 class InteractiveShell(object,Magic):
201 203 """An enhanced console for Python."""
202 204
203 205 # class attribute to indicate whether the class supports threads or not.
204 206 # Subclasses with thread support should override this as needed.
205 207 isthreaded = False
206 208
207 209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
208 210 user_ns = None,user_global_ns=None,banner2='',
209 211 custom_exceptions=((),None),embedded=False):
210 212
211 213 # log system
212 214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
213 215
214 216 # some minimal strict typechecks. For some core data structures, I
215 217 # want actual basic python types, not just anything that looks like
216 218 # one. This is especially true for namespaces.
217 219 for ns in (user_ns,user_global_ns):
218 220 if ns is not None and type(ns) != types.DictType:
219 221 raise TypeError,'namespace must be a dictionary'
220 222 # Job manager (for jobs run as background threads)
221 223 self.jobs = BackgroundJobManager()
222 224
223 225 # Store the actual shell's name
224 226 self.name = name
225 227 self.more = False
226 228
227 229 # We need to know whether the instance is meant for embedding, since
228 230 # global/local namespaces need to be handled differently in that case
229 231 self.embedded = embedded
230 232 if embedded:
231 233 # Control variable so users can, from within the embedded instance,
232 234 # permanently deactivate it.
233 235 self.embedded_active = True
234 236
235 237 # command compiler
236 238 self.compile = codeop.CommandCompiler()
237 239
238 240 # User input buffer
239 241 self.buffer = []
240 242
241 243 # Default name given in compilation of code
242 244 self.filename = '<ipython console>'
243 245
244 246 # Install our own quitter instead of the builtins. For python2.3-2.4,
245 247 # this brings in behavior like 2.5, and for 2.5 it's identical.
246 248 __builtin__.exit = Quitter(self,'exit')
247 249 __builtin__.quit = Quitter(self,'quit')
248 250
249 251 # Make an empty namespace, which extension writers can rely on both
250 252 # existing and NEVER being used by ipython itself. This gives them a
251 253 # convenient location for storing additional information and state
252 254 # their extensions may require, without fear of collisions with other
253 255 # ipython names that may develop later.
254 256 self.meta = Struct()
255 257
256 258 # Create the namespace where the user will operate. user_ns is
257 259 # normally the only one used, and it is passed to the exec calls as
258 260 # the locals argument. But we do carry a user_global_ns namespace
259 261 # given as the exec 'globals' argument, This is useful in embedding
260 262 # situations where the ipython shell opens in a context where the
261 263 # distinction between locals and globals is meaningful.
262 264
263 265 # FIXME. For some strange reason, __builtins__ is showing up at user
264 266 # level as a dict instead of a module. This is a manual fix, but I
265 267 # should really track down where the problem is coming from. Alex
266 268 # Schmolck reported this problem first.
267 269
268 270 # A useful post by Alex Martelli on this topic:
269 271 # Re: inconsistent value from __builtins__
270 272 # Von: Alex Martelli <aleaxit@yahoo.com>
271 273 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
272 274 # Gruppen: comp.lang.python
273 275
274 276 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
275 277 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
276 278 # > <type 'dict'>
277 279 # > >>> print type(__builtins__)
278 280 # > <type 'module'>
279 281 # > Is this difference in return value intentional?
280 282
281 283 # Well, it's documented that '__builtins__' can be either a dictionary
282 284 # or a module, and it's been that way for a long time. Whether it's
283 285 # intentional (or sensible), I don't know. In any case, the idea is
284 286 # that if you need to access the built-in namespace directly, you
285 287 # should start with "import __builtin__" (note, no 's') which will
286 288 # definitely give you a module. Yeah, it's somewhat confusing:-(.
287 289
288 290 # These routines return properly built dicts as needed by the rest of
289 291 # the code, and can also be used by extension writers to generate
290 292 # properly initialized namespaces.
291 293 user_ns = IPython.ipapi.make_user_ns(user_ns)
292 294 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
293 295
294 296 # Assign namespaces
295 297 # This is the namespace where all normal user variables live
296 298 self.user_ns = user_ns
297 299 # Embedded instances require a separate namespace for globals.
298 300 # Normally this one is unused by non-embedded instances.
299 301 self.user_global_ns = user_global_ns
300 302 # A namespace to keep track of internal data structures to prevent
301 303 # them from cluttering user-visible stuff. Will be updated later
302 304 self.internal_ns = {}
303 305
304 306 # Namespace of system aliases. Each entry in the alias
305 307 # table must be a 2-tuple of the form (N,name), where N is the number
306 308 # of positional arguments of the alias.
307 309 self.alias_table = {}
308 310
309 311 # A table holding all the namespaces IPython deals with, so that
310 312 # introspection facilities can search easily.
311 313 self.ns_table = {'user':user_ns,
312 314 'user_global':user_global_ns,
313 315 'alias':self.alias_table,
314 316 'internal':self.internal_ns,
315 317 'builtin':__builtin__.__dict__
316 318 }
317 319 # The user namespace MUST have a pointer to the shell itself.
318 320 self.user_ns[name] = self
319 321
320 322 # We need to insert into sys.modules something that looks like a
321 323 # module but which accesses the IPython namespace, for shelve and
322 324 # pickle to work interactively. Normally they rely on getting
323 325 # everything out of __main__, but for embedding purposes each IPython
324 326 # instance has its own private namespace, so we can't go shoving
325 327 # everything into __main__.
326 328
327 329 # note, however, that we should only do this for non-embedded
328 330 # ipythons, which really mimic the __main__.__dict__ with their own
329 331 # namespace. Embedded instances, on the other hand, should not do
330 332 # this because they need to manage the user local/global namespaces
331 333 # only, but they live within a 'normal' __main__ (meaning, they
332 334 # shouldn't overtake the execution environment of the script they're
333 335 # embedded in).
334 336
335 337 if not embedded:
336 338 try:
337 339 main_name = self.user_ns['__name__']
338 340 except KeyError:
339 341 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
340 342 else:
341 343 #print "pickle hack in place" # dbg
342 344 #print 'main_name:',main_name # dbg
343 345 sys.modules[main_name] = FakeModule(self.user_ns)
344 346
345 347 # Now that FakeModule produces a real module, we've run into a nasty
346 348 # problem: after script execution (via %run), the module where the user
347 349 # code ran is deleted. Now that this object is a true module (needed
348 350 # so docetst and other tools work correctly), the Python module
349 351 # teardown mechanism runs over it, and sets to None every variable
350 352 # present in that module. This means that later calls to functions
351 353 # defined in the script (which have become interactively visible after
352 354 # script exit) fail, because they hold references to objects that have
353 355 # become overwritten into None. The only solution I see right now is
354 356 # to protect every FakeModule used by %run by holding an internal
355 357 # reference to it. This private list will be used for that. The
356 358 # %reset command will flush it as well.
357 359 self._user_main_modules = []
358 360
359 361 # List of input with multi-line handling.
360 362 # Fill its zero entry, user counter starts at 1
361 363 self.input_hist = InputList(['\n'])
362 364 # This one will hold the 'raw' input history, without any
363 365 # pre-processing. This will allow users to retrieve the input just as
364 366 # it was exactly typed in by the user, with %hist -r.
365 367 self.input_hist_raw = InputList(['\n'])
366 368
367 369 # list of visited directories
368 370 try:
369 371 self.dir_hist = [os.getcwd()]
370 372 except OSError:
371 373 self.dir_hist = []
372 374
373 375 # dict of output history
374 376 self.output_hist = {}
375 377
376 378 # Get system encoding at startup time. Certain terminals (like Emacs
377 379 # under Win32 have it set to None, and we need to have a known valid
378 380 # encoding to use in the raw_input() method
379 381 try:
380 382 self.stdin_encoding = sys.stdin.encoding or 'ascii'
381 383 except AttributeError:
382 384 self.stdin_encoding = 'ascii'
383 385
384 386 # dict of things NOT to alias (keywords, builtins and some magics)
385 387 no_alias = {}
386 388 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
387 389 for key in keyword.kwlist + no_alias_magics:
388 390 no_alias[key] = 1
389 391 no_alias.update(__builtin__.__dict__)
390 392 self.no_alias = no_alias
391 393
392 394 # make global variables for user access to these
393 395 self.user_ns['_ih'] = self.input_hist
394 396 self.user_ns['_oh'] = self.output_hist
395 397 self.user_ns['_dh'] = self.dir_hist
396 398
397 399 # user aliases to input and output histories
398 400 self.user_ns['In'] = self.input_hist
399 401 self.user_ns['Out'] = self.output_hist
400 402
401 403 self.user_ns['_sh'] = IPython.shadowns
402 404 # Object variable to store code object waiting execution. This is
403 405 # used mainly by the multithreaded shells, but it can come in handy in
404 406 # other situations. No need to use a Queue here, since it's a single
405 407 # item which gets cleared once run.
406 408 self.code_to_run = None
407 409
408 410 # escapes for automatic behavior on the command line
409 411 self.ESC_SHELL = '!'
410 412 self.ESC_SH_CAP = '!!'
411 413 self.ESC_HELP = '?'
412 414 self.ESC_MAGIC = '%'
413 415 self.ESC_QUOTE = ','
414 416 self.ESC_QUOTE2 = ';'
415 417 self.ESC_PAREN = '/'
416 418
417 419 # And their associated handlers
418 420 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
419 421 self.ESC_QUOTE : self.handle_auto,
420 422 self.ESC_QUOTE2 : self.handle_auto,
421 423 self.ESC_MAGIC : self.handle_magic,
422 424 self.ESC_HELP : self.handle_help,
423 425 self.ESC_SHELL : self.handle_shell_escape,
424 426 self.ESC_SH_CAP : self.handle_shell_escape,
425 427 }
426 428
427 429 # class initializations
428 430 Magic.__init__(self,self)
429 431
430 432 # Python source parser/formatter for syntax highlighting
431 433 pyformat = PyColorize.Parser().format
432 434 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
433 435
434 436 # hooks holds pointers used for user-side customizations
435 437 self.hooks = Struct()
436 438
437 439 self.strdispatchers = {}
438 440
439 441 # Set all default hooks, defined in the IPython.hooks module.
440 442 hooks = IPython.hooks
441 443 for hook_name in hooks.__all__:
442 444 # default hooks have priority 100, i.e. low; user hooks should have
443 445 # 0-100 priority
444 446 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
445 447 #print "bound hook",hook_name
446 448
447 449 # Flag to mark unconditional exit
448 450 self.exit_now = False
449 451
450 452 self.usage_min = """\
451 453 An enhanced console for Python.
452 454 Some of its features are:
453 455 - Readline support if the readline library is present.
454 456 - Tab completion in the local namespace.
455 457 - Logging of input, see command-line options.
456 458 - System shell escape via ! , eg !ls.
457 459 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
458 460 - Keeps track of locally defined variables via %who, %whos.
459 461 - Show object information with a ? eg ?x or x? (use ?? for more info).
460 462 """
461 463 if usage: self.usage = usage
462 464 else: self.usage = self.usage_min
463 465
464 466 # Storage
465 467 self.rc = rc # This will hold all configuration information
466 468 self.pager = 'less'
467 469 # temporary files used for various purposes. Deleted at exit.
468 470 self.tempfiles = []
469 471
470 472 # Keep track of readline usage (later set by init_readline)
471 473 self.has_readline = False
472 474
473 475 # template for logfile headers. It gets resolved at runtime by the
474 476 # logstart method.
475 477 self.loghead_tpl = \
476 478 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
477 479 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
478 480 #log# opts = %s
479 481 #log# args = %s
480 482 #log# It is safe to make manual edits below here.
481 483 #log#-----------------------------------------------------------------------
482 484 """
483 485 # for pushd/popd management
484 486 try:
485 487 self.home_dir = get_home_dir()
486 488 except HomeDirError,msg:
487 489 fatal(msg)
488 490
489 491 self.dir_stack = []
490 492
491 493 # Functions to call the underlying shell.
492 494
493 495 # The first is similar to os.system, but it doesn't return a value,
494 496 # and it allows interpolation of variables in the user's namespace.
495 497 self.system = lambda cmd: \
496 498 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
497 499
498 500 # These are for getoutput and getoutputerror:
499 501 self.getoutput = lambda cmd: \
500 502 getoutput(self.var_expand(cmd,depth=2),
501 503 header=self.rc.system_header,
502 504 verbose=self.rc.system_verbose)
503 505
504 506 self.getoutputerror = lambda cmd: \
505 507 getoutputerror(self.var_expand(cmd,depth=2),
506 508 header=self.rc.system_header,
507 509 verbose=self.rc.system_verbose)
508 510
509 511
510 512 # keep track of where we started running (mainly for crash post-mortem)
511 513 self.starting_dir = os.getcwd()
512 514
513 515 # Various switches which can be set
514 516 self.CACHELENGTH = 5000 # this is cheap, it's just text
515 517 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
516 518 self.banner2 = banner2
517 519
518 520 # TraceBack handlers:
519 521
520 522 # Syntax error handler.
521 523 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
522 524
523 525 # The interactive one is initialized with an offset, meaning we always
524 526 # want to remove the topmost item in the traceback, which is our own
525 527 # internal code. Valid modes: ['Plain','Context','Verbose']
526 528 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
527 529 color_scheme='NoColor',
528 530 tb_offset = 1)
529 531
530 532 # IPython itself shouldn't crash. This will produce a detailed
531 533 # post-mortem if it does. But we only install the crash handler for
532 534 # non-threaded shells, the threaded ones use a normal verbose reporter
533 535 # and lose the crash handler. This is because exceptions in the main
534 536 # thread (such as in GUI code) propagate directly to sys.excepthook,
535 537 # and there's no point in printing crash dumps for every user exception.
536 538 if self.isthreaded:
537 539 ipCrashHandler = ultraTB.FormattedTB()
538 540 else:
539 541 from IPython import CrashHandler
540 542 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
541 543 self.set_crash_handler(ipCrashHandler)
542 544
543 545 # and add any custom exception handlers the user may have specified
544 546 self.set_custom_exc(*custom_exceptions)
545 547
546 548 # indentation management
547 549 self.autoindent = False
548 550 self.indent_current_nsp = 0
549 551
550 552 # Make some aliases automatically
551 553 # Prepare list of shell aliases to auto-define
552 554 if os.name == 'posix':
553 555 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
554 556 'mv mv -i','rm rm -i','cp cp -i',
555 557 'cat cat','less less','clear clear',
556 558 # a better ls
557 559 'ls ls -F',
558 560 # long ls
559 561 'll ls -lF')
560 562 # Extra ls aliases with color, which need special treatment on BSD
561 563 # variants
562 564 ls_extra = ( # color ls
563 565 'lc ls -F -o --color',
564 566 # ls normal files only
565 567 'lf ls -F -o --color %l | grep ^-',
566 568 # ls symbolic links
567 569 'lk ls -F -o --color %l | grep ^l',
568 570 # directories or links to directories,
569 571 'ldir ls -F -o --color %l | grep /$',
570 572 # things which are executable
571 573 'lx ls -F -o --color %l | grep ^-..x',
572 574 )
573 575 # The BSDs don't ship GNU ls, so they don't understand the
574 576 # --color switch out of the box
575 577 if 'bsd' in sys.platform:
576 578 ls_extra = ( # ls normal files only
577 579 'lf ls -lF | grep ^-',
578 580 # ls symbolic links
579 581 'lk ls -lF | grep ^l',
580 582 # directories or links to directories,
581 583 'ldir ls -lF | grep /$',
582 584 # things which are executable
583 585 'lx ls -lF | grep ^-..x',
584 586 )
585 587 auto_alias = auto_alias + ls_extra
586 588 elif os.name in ['nt','dos']:
587 589 auto_alias = ('ls dir /on',
588 590 'ddir dir /ad /on', 'ldir dir /ad /on',
589 591 'mkdir mkdir','rmdir rmdir','echo echo',
590 592 'ren ren','cls cls','copy copy')
591 593 else:
592 594 auto_alias = ()
593 595 self.auto_alias = [s.split(None,1) for s in auto_alias]
594 596
595 597
596 598 # Produce a public API instance
597 599 self.api = IPython.ipapi.IPApi(self)
598 600
599 601 # Call the actual (public) initializer
600 602 self.init_auto_alias()
601 603
602 604 # track which builtins we add, so we can clean up later
603 605 self.builtins_added = {}
604 606 # This method will add the necessary builtins for operation, but
605 607 # tracking what it did via the builtins_added dict.
606 608
607 609 #TODO: remove this, redundant
608 610 self.add_builtins()
609 611
610 612
611 613
612 614
613 615 # end __init__
614 616
615 617 def var_expand(self,cmd,depth=0):
616 618 """Expand python variables in a string.
617 619
618 620 The depth argument indicates how many frames above the caller should
619 621 be walked to look for the local namespace where to expand variables.
620 622
621 623 The global namespace for expansion is always the user's interactive
622 624 namespace.
623 625 """
624 626
625 627 return str(ItplNS(cmd,
626 628 self.user_ns, # globals
627 629 # Skip our own frame in searching for locals:
628 630 sys._getframe(depth+1).f_locals # locals
629 631 ))
630 632
631 633 def pre_config_initialization(self):
632 634 """Pre-configuration init method
633 635
634 636 This is called before the configuration files are processed to
635 637 prepare the services the config files might need.
636 638
637 639 self.rc already has reasonable default values at this point.
638 640 """
639 641 rc = self.rc
640 642 try:
641 643 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
642 644 except exceptions.UnicodeDecodeError:
643 645 print "Your ipythondir can't be decoded to unicode!"
644 646 print "Please set HOME environment variable to something that"
645 647 print r"only has ASCII characters, e.g. c:\home"
646 648 print "Now it is",rc.ipythondir
647 649 sys.exit()
648 650 self.shadowhist = IPython.history.ShadowHist(self.db)
649 651
650 652
651 653 def post_config_initialization(self):
652 654 """Post configuration init method
653 655
654 656 This is called after the configuration files have been processed to
655 657 'finalize' the initialization."""
656 658
657 659 rc = self.rc
658 660
659 661 # Object inspector
660 662 self.inspector = OInspect.Inspector(OInspect.InspectColors,
661 663 PyColorize.ANSICodeColors,
662 664 'NoColor',
663 665 rc.object_info_string_level)
664 666
665 667 self.rl_next_input = None
666 668 self.rl_do_indent = False
667 669 # Load readline proper
668 670 if rc.readline:
669 671 self.init_readline()
670 672
671 673
672 674 # local shortcut, this is used a LOT
673 675 self.log = self.logger.log
674 676
675 677 # Initialize cache, set in/out prompts and printing system
676 678 self.outputcache = CachedOutput(self,
677 679 rc.cache_size,
678 680 rc.pprint,
679 681 input_sep = rc.separate_in,
680 682 output_sep = rc.separate_out,
681 683 output_sep2 = rc.separate_out2,
682 684 ps1 = rc.prompt_in1,
683 685 ps2 = rc.prompt_in2,
684 686 ps_out = rc.prompt_out,
685 687 pad_left = rc.prompts_pad_left)
686 688
687 689 # user may have over-ridden the default print hook:
688 690 try:
689 691 self.outputcache.__class__.display = self.hooks.display
690 692 except AttributeError:
691 693 pass
692 694
693 695 # I don't like assigning globally to sys, because it means when
694 696 # embedding instances, each embedded instance overrides the previous
695 697 # choice. But sys.displayhook seems to be called internally by exec,
696 698 # so I don't see a way around it. We first save the original and then
697 699 # overwrite it.
698 700 self.sys_displayhook = sys.displayhook
699 701 sys.displayhook = self.outputcache
700 702
701 703 # Do a proper resetting of doctest, including the necessary displayhook
702 704 # monkeypatching
703 705 doctest_reload()
704 706
705 707 # Set user colors (don't do it in the constructor above so that it
706 708 # doesn't crash if colors option is invalid)
707 709 self.magic_colors(rc.colors)
708 710
709 711 # Set calling of pdb on exceptions
710 712 self.call_pdb = rc.pdb
711 713
712 714 # Load user aliases
713 715 for alias in rc.alias:
714 716 self.magic_alias(alias)
715 717
716 718 self.hooks.late_startup_hook()
717 719
718 720 for cmd in self.rc.autoexec:
719 721 #print "autoexec>",cmd #dbg
720 722 self.api.runlines(cmd)
721 723
722 724 batchrun = False
723 725 for batchfile in [path(arg) for arg in self.rc.args
724 726 if arg.lower().endswith('.ipy')]:
725 727 if not batchfile.isfile():
726 728 print "No such batch file:", batchfile
727 729 continue
728 730 self.api.runlines(batchfile.text())
729 731 batchrun = True
730 732 # without -i option, exit after running the batch file
731 733 if batchrun and not self.rc.interact:
732 734 self.exit_now = True
733 735
734 736 def add_builtins(self):
735 737 """Store ipython references into the builtin namespace.
736 738
737 739 Some parts of ipython operate via builtins injected here, which hold a
738 740 reference to IPython itself."""
739 741
740 742 # TODO: deprecate all of these, they are unsafe
741 743 builtins_new = dict(__IPYTHON__ = self,
742 744 ip_set_hook = self.set_hook,
743 745 jobs = self.jobs,
744 746 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
745 747 ipalias = wrap_deprecated(self.ipalias),
746 748 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
747 749 #_ip = self.api
748 750 )
749 751 for biname,bival in builtins_new.items():
750 752 try:
751 753 # store the orignal value so we can restore it
752 754 self.builtins_added[biname] = __builtin__.__dict__[biname]
753 755 except KeyError:
754 756 # or mark that it wasn't defined, and we'll just delete it at
755 757 # cleanup
756 758 self.builtins_added[biname] = Undefined
757 759 __builtin__.__dict__[biname] = bival
758 760
759 761 # Keep in the builtins a flag for when IPython is active. We set it
760 762 # with setdefault so that multiple nested IPythons don't clobber one
761 763 # another. Each will increase its value by one upon being activated,
762 764 # which also gives us a way to determine the nesting level.
763 765 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
764 766
765 767 def clean_builtins(self):
766 768 """Remove any builtins which might have been added by add_builtins, or
767 769 restore overwritten ones to their previous values."""
768 770 for biname,bival in self.builtins_added.items():
769 771 if bival is Undefined:
770 772 del __builtin__.__dict__[biname]
771 773 else:
772 774 __builtin__.__dict__[biname] = bival
773 775 self.builtins_added.clear()
774 776
775 777 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
776 778 """set_hook(name,hook) -> sets an internal IPython hook.
777 779
778 780 IPython exposes some of its internal API as user-modifiable hooks. By
779 781 adding your function to one of these hooks, you can modify IPython's
780 782 behavior to call at runtime your own routines."""
781 783
782 784 # At some point in the future, this should validate the hook before it
783 785 # accepts it. Probably at least check that the hook takes the number
784 786 # of args it's supposed to.
785 787
786 788 f = new.instancemethod(hook,self,self.__class__)
787 789
788 790 # check if the hook is for strdispatcher first
789 791 if str_key is not None:
790 792 sdp = self.strdispatchers.get(name, StrDispatch())
791 793 sdp.add_s(str_key, f, priority )
792 794 self.strdispatchers[name] = sdp
793 795 return
794 796 if re_key is not None:
795 797 sdp = self.strdispatchers.get(name, StrDispatch())
796 798 sdp.add_re(re.compile(re_key), f, priority )
797 799 self.strdispatchers[name] = sdp
798 800 return
799 801
800 802 dp = getattr(self.hooks, name, None)
801 803 if name not in IPython.hooks.__all__:
802 804 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
803 805 if not dp:
804 806 dp = IPython.hooks.CommandChainDispatcher()
805 807
806 808 try:
807 809 dp.add(f,priority)
808 810 except AttributeError:
809 811 # it was not commandchain, plain old func - replace
810 812 dp = f
811 813
812 814 setattr(self.hooks,name, dp)
813 815
814 816
815 817 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
816 818
817 819 def set_crash_handler(self,crashHandler):
818 820 """Set the IPython crash handler.
819 821
820 822 This must be a callable with a signature suitable for use as
821 823 sys.excepthook."""
822 824
823 825 # Install the given crash handler as the Python exception hook
824 826 sys.excepthook = crashHandler
825 827
826 828 # The instance will store a pointer to this, so that runtime code
827 829 # (such as magics) can access it. This is because during the
828 830 # read-eval loop, it gets temporarily overwritten (to deal with GUI
829 831 # frameworks).
830 832 self.sys_excepthook = sys.excepthook
831 833
832 834
833 835 def set_custom_exc(self,exc_tuple,handler):
834 836 """set_custom_exc(exc_tuple,handler)
835 837
836 838 Set a custom exception handler, which will be called if any of the
837 839 exceptions in exc_tuple occur in the mainloop (specifically, in the
838 840 runcode() method.
839 841
840 842 Inputs:
841 843
842 844 - exc_tuple: a *tuple* of valid exceptions to call the defined
843 845 handler for. It is very important that you use a tuple, and NOT A
844 846 LIST here, because of the way Python's except statement works. If
845 847 you only want to trap a single exception, use a singleton tuple:
846 848
847 849 exc_tuple == (MyCustomException,)
848 850
849 851 - handler: this must be defined as a function with the following
850 852 basic interface: def my_handler(self,etype,value,tb).
851 853
852 854 This will be made into an instance method (via new.instancemethod)
853 855 of IPython itself, and it will be called if any of the exceptions
854 856 listed in the exc_tuple are caught. If the handler is None, an
855 857 internal basic one is used, which just prints basic info.
856 858
857 859 WARNING: by putting in your own exception handler into IPython's main
858 860 execution loop, you run a very good chance of nasty crashes. This
859 861 facility should only be used if you really know what you are doing."""
860 862
861 863 assert type(exc_tuple)==type(()) , \
862 864 "The custom exceptions must be given AS A TUPLE."
863 865
864 866 def dummy_handler(self,etype,value,tb):
865 867 print '*** Simple custom exception handler ***'
866 868 print 'Exception type :',etype
867 869 print 'Exception value:',value
868 870 print 'Traceback :',tb
869 871 print 'Source code :','\n'.join(self.buffer)
870 872
871 873 if handler is None: handler = dummy_handler
872 874
873 875 self.CustomTB = new.instancemethod(handler,self,self.__class__)
874 876 self.custom_exceptions = exc_tuple
875 877
876 878 def set_custom_completer(self,completer,pos=0):
877 879 """set_custom_completer(completer,pos=0)
878 880
879 881 Adds a new custom completer function.
880 882
881 883 The position argument (defaults to 0) is the index in the completers
882 884 list where you want the completer to be inserted."""
883 885
884 886 newcomp = new.instancemethod(completer,self.Completer,
885 887 self.Completer.__class__)
886 888 self.Completer.matchers.insert(pos,newcomp)
887 889
888 890 def set_completer(self):
889 891 """reset readline's completer to be our own."""
890 892 self.readline.set_completer(self.Completer.complete)
891 893
892 894 def _get_call_pdb(self):
893 895 return self._call_pdb
894 896
895 897 def _set_call_pdb(self,val):
896 898
897 899 if val not in (0,1,False,True):
898 900 raise ValueError,'new call_pdb value must be boolean'
899 901
900 902 # store value in instance
901 903 self._call_pdb = val
902 904
903 905 # notify the actual exception handlers
904 906 self.InteractiveTB.call_pdb = val
905 907 if self.isthreaded:
906 908 try:
907 909 self.sys_excepthook.call_pdb = val
908 910 except:
909 911 warn('Failed to activate pdb for threaded exception handler')
910 912
911 913 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
912 914 'Control auto-activation of pdb at exceptions')
913 915
914 916
915 917 # These special functions get installed in the builtin namespace, to
916 918 # provide programmatic (pure python) access to magics, aliases and system
917 919 # calls. This is important for logging, user scripting, and more.
918 920
919 921 # We are basically exposing, via normal python functions, the three
920 922 # mechanisms in which ipython offers special call modes (magics for
921 923 # internal control, aliases for direct system access via pre-selected
922 924 # names, and !cmd for calling arbitrary system commands).
923 925
924 926 def ipmagic(self,arg_s):
925 927 """Call a magic function by name.
926 928
927 929 Input: a string containing the name of the magic function to call and any
928 930 additional arguments to be passed to the magic.
929 931
930 932 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
931 933 prompt:
932 934
933 935 In[1]: %name -opt foo bar
934 936
935 937 To call a magic without arguments, simply use ipmagic('name').
936 938
937 939 This provides a proper Python function to call IPython's magics in any
938 940 valid Python code you can type at the interpreter, including loops and
939 941 compound statements. It is added by IPython to the Python builtin
940 942 namespace upon initialization."""
941 943
942 944 args = arg_s.split(' ',1)
943 945 magic_name = args[0]
944 946 magic_name = magic_name.lstrip(self.ESC_MAGIC)
945 947
946 948 try:
947 949 magic_args = args[1]
948 950 except IndexError:
949 951 magic_args = ''
950 952 fn = getattr(self,'magic_'+magic_name,None)
951 953 if fn is None:
952 954 error("Magic function `%s` not found." % magic_name)
953 955 else:
954 956 magic_args = self.var_expand(magic_args,1)
955 957 return fn(magic_args)
956 958
957 959 def ipalias(self,arg_s):
958 960 """Call an alias by name.
959 961
960 962 Input: a string containing the name of the alias to call and any
961 963 additional arguments to be passed to the magic.
962 964
963 965 ipalias('name -opt foo bar') is equivalent to typing at the ipython
964 966 prompt:
965 967
966 968 In[1]: name -opt foo bar
967 969
968 970 To call an alias without arguments, simply use ipalias('name').
969 971
970 972 This provides a proper Python function to call IPython's aliases in any
971 973 valid Python code you can type at the interpreter, including loops and
972 974 compound statements. It is added by IPython to the Python builtin
973 975 namespace upon initialization."""
974 976
975 977 args = arg_s.split(' ',1)
976 978 alias_name = args[0]
977 979 try:
978 980 alias_args = args[1]
979 981 except IndexError:
980 982 alias_args = ''
981 983 if alias_name in self.alias_table:
982 984 self.call_alias(alias_name,alias_args)
983 985 else:
984 986 error("Alias `%s` not found." % alias_name)
985 987
986 988 def ipsystem(self,arg_s):
987 989 """Make a system call, using IPython."""
988 990
989 991 self.system(arg_s)
990 992
991 993 def complete(self,text):
992 994 """Return a sorted list of all possible completions on text.
993 995
994 996 Inputs:
995 997
996 998 - text: a string of text to be completed on.
997 999
998 1000 This is a wrapper around the completion mechanism, similar to what
999 1001 readline does at the command line when the TAB key is hit. By
1000 1002 exposing it as a method, it can be used by other non-readline
1001 1003 environments (such as GUIs) for text completion.
1002 1004
1003 1005 Simple usage example:
1004 1006
1005 1007 In [1]: x = 'hello'
1006 1008
1007 1009 In [2]: __IP.complete('x.l')
1008 1010 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
1009 1011
1010 1012 complete = self.Completer.complete
1011 1013 state = 0
1012 1014 # use a dict so we get unique keys, since ipyhton's multiple
1013 1015 # completers can return duplicates. When we make 2.4 a requirement,
1014 1016 # start using sets instead, which are faster.
1015 1017 comps = {}
1016 1018 while True:
1017 1019 newcomp = complete(text,state,line_buffer=text)
1018 1020 if newcomp is None:
1019 1021 break
1020 1022 comps[newcomp] = 1
1021 1023 state += 1
1022 1024 outcomps = comps.keys()
1023 1025 outcomps.sort()
1024 1026 return outcomps
1025 1027
1026 1028 def set_completer_frame(self, frame=None):
1027 1029 if frame:
1028 1030 self.Completer.namespace = frame.f_locals
1029 1031 self.Completer.global_namespace = frame.f_globals
1030 1032 else:
1031 1033 self.Completer.namespace = self.user_ns
1032 1034 self.Completer.global_namespace = self.user_global_ns
1033 1035
1034 1036 def init_auto_alias(self):
1035 1037 """Define some aliases automatically.
1036 1038
1037 1039 These are ALL parameter-less aliases"""
1038 1040
1039 1041 for alias,cmd in self.auto_alias:
1040 1042 self.getapi().defalias(alias,cmd)
1041 1043
1042 1044
1043 1045 def alias_table_validate(self,verbose=0):
1044 1046 """Update information about the alias table.
1045 1047
1046 1048 In particular, make sure no Python keywords/builtins are in it."""
1047 1049
1048 1050 no_alias = self.no_alias
1049 1051 for k in self.alias_table.keys():
1050 1052 if k in no_alias:
1051 1053 del self.alias_table[k]
1052 1054 if verbose:
1053 1055 print ("Deleting alias <%s>, it's a Python "
1054 1056 "keyword or builtin." % k)
1055 1057
1056 1058 def set_autoindent(self,value=None):
1057 1059 """Set the autoindent flag, checking for readline support.
1058 1060
1059 1061 If called with no arguments, it acts as a toggle."""
1060 1062
1061 1063 if not self.has_readline:
1062 1064 if os.name == 'posix':
1063 1065 warn("The auto-indent feature requires the readline library")
1064 1066 self.autoindent = 0
1065 1067 return
1066 1068 if value is None:
1067 1069 self.autoindent = not self.autoindent
1068 1070 else:
1069 1071 self.autoindent = value
1070 1072
1071 1073 def rc_set_toggle(self,rc_field,value=None):
1072 1074 """Set or toggle a field in IPython's rc config. structure.
1073 1075
1074 1076 If called with no arguments, it acts as a toggle.
1075 1077
1076 1078 If called with a non-existent field, the resulting AttributeError
1077 1079 exception will propagate out."""
1078 1080
1079 1081 rc_val = getattr(self.rc,rc_field)
1080 1082 if value is None:
1081 1083 value = not rc_val
1082 1084 setattr(self.rc,rc_field,value)
1083 1085
1084 1086 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1085 1087 """Install the user configuration directory.
1086 1088
1087 1089 Can be called when running for the first time or to upgrade the user's
1088 1090 .ipython/ directory with the mode parameter. Valid modes are 'install'
1089 1091 and 'upgrade'."""
1090 1092
1091 1093 def wait():
1092 1094 try:
1093 1095 raw_input("Please press <RETURN> to start IPython.")
1094 1096 except EOFError:
1095 1097 print >> Term.cout
1096 1098 print '*'*70
1097 1099
1098 1100 cwd = os.getcwd() # remember where we started
1099 1101 glb = glob.glob
1100 1102 print '*'*70
1101 1103 if mode == 'install':
1102 1104 print \
1103 1105 """Welcome to IPython. I will try to create a personal configuration directory
1104 1106 where you can customize many aspects of IPython's functionality in:\n"""
1105 1107 else:
1106 1108 print 'I am going to upgrade your configuration in:'
1107 1109
1108 1110 print ipythondir
1109 1111
1110 1112 rcdirend = os.path.join('IPython','UserConfig')
1111 1113 cfg = lambda d: os.path.join(d,rcdirend)
1112 1114 try:
1113 1115 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1114 1116 print "Initializing from configuration",rcdir
1115 1117 except IndexError:
1116 1118 warning = """
1117 1119 Installation error. IPython's directory was not found.
1118 1120
1119 1121 Check the following:
1120 1122
1121 1123 The ipython/IPython directory should be in a directory belonging to your
1122 1124 PYTHONPATH environment variable (that is, it should be in a directory
1123 1125 belonging to sys.path). You can copy it explicitly there or just link to it.
1124 1126
1125 1127 IPython will create a minimal default configuration for you.
1126 1128
1127 1129 """
1128 1130 warn(warning)
1129 1131 wait()
1130 1132
1131 1133 if sys.platform =='win32':
1132 1134 inif = 'ipythonrc.ini'
1133 1135 else:
1134 1136 inif = 'ipythonrc'
1135 1137 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1136 1138 os.makedirs(ipythondir, mode = 0777)
1137 1139 for f, cont in minimal_setup.items():
1138 1140 open(ipythondir + '/' + f,'w').write(cont)
1139 1141
1140 1142 return
1141 1143
1142 1144 if mode == 'install':
1143 1145 try:
1144 1146 shutil.copytree(rcdir,ipythondir)
1145 1147 os.chdir(ipythondir)
1146 1148 rc_files = glb("ipythonrc*")
1147 1149 for rc_file in rc_files:
1148 1150 os.rename(rc_file,rc_file+rc_suffix)
1149 1151 except:
1150 1152 warning = """
1151 1153
1152 1154 There was a problem with the installation:
1153 1155 %s
1154 1156 Try to correct it or contact the developers if you think it's a bug.
1155 1157 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1156 1158 warn(warning)
1157 1159 wait()
1158 1160 return
1159 1161
1160 1162 elif mode == 'upgrade':
1161 1163 try:
1162 1164 os.chdir(ipythondir)
1163 1165 except:
1164 1166 print """
1165 1167 Can not upgrade: changing to directory %s failed. Details:
1166 1168 %s
1167 1169 """ % (ipythondir,sys.exc_info()[1])
1168 1170 wait()
1169 1171 return
1170 1172 else:
1171 1173 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1172 1174 for new_full_path in sources:
1173 1175 new_filename = os.path.basename(new_full_path)
1174 1176 if new_filename.startswith('ipythonrc'):
1175 1177 new_filename = new_filename + rc_suffix
1176 1178 # The config directory should only contain files, skip any
1177 1179 # directories which may be there (like CVS)
1178 1180 if os.path.isdir(new_full_path):
1179 1181 continue
1180 1182 if os.path.exists(new_filename):
1181 1183 old_file = new_filename+'.old'
1182 1184 if os.path.exists(old_file):
1183 1185 os.remove(old_file)
1184 1186 os.rename(new_filename,old_file)
1185 1187 shutil.copy(new_full_path,new_filename)
1186 1188 else:
1187 1189 raise ValueError,'unrecognized mode for install:',`mode`
1188 1190
1189 1191 # Fix line-endings to those native to each platform in the config
1190 1192 # directory.
1191 1193 try:
1192 1194 os.chdir(ipythondir)
1193 1195 except:
1194 1196 print """
1195 1197 Problem: changing to directory %s failed.
1196 1198 Details:
1197 1199 %s
1198 1200
1199 1201 Some configuration files may have incorrect line endings. This should not
1200 1202 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1201 1203 wait()
1202 1204 else:
1203 1205 for fname in glb('ipythonrc*'):
1204 1206 try:
1205 1207 native_line_ends(fname,backup=0)
1206 1208 except IOError:
1207 1209 pass
1208 1210
1209 1211 if mode == 'install':
1210 1212 print """
1211 1213 Successful installation!
1212 1214
1213 1215 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1214 1216 IPython manual (there are both HTML and PDF versions supplied with the
1215 1217 distribution) to make sure that your system environment is properly configured
1216 1218 to take advantage of IPython's features.
1217 1219
1218 1220 Important note: the configuration system has changed! The old system is
1219 1221 still in place, but its setting may be partly overridden by the settings in
1220 1222 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1221 1223 if some of the new settings bother you.
1222 1224
1223 1225 """
1224 1226 else:
1225 1227 print """
1226 1228 Successful upgrade!
1227 1229
1228 1230 All files in your directory:
1229 1231 %(ipythondir)s
1230 1232 which would have been overwritten by the upgrade were backed up with a .old
1231 1233 extension. If you had made particular customizations in those files you may
1232 1234 want to merge them back into the new files.""" % locals()
1233 1235 wait()
1234 1236 os.chdir(cwd)
1235 1237 # end user_setup()
1236 1238
1237 1239 def atexit_operations(self):
1238 1240 """This will be executed at the time of exit.
1239 1241
1240 1242 Saving of persistent data should be performed here. """
1241 1243
1242 1244 #print '*** IPython exit cleanup ***' # dbg
1243 1245 # input history
1244 1246 self.savehist()
1245 1247
1246 1248 # Cleanup all tempfiles left around
1247 1249 for tfile in self.tempfiles:
1248 1250 try:
1249 1251 os.unlink(tfile)
1250 1252 except OSError:
1251 1253 pass
1252 1254
1253 1255 self.hooks.shutdown_hook()
1254 1256
1255 1257 def savehist(self):
1256 1258 """Save input history to a file (via readline library)."""
1257 1259
1258 1260 if not self.has_readline:
1259 1261 return
1260 1262
1261 1263 try:
1262 1264 self.readline.write_history_file(self.histfile)
1263 1265 except:
1264 1266 print 'Unable to save IPython command history to file: ' + \
1265 1267 `self.histfile`
1266 1268
1267 1269 def reloadhist(self):
1268 1270 """Reload the input history from disk file."""
1269 1271
1270 1272 if self.has_readline:
1271 1273 try:
1272 1274 self.readline.clear_history()
1273 1275 self.readline.read_history_file(self.shell.histfile)
1274 1276 except AttributeError:
1275 1277 pass
1276 1278
1277 1279
1278 1280 def history_saving_wrapper(self, func):
1279 1281 """ Wrap func for readline history saving
1280 1282
1281 1283 Convert func into callable that saves & restores
1282 1284 history around the call """
1283 1285
1284 1286 if not self.has_readline:
1285 1287 return func
1286 1288
1287 1289 def wrapper():
1288 1290 self.savehist()
1289 1291 try:
1290 1292 func()
1291 1293 finally:
1292 1294 readline.read_history_file(self.histfile)
1293 1295 return wrapper
1294 1296
1295 1297
1296 1298 def pre_readline(self):
1297 1299 """readline hook to be used at the start of each line.
1298 1300
1299 1301 Currently it handles auto-indent only."""
1300 1302
1301 1303 #debugx('self.indent_current_nsp','pre_readline:')
1302 1304
1303 1305 if self.rl_do_indent:
1304 1306 self.readline.insert_text(self.indent_current_str())
1305 1307 if self.rl_next_input is not None:
1306 1308 self.readline.insert_text(self.rl_next_input)
1307 1309 self.rl_next_input = None
1308 1310
1309 1311 def init_readline(self):
1310 1312 """Command history completion/saving/reloading."""
1311 1313
1312 1314
1313 1315 import IPython.rlineimpl as readline
1314 1316
1315 1317 if not readline.have_readline:
1316 1318 self.has_readline = 0
1317 1319 self.readline = None
1318 1320 # no point in bugging windows users with this every time:
1319 1321 warn('Readline services not available on this platform.')
1320 1322 else:
1321 1323 sys.modules['readline'] = readline
1322 1324 import atexit
1323 1325 from IPython.completer import IPCompleter
1324 1326 self.Completer = IPCompleter(self,
1325 1327 self.user_ns,
1326 1328 self.user_global_ns,
1327 1329 self.rc.readline_omit__names,
1328 1330 self.alias_table)
1329 1331 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1330 1332 self.strdispatchers['complete_command'] = sdisp
1331 1333 self.Completer.custom_completers = sdisp
1332 1334 # Platform-specific configuration
1333 1335 if os.name == 'nt':
1334 1336 self.readline_startup_hook = readline.set_pre_input_hook
1335 1337 else:
1336 1338 self.readline_startup_hook = readline.set_startup_hook
1337 1339
1338 1340 # Load user's initrc file (readline config)
1339 1341 # Or if libedit is used, load editrc.
1340 1342 inputrc_name = os.environ.get('INPUTRC')
1341 1343 if inputrc_name is None:
1342 1344 home_dir = get_home_dir()
1343 1345 if home_dir is not None:
1344 1346 inputrc_name = '.inputrc'
1345 1347 if readline.uses_libedit:
1346 1348 inputrc_name = '.editrc'
1347 1349 inputrc_name = os.path.join(home_dir, inputrc_name)
1348 1350 if os.path.isfile(inputrc_name):
1349 1351 try:
1350 1352 readline.read_init_file(inputrc_name)
1351 1353 except:
1352 1354 warn('Problems reading readline initialization file <%s>'
1353 1355 % inputrc_name)
1354 1356
1355 1357 self.has_readline = 1
1356 1358 self.readline = readline
1357 1359 # save this in sys so embedded copies can restore it properly
1358 1360 sys.ipcompleter = self.Completer.complete
1359 1361 self.set_completer()
1360 1362
1361 1363 # Configure readline according to user's prefs
1362 1364 # This is only done if GNU readline is being used. If libedit
1363 1365 # is being used (as on Leopard) the readline config is
1364 1366 # not run as the syntax for libedit is different.
1365 1367 if not readline.uses_libedit:
1366 1368 for rlcommand in self.rc.readline_parse_and_bind:
1367 1369 readline.parse_and_bind(rlcommand)
1368 1370
1369 1371 # remove some chars from the delimiters list
1370 1372 delims = readline.get_completer_delims()
1371 1373 delims = delims.translate(string._idmap,
1372 1374 self.rc.readline_remove_delims)
1373 1375 readline.set_completer_delims(delims)
1374 1376 # otherwise we end up with a monster history after a while:
1375 1377 readline.set_history_length(1000)
1376 1378 try:
1377 1379 #print '*** Reading readline history' # dbg
1378 1380 readline.read_history_file(self.histfile)
1379 1381 except IOError:
1380 1382 pass # It doesn't exist yet.
1381 1383
1382 1384 atexit.register(self.atexit_operations)
1383 1385 del atexit
1384 1386
1385 1387 # Configure auto-indent for all platforms
1386 1388 self.set_autoindent(self.rc.autoindent)
1387 1389
1388 1390 def ask_yes_no(self,prompt,default=True):
1389 1391 if self.rc.quiet:
1390 1392 return True
1391 1393 return ask_yes_no(prompt,default)
1392 1394
1393 1395 def _should_recompile(self,e):
1394 1396 """Utility routine for edit_syntax_error"""
1395 1397
1396 1398 if e.filename in ('<ipython console>','<input>','<string>',
1397 1399 '<console>','<BackgroundJob compilation>',
1398 1400 None):
1399 1401
1400 1402 return False
1401 1403 try:
1402 1404 if (self.rc.autoedit_syntax and
1403 1405 not self.ask_yes_no('Return to editor to correct syntax error? '
1404 1406 '[Y/n] ','y')):
1405 1407 return False
1406 1408 except EOFError:
1407 1409 return False
1408 1410
1409 1411 def int0(x):
1410 1412 try:
1411 1413 return int(x)
1412 1414 except TypeError:
1413 1415 return 0
1414 1416 # always pass integer line and offset values to editor hook
1415 1417 self.hooks.fix_error_editor(e.filename,
1416 1418 int0(e.lineno),int0(e.offset),e.msg)
1417 1419 return True
1418 1420
1419 1421 def edit_syntax_error(self):
1420 1422 """The bottom half of the syntax error handler called in the main loop.
1421 1423
1422 1424 Loop until syntax error is fixed or user cancels.
1423 1425 """
1424 1426
1425 1427 while self.SyntaxTB.last_syntax_error:
1426 1428 # copy and clear last_syntax_error
1427 1429 err = self.SyntaxTB.clear_err_state()
1428 1430 if not self._should_recompile(err):
1429 1431 return
1430 1432 try:
1431 1433 # may set last_syntax_error again if a SyntaxError is raised
1432 1434 self.safe_execfile(err.filename,self.user_ns)
1433 1435 except:
1434 1436 self.showtraceback()
1435 1437 else:
1436 1438 try:
1437 1439 f = file(err.filename)
1438 1440 try:
1439 1441 sys.displayhook(f.read())
1440 1442 finally:
1441 1443 f.close()
1442 1444 except:
1443 1445 self.showtraceback()
1444 1446
1445 1447 def showsyntaxerror(self, filename=None):
1446 1448 """Display the syntax error that just occurred.
1447 1449
1448 1450 This doesn't display a stack trace because there isn't one.
1449 1451
1450 1452 If a filename is given, it is stuffed in the exception instead
1451 1453 of what was there before (because Python's parser always uses
1452 1454 "<string>" when reading from a string).
1453 1455 """
1454 1456 etype, value, last_traceback = sys.exc_info()
1455 1457
1456 1458 # See note about these variables in showtraceback() below
1457 1459 sys.last_type = etype
1458 1460 sys.last_value = value
1459 1461 sys.last_traceback = last_traceback
1460 1462
1461 1463 if filename and etype is SyntaxError:
1462 1464 # Work hard to stuff the correct filename in the exception
1463 1465 try:
1464 1466 msg, (dummy_filename, lineno, offset, line) = value
1465 1467 except:
1466 1468 # Not the format we expect; leave it alone
1467 1469 pass
1468 1470 else:
1469 1471 # Stuff in the right filename
1470 1472 try:
1471 1473 # Assume SyntaxError is a class exception
1472 1474 value = SyntaxError(msg, (filename, lineno, offset, line))
1473 1475 except:
1474 1476 # If that failed, assume SyntaxError is a string
1475 1477 value = msg, (filename, lineno, offset, line)
1476 1478 self.SyntaxTB(etype,value,[])
1477 1479
1478 1480 def debugger(self,force=False):
1479 1481 """Call the pydb/pdb debugger.
1480 1482
1481 1483 Keywords:
1482 1484
1483 1485 - force(False): by default, this routine checks the instance call_pdb
1484 1486 flag and does not actually invoke the debugger if the flag is false.
1485 1487 The 'force' option forces the debugger to activate even if the flag
1486 1488 is false.
1487 1489 """
1488 1490
1489 1491 if not (force or self.call_pdb):
1490 1492 return
1491 1493
1492 1494 if not hasattr(sys,'last_traceback'):
1493 1495 error('No traceback has been produced, nothing to debug.')
1494 1496 return
1495 1497
1496 1498 # use pydb if available
1497 1499 if Debugger.has_pydb:
1498 1500 from pydb import pm
1499 1501 else:
1500 1502 # fallback to our internal debugger
1501 1503 pm = lambda : self.InteractiveTB.debugger(force=True)
1502 1504 self.history_saving_wrapper(pm)()
1503 1505
1504 1506 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1505 1507 """Display the exception that just occurred.
1506 1508
1507 1509 If nothing is known about the exception, this is the method which
1508 1510 should be used throughout the code for presenting user tracebacks,
1509 1511 rather than directly invoking the InteractiveTB object.
1510 1512
1511 1513 A specific showsyntaxerror() also exists, but this method can take
1512 1514 care of calling it if needed, so unless you are explicitly catching a
1513 1515 SyntaxError exception, don't try to analyze the stack manually and
1514 1516 simply call this method."""
1515 1517
1516 1518
1517 1519 # Though this won't be called by syntax errors in the input line,
1518 1520 # there may be SyntaxError cases whith imported code.
1519 1521
1520 1522 try:
1521 1523 if exc_tuple is None:
1522 1524 etype, value, tb = sys.exc_info()
1523 1525 else:
1524 1526 etype, value, tb = exc_tuple
1525 1527
1526 1528 if etype is SyntaxError:
1527 1529 self.showsyntaxerror(filename)
1528 1530 elif etype is IPython.ipapi.UsageError:
1529 1531 print "UsageError:", value
1530 1532 else:
1531 1533 # WARNING: these variables are somewhat deprecated and not
1532 1534 # necessarily safe to use in a threaded environment, but tools
1533 1535 # like pdb depend on their existence, so let's set them. If we
1534 1536 # find problems in the field, we'll need to revisit their use.
1535 1537 sys.last_type = etype
1536 1538 sys.last_value = value
1537 1539 sys.last_traceback = tb
1538 1540
1539 1541 if etype in self.custom_exceptions:
1540 1542 self.CustomTB(etype,value,tb)
1541 1543 else:
1542 1544 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1543 1545 if self.InteractiveTB.call_pdb and self.has_readline:
1544 1546 # pdb mucks up readline, fix it back
1545 1547 self.set_completer()
1546 1548 except KeyboardInterrupt:
1547 1549 self.write("\nKeyboardInterrupt\n")
1548 1550
1549 1551
1550 1552
1551 1553 def mainloop(self,banner=None):
1552 1554 """Creates the local namespace and starts the mainloop.
1553 1555
1554 1556 If an optional banner argument is given, it will override the
1555 1557 internally created default banner."""
1556 1558
1557 1559 if self.rc.c: # Emulate Python's -c option
1558 1560 self.exec_init_cmd()
1559 1561 if banner is None:
1560 1562 if not self.rc.banner:
1561 1563 banner = ''
1562 1564 # banner is string? Use it directly!
1563 1565 elif isinstance(self.rc.banner,basestring):
1564 1566 banner = self.rc.banner
1565 1567 else:
1566 1568 banner = self.BANNER+self.banner2
1567 1569
1568 1570 while 1:
1569 1571 try:
1570 1572 self.interact(banner)
1571 1573 #self.interact_with_readline()
1572 1574 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1573 1575
1574 1576 break
1575 1577 except KeyboardInterrupt:
1576 1578 # this should not be necessary, but KeyboardInterrupt
1577 1579 # handling seems rather unpredictable...
1578 1580 self.write("\nKeyboardInterrupt in interact()\n")
1579 1581
1580 1582 def exec_init_cmd(self):
1581 1583 """Execute a command given at the command line.
1582 1584
1583 1585 This emulates Python's -c option."""
1584 1586
1585 1587 #sys.argv = ['-c']
1586 1588 self.push(self.prefilter(self.rc.c, False))
1587 1589 if not self.rc.interact:
1588 1590 self.exit_now = True
1589 1591
1590 1592 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1591 1593 """Embeds IPython into a running python program.
1592 1594
1593 1595 Input:
1594 1596
1595 1597 - header: An optional header message can be specified.
1596 1598
1597 1599 - local_ns, global_ns: working namespaces. If given as None, the
1598 1600 IPython-initialized one is updated with __main__.__dict__, so that
1599 1601 program variables become visible but user-specific configuration
1600 1602 remains possible.
1601 1603
1602 1604 - stack_depth: specifies how many levels in the stack to go to
1603 1605 looking for namespaces (when local_ns and global_ns are None). This
1604 1606 allows an intermediate caller to make sure that this function gets
1605 1607 the namespace from the intended level in the stack. By default (0)
1606 1608 it will get its locals and globals from the immediate caller.
1607 1609
1608 1610 Warning: it's possible to use this in a program which is being run by
1609 1611 IPython itself (via %run), but some funny things will happen (a few
1610 1612 globals get overwritten). In the future this will be cleaned up, as
1611 1613 there is no fundamental reason why it can't work perfectly."""
1612 1614
1613 1615 # Get locals and globals from caller
1614 1616 if local_ns is None or global_ns is None:
1615 1617 call_frame = sys._getframe(stack_depth).f_back
1616 1618
1617 1619 if local_ns is None:
1618 1620 local_ns = call_frame.f_locals
1619 1621 if global_ns is None:
1620 1622 global_ns = call_frame.f_globals
1621 1623
1622 1624 # Update namespaces and fire up interpreter
1623 1625
1624 1626 # The global one is easy, we can just throw it in
1625 1627 self.user_global_ns = global_ns
1626 1628
1627 1629 # but the user/local one is tricky: ipython needs it to store internal
1628 1630 # data, but we also need the locals. We'll copy locals in the user
1629 1631 # one, but will track what got copied so we can delete them at exit.
1630 1632 # This is so that a later embedded call doesn't see locals from a
1631 1633 # previous call (which most likely existed in a separate scope).
1632 1634 local_varnames = local_ns.keys()
1633 1635 self.user_ns.update(local_ns)
1634 1636
1635 1637 # Patch for global embedding to make sure that things don't overwrite
1636 1638 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1637 1639 # FIXME. Test this a bit more carefully (the if.. is new)
1638 1640 if local_ns is None and global_ns is None:
1639 1641 self.user_global_ns.update(__main__.__dict__)
1640 1642
1641 1643 # make sure the tab-completer has the correct frame information, so it
1642 1644 # actually completes using the frame's locals/globals
1643 1645 self.set_completer_frame()
1644 1646
1645 1647 # before activating the interactive mode, we need to make sure that
1646 1648 # all names in the builtin namespace needed by ipython point to
1647 1649 # ourselves, and not to other instances.
1648 1650 self.add_builtins()
1649 1651
1650 1652 self.interact(header)
1651 1653
1652 1654 # now, purge out the user namespace from anything we might have added
1653 1655 # from the caller's local namespace
1654 1656 delvar = self.user_ns.pop
1655 1657 for var in local_varnames:
1656 1658 delvar(var,None)
1657 1659 # and clean builtins we may have overridden
1658 1660 self.clean_builtins()
1659 1661
1660 1662 def interact_prompt(self):
1661 1663 """ Print the prompt (in read-eval-print loop)
1662 1664
1663 1665 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1664 1666 used in standard IPython flow.
1665 1667 """
1666 1668 if self.more:
1667 1669 try:
1668 1670 prompt = self.hooks.generate_prompt(True)
1669 1671 except:
1670 1672 self.showtraceback()
1671 1673 if self.autoindent:
1672 1674 self.rl_do_indent = True
1673 1675
1674 1676 else:
1675 1677 try:
1676 1678 prompt = self.hooks.generate_prompt(False)
1677 1679 except:
1678 1680 self.showtraceback()
1679 1681 self.write(prompt)
1680 1682
1681 1683 def interact_handle_input(self,line):
1682 1684 """ Handle the input line (in read-eval-print loop)
1683 1685
1684 1686 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1685 1687 used in standard IPython flow.
1686 1688 """
1687 1689 if line.lstrip() == line:
1688 1690 self.shadowhist.add(line.strip())
1689 1691 lineout = self.prefilter(line,self.more)
1690 1692
1691 1693 if line.strip():
1692 1694 if self.more:
1693 1695 self.input_hist_raw[-1] += '%s\n' % line
1694 1696 else:
1695 1697 self.input_hist_raw.append('%s\n' % line)
1696 1698
1697 1699
1698 1700 self.more = self.push(lineout)
1699 1701 if (self.SyntaxTB.last_syntax_error and
1700 1702 self.rc.autoedit_syntax):
1701 1703 self.edit_syntax_error()
1702 1704
1703 1705 def interact_with_readline(self):
1704 1706 """ Demo of using interact_handle_input, interact_prompt
1705 1707
1706 1708 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1707 1709 it should work like this.
1708 1710 """
1709 1711 self.readline_startup_hook(self.pre_readline)
1710 1712 while not self.exit_now:
1711 1713 self.interact_prompt()
1712 1714 if self.more:
1713 1715 self.rl_do_indent = True
1714 1716 else:
1715 1717 self.rl_do_indent = False
1716 1718 line = raw_input_original().decode(self.stdin_encoding)
1717 1719 self.interact_handle_input(line)
1718 1720
1719 1721
1720 1722 def interact(self, banner=None):
1721 1723 """Closely emulate the interactive Python console.
1722 1724
1723 1725 The optional banner argument specify the banner to print
1724 1726 before the first interaction; by default it prints a banner
1725 1727 similar to the one printed by the real Python interpreter,
1726 1728 followed by the current class name in parentheses (so as not
1727 1729 to confuse this with the real interpreter -- since it's so
1728 1730 close!).
1729 1731
1730 1732 """
1731 1733
1732 1734 if self.exit_now:
1733 1735 # batch run -> do not interact
1734 1736 return
1735 1737 cprt = 'Type "copyright", "credits" or "license" for more information.'
1736 1738 if banner is None:
1737 1739 self.write("Python %s on %s\n%s\n(%s)\n" %
1738 1740 (sys.version, sys.platform, cprt,
1739 1741 self.__class__.__name__))
1740 1742 else:
1741 1743 self.write(banner)
1742 1744
1743 1745 more = 0
1744 1746
1745 1747 # Mark activity in the builtins
1746 1748 __builtin__.__dict__['__IPYTHON__active'] += 1
1747 1749
1748 1750 if self.has_readline:
1749 1751 self.readline_startup_hook(self.pre_readline)
1750 1752 # exit_now is set by a call to %Exit or %Quit
1751 1753
1752 1754 while not self.exit_now:
1753 1755 self.hooks.pre_prompt_hook()
1754 1756 if more:
1755 1757 try:
1756 1758 prompt = self.hooks.generate_prompt(True)
1757 1759 except:
1758 1760 self.showtraceback()
1759 1761 if self.autoindent:
1760 1762 self.rl_do_indent = True
1761 1763
1762 1764 else:
1763 1765 try:
1764 1766 prompt = self.hooks.generate_prompt(False)
1765 1767 except:
1766 1768 self.showtraceback()
1767 1769 try:
1768 1770 line = self.raw_input(prompt,more)
1769 1771 if self.exit_now:
1770 1772 # quick exit on sys.std[in|out] close
1771 1773 break
1772 1774 if self.autoindent:
1773 1775 self.rl_do_indent = False
1774 1776
1775 1777 except KeyboardInterrupt:
1776 1778 #double-guard against keyboardinterrupts during kbdint handling
1777 1779 try:
1778 1780 self.write('\nKeyboardInterrupt\n')
1779 1781 self.resetbuffer()
1780 1782 # keep cache in sync with the prompt counter:
1781 1783 self.outputcache.prompt_count -= 1
1782 1784
1783 1785 if self.autoindent:
1784 1786 self.indent_current_nsp = 0
1785 1787 more = 0
1786 1788 except KeyboardInterrupt:
1787 1789 pass
1788 1790 except EOFError:
1789 1791 if self.autoindent:
1790 1792 self.rl_do_indent = False
1791 1793 self.readline_startup_hook(None)
1792 1794 self.write('\n')
1793 1795 self.exit()
1794 1796 except bdb.BdbQuit:
1795 1797 warn('The Python debugger has exited with a BdbQuit exception.\n'
1796 1798 'Because of how pdb handles the stack, it is impossible\n'
1797 1799 'for IPython to properly format this particular exception.\n'
1798 1800 'IPython will resume normal operation.')
1799 1801 except:
1800 1802 # exceptions here are VERY RARE, but they can be triggered
1801 1803 # asynchronously by signal handlers, for example.
1802 1804 self.showtraceback()
1803 1805 else:
1804 1806 more = self.push(line)
1805 1807 if (self.SyntaxTB.last_syntax_error and
1806 1808 self.rc.autoedit_syntax):
1807 1809 self.edit_syntax_error()
1808 1810
1809 1811 # We are off again...
1810 1812 __builtin__.__dict__['__IPYTHON__active'] -= 1
1811 1813
1812 1814 def excepthook(self, etype, value, tb):
1813 1815 """One more defense for GUI apps that call sys.excepthook.
1814 1816
1815 1817 GUI frameworks like wxPython trap exceptions and call
1816 1818 sys.excepthook themselves. I guess this is a feature that
1817 1819 enables them to keep running after exceptions that would
1818 1820 otherwise kill their mainloop. This is a bother for IPython
1819 1821 which excepts to catch all of the program exceptions with a try:
1820 1822 except: statement.
1821 1823
1822 1824 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1823 1825 any app directly invokes sys.excepthook, it will look to the user like
1824 1826 IPython crashed. In order to work around this, we can disable the
1825 1827 CrashHandler and replace it with this excepthook instead, which prints a
1826 1828 regular traceback using our InteractiveTB. In this fashion, apps which
1827 1829 call sys.excepthook will generate a regular-looking exception from
1828 1830 IPython, and the CrashHandler will only be triggered by real IPython
1829 1831 crashes.
1830 1832
1831 1833 This hook should be used sparingly, only in places which are not likely
1832 1834 to be true IPython errors.
1833 1835 """
1834 1836 self.showtraceback((etype,value,tb),tb_offset=0)
1835 1837
1836 1838 def expand_aliases(self,fn,rest):
1837 1839 """ Expand multiple levels of aliases:
1838 1840
1839 1841 if:
1840 1842
1841 1843 alias foo bar /tmp
1842 1844 alias baz foo
1843 1845
1844 1846 then:
1845 1847
1846 1848 baz huhhahhei -> bar /tmp huhhahhei
1847 1849
1848 1850 """
1849 1851 line = fn + " " + rest
1850 1852
1851 1853 done = Set()
1852 1854 while 1:
1853 1855 pre,fn,rest = prefilter.splitUserInput(line,
1854 1856 prefilter.shell_line_split)
1855 1857 if fn in self.alias_table:
1856 1858 if fn in done:
1857 1859 warn("Cyclic alias definition, repeated '%s'" % fn)
1858 1860 return ""
1859 1861 done.add(fn)
1860 1862
1861 1863 l2 = self.transform_alias(fn,rest)
1862 1864 # dir -> dir
1863 1865 # print "alias",line, "->",l2 #dbg
1864 1866 if l2 == line:
1865 1867 break
1866 1868 # ls -> ls -F should not recurse forever
1867 1869 if l2.split(None,1)[0] == line.split(None,1)[0]:
1868 1870 line = l2
1869 1871 break
1870 1872
1871 1873 line=l2
1872 1874
1873 1875
1874 1876 # print "al expand to",line #dbg
1875 1877 else:
1876 1878 break
1877 1879
1878 1880 return line
1879 1881
1880 1882 def transform_alias(self, alias,rest=''):
1881 1883 """ Transform alias to system command string.
1882 1884 """
1883 1885 trg = self.alias_table[alias]
1884 1886
1885 1887 nargs,cmd = trg
1886 1888 # print trg #dbg
1887 1889 if ' ' in cmd and os.path.isfile(cmd):
1888 1890 cmd = '"%s"' % cmd
1889 1891
1890 1892 # Expand the %l special to be the user's input line
1891 1893 if cmd.find('%l') >= 0:
1892 1894 cmd = cmd.replace('%l',rest)
1893 1895 rest = ''
1894 1896 if nargs==0:
1895 1897 # Simple, argument-less aliases
1896 1898 cmd = '%s %s' % (cmd,rest)
1897 1899 else:
1898 1900 # Handle aliases with positional arguments
1899 1901 args = rest.split(None,nargs)
1900 1902 if len(args)< nargs:
1901 1903 error('Alias <%s> requires %s arguments, %s given.' %
1902 1904 (alias,nargs,len(args)))
1903 1905 return None
1904 1906 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1905 1907 # Now call the macro, evaluating in the user's namespace
1906 1908 #print 'new command: <%r>' % cmd # dbg
1907 1909 return cmd
1908 1910
1909 1911 def call_alias(self,alias,rest=''):
1910 1912 """Call an alias given its name and the rest of the line.
1911 1913
1912 1914 This is only used to provide backwards compatibility for users of
1913 1915 ipalias(), use of which is not recommended for anymore."""
1914 1916
1915 1917 # Now call the macro, evaluating in the user's namespace
1916 1918 cmd = self.transform_alias(alias, rest)
1917 1919 try:
1918 1920 self.system(cmd)
1919 1921 except:
1920 1922 self.showtraceback()
1921 1923
1922 1924 def indent_current_str(self):
1923 1925 """return the current level of indentation as a string"""
1924 1926 return self.indent_current_nsp * ' '
1925 1927
1926 1928 def autoindent_update(self,line):
1927 1929 """Keep track of the indent level."""
1928 1930
1929 1931 #debugx('line')
1930 1932 #debugx('self.indent_current_nsp')
1931 1933 if self.autoindent:
1932 1934 if line:
1933 1935 inisp = num_ini_spaces(line)
1934 1936 if inisp < self.indent_current_nsp:
1935 1937 self.indent_current_nsp = inisp
1936 1938
1937 1939 if line[-1] == ':':
1938 1940 self.indent_current_nsp += 4
1939 1941 elif dedent_re.match(line):
1940 1942 self.indent_current_nsp -= 4
1941 1943 else:
1942 1944 self.indent_current_nsp = 0
1943 1945
1944 1946 def runlines(self,lines):
1945 1947 """Run a string of one or more lines of source.
1946 1948
1947 1949 This method is capable of running a string containing multiple source
1948 1950 lines, as if they had been entered at the IPython prompt. Since it
1949 1951 exposes IPython's processing machinery, the given strings can contain
1950 1952 magic calls (%magic), special shell access (!cmd), etc."""
1951 1953
1952 1954 # We must start with a clean buffer, in case this is run from an
1953 1955 # interactive IPython session (via a magic, for example).
1954 1956 self.resetbuffer()
1955 1957 lines = lines.split('\n')
1956 1958 more = 0
1957 1959
1958 1960 for line in lines:
1959 1961 # skip blank lines so we don't mess up the prompt counter, but do
1960 1962 # NOT skip even a blank line if we are in a code block (more is
1961 1963 # true)
1962 1964
1963 1965
1964 1966 if line or more:
1965 1967 # push to raw history, so hist line numbers stay in sync
1966 1968 self.input_hist_raw.append("# " + line + "\n")
1967 1969 more = self.push(self.prefilter(line,more))
1968 1970 # IPython's runsource returns None if there was an error
1969 1971 # compiling the code. This allows us to stop processing right
1970 1972 # away, so the user gets the error message at the right place.
1971 1973 if more is None:
1972 1974 break
1973 1975 else:
1974 1976 self.input_hist_raw.append("\n")
1975 1977 # final newline in case the input didn't have it, so that the code
1976 1978 # actually does get executed
1977 1979 if more:
1978 1980 self.push('\n')
1979 1981
1980 1982 def runsource(self, source, filename='<input>', symbol='single'):
1981 1983 """Compile and run some source in the interpreter.
1982 1984
1983 1985 Arguments are as for compile_command().
1984 1986
1985 1987 One several things can happen:
1986 1988
1987 1989 1) The input is incorrect; compile_command() raised an
1988 1990 exception (SyntaxError or OverflowError). A syntax traceback
1989 1991 will be printed by calling the showsyntaxerror() method.
1990 1992
1991 1993 2) The input is incomplete, and more input is required;
1992 1994 compile_command() returned None. Nothing happens.
1993 1995
1994 1996 3) The input is complete; compile_command() returned a code
1995 1997 object. The code is executed by calling self.runcode() (which
1996 1998 also handles run-time exceptions, except for SystemExit).
1997 1999
1998 2000 The return value is:
1999 2001
2000 2002 - True in case 2
2001 2003
2002 2004 - False in the other cases, unless an exception is raised, where
2003 2005 None is returned instead. This can be used by external callers to
2004 2006 know whether to continue feeding input or not.
2005 2007
2006 2008 The return value can be used to decide whether to use sys.ps1 or
2007 2009 sys.ps2 to prompt the next line."""
2008 2010
2009 2011 # if the source code has leading blanks, add 'if 1:\n' to it
2010 2012 # this allows execution of indented pasted code. It is tempting
2011 2013 # to add '\n' at the end of source to run commands like ' a=1'
2012 2014 # directly, but this fails for more complicated scenarios
2013 2015 source=source.encode(self.stdin_encoding)
2014 2016 if source[:1] in [' ', '\t']:
2015 2017 source = 'if 1:\n%s' % source
2016 2018
2017 2019 try:
2018 2020 code = self.compile(source,filename,symbol)
2019 2021 except (OverflowError, SyntaxError, ValueError, TypeError):
2020 2022 # Case 1
2021 2023 self.showsyntaxerror(filename)
2022 2024 return None
2023 2025
2024 2026 if code is None:
2025 2027 # Case 2
2026 2028 return True
2027 2029
2028 2030 # Case 3
2029 2031 # We store the code object so that threaded shells and
2030 2032 # custom exception handlers can access all this info if needed.
2031 2033 # The source corresponding to this can be obtained from the
2032 2034 # buffer attribute as '\n'.join(self.buffer).
2033 2035 self.code_to_run = code
2034 2036 # now actually execute the code object
2035 2037 if self.runcode(code) == 0:
2036 2038 return False
2037 2039 else:
2038 2040 return None
2039 2041
2040 2042 def runcode(self,code_obj):
2041 2043 """Execute a code object.
2042 2044
2043 2045 When an exception occurs, self.showtraceback() is called to display a
2044 2046 traceback.
2045 2047
2046 2048 Return value: a flag indicating whether the code to be run completed
2047 2049 successfully:
2048 2050
2049 2051 - 0: successful execution.
2050 2052 - 1: an error occurred.
2051 2053 """
2052 2054
2053 2055 # Set our own excepthook in case the user code tries to call it
2054 2056 # directly, so that the IPython crash handler doesn't get triggered
2055 2057 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2056 2058
2057 2059 # we save the original sys.excepthook in the instance, in case config
2058 2060 # code (such as magics) needs access to it.
2059 2061 self.sys_excepthook = old_excepthook
2060 2062 outflag = 1 # happens in more places, so it's easier as default
2061 2063 try:
2062 2064 try:
2063 2065 self.hooks.pre_runcode_hook()
2064 2066 # Embedded instances require separate global/local namespaces
2065 2067 # so they can see both the surrounding (local) namespace and
2066 2068 # the module-level globals when called inside another function.
2067 2069 if self.embedded:
2068 2070 exec code_obj in self.user_global_ns, self.user_ns
2069 2071 # Normal (non-embedded) instances should only have a single
2070 2072 # namespace for user code execution, otherwise functions won't
2071 2073 # see interactive top-level globals.
2072 2074 else:
2073 2075 exec code_obj in self.user_ns
2074 2076 finally:
2075 2077 # Reset our crash handler in place
2076 2078 sys.excepthook = old_excepthook
2077 2079 except SystemExit:
2078 2080 self.resetbuffer()
2079 2081 self.showtraceback()
2080 2082 warn("Type %exit or %quit to exit IPython "
2081 2083 "(%Exit or %Quit do so unconditionally).",level=1)
2082 2084 except self.custom_exceptions:
2083 2085 etype,value,tb = sys.exc_info()
2084 2086 self.CustomTB(etype,value,tb)
2085 2087 except:
2086 2088 self.showtraceback()
2087 2089 else:
2088 2090 outflag = 0
2089 2091 if softspace(sys.stdout, 0):
2090 2092 print
2091 2093 # Flush out code object which has been run (and source)
2092 2094 self.code_to_run = None
2093 2095 return outflag
2094 2096
2095 2097 def push(self, line):
2096 2098 """Push a line to the interpreter.
2097 2099
2098 2100 The line should not have a trailing newline; it may have
2099 2101 internal newlines. The line is appended to a buffer and the
2100 2102 interpreter's runsource() method is called with the
2101 2103 concatenated contents of the buffer as source. If this
2102 2104 indicates that the command was executed or invalid, the buffer
2103 2105 is reset; otherwise, the command is incomplete, and the buffer
2104 2106 is left as it was after the line was appended. The return
2105 2107 value is 1 if more input is required, 0 if the line was dealt
2106 2108 with in some way (this is the same as runsource()).
2107 2109 """
2108 2110
2109 2111 # autoindent management should be done here, and not in the
2110 2112 # interactive loop, since that one is only seen by keyboard input. We
2111 2113 # need this done correctly even for code run via runlines (which uses
2112 2114 # push).
2113 2115
2114 2116 #print 'push line: <%s>' % line # dbg
2115 2117 for subline in line.splitlines():
2116 2118 self.autoindent_update(subline)
2117 2119 self.buffer.append(line)
2118 2120 more = self.runsource('\n'.join(self.buffer), self.filename)
2119 2121 if not more:
2120 2122 self.resetbuffer()
2121 2123 return more
2122 2124
2123 2125 def split_user_input(self, line):
2124 2126 # This is really a hold-over to support ipapi and some extensions
2125 2127 return prefilter.splitUserInput(line)
2126 2128
2127 2129 def resetbuffer(self):
2128 2130 """Reset the input buffer."""
2129 2131 self.buffer[:] = []
2130 2132
2131 2133 def raw_input(self,prompt='',continue_prompt=False):
2132 2134 """Write a prompt and read a line.
2133 2135
2134 2136 The returned line does not include the trailing newline.
2135 2137 When the user enters the EOF key sequence, EOFError is raised.
2136 2138
2137 2139 Optional inputs:
2138 2140
2139 2141 - prompt(''): a string to be printed to prompt the user.
2140 2142
2141 2143 - continue_prompt(False): whether this line is the first one or a
2142 2144 continuation in a sequence of inputs.
2143 2145 """
2144 2146
2145 2147 # Code run by the user may have modified the readline completer state.
2146 2148 # We must ensure that our completer is back in place.
2147 2149 if self.has_readline:
2148 2150 self.set_completer()
2149 2151
2150 2152 try:
2151 2153 line = raw_input_original(prompt).decode(self.stdin_encoding)
2152 2154 except ValueError:
2153 2155 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2154 2156 " or sys.stdout.close()!\nExiting IPython!")
2155 2157 self.exit_now = True
2156 2158 return ""
2157 2159
2158 2160 # Try to be reasonably smart about not re-indenting pasted input more
2159 2161 # than necessary. We do this by trimming out the auto-indent initial
2160 2162 # spaces, if the user's actual input started itself with whitespace.
2161 2163 #debugx('self.buffer[-1]')
2162 2164
2163 2165 if self.autoindent:
2164 2166 if num_ini_spaces(line) > self.indent_current_nsp:
2165 2167 line = line[self.indent_current_nsp:]
2166 2168 self.indent_current_nsp = 0
2167 2169
2168 2170 # store the unfiltered input before the user has any chance to modify
2169 2171 # it.
2170 2172 if line.strip():
2171 2173 if continue_prompt:
2172 2174 self.input_hist_raw[-1] += '%s\n' % line
2173 2175 if self.has_readline: # and some config option is set?
2174 2176 try:
2175 2177 histlen = self.readline.get_current_history_length()
2176 2178 if histlen > 1:
2177 2179 newhist = self.input_hist_raw[-1].rstrip()
2178 2180 self.readline.remove_history_item(histlen-1)
2179 2181 self.readline.replace_history_item(histlen-2,
2180 2182 newhist.encode(self.stdin_encoding))
2181 2183 except AttributeError:
2182 2184 pass # re{move,place}_history_item are new in 2.4.
2183 2185 else:
2184 2186 self.input_hist_raw.append('%s\n' % line)
2185 2187 # only entries starting at first column go to shadow history
2186 2188 if line.lstrip() == line:
2187 2189 self.shadowhist.add(line.strip())
2188 2190 elif not continue_prompt:
2189 2191 self.input_hist_raw.append('\n')
2190 2192 try:
2191 2193 lineout = self.prefilter(line,continue_prompt)
2192 2194 except:
2193 2195 # blanket except, in case a user-defined prefilter crashes, so it
2194 2196 # can't take all of ipython with it.
2195 2197 self.showtraceback()
2196 2198 return ''
2197 2199 else:
2198 2200 return lineout
2199 2201
2200 2202 def _prefilter(self, line, continue_prompt):
2201 2203 """Calls different preprocessors, depending on the form of line."""
2202 2204
2203 2205 # All handlers *must* return a value, even if it's blank ('').
2204 2206
2205 2207 # Lines are NOT logged here. Handlers should process the line as
2206 2208 # needed, update the cache AND log it (so that the input cache array
2207 2209 # stays synced).
2208 2210
2209 2211 #.....................................................................
2210 2212 # Code begins
2211 2213
2212 2214 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2213 2215
2214 2216 # save the line away in case we crash, so the post-mortem handler can
2215 2217 # record it
2216 2218 self._last_input_line = line
2217 2219
2218 2220 #print '***line: <%s>' % line # dbg
2219 2221
2220 2222 if not line:
2221 2223 # Return immediately on purely empty lines, so that if the user
2222 2224 # previously typed some whitespace that started a continuation
2223 2225 # prompt, he can break out of that loop with just an empty line.
2224 2226 # This is how the default python prompt works.
2225 2227
2226 2228 # Only return if the accumulated input buffer was just whitespace!
2227 2229 if ''.join(self.buffer).isspace():
2228 2230 self.buffer[:] = []
2229 2231 return ''
2230 2232
2231 2233 line_info = prefilter.LineInfo(line, continue_prompt)
2232 2234
2233 2235 # the input history needs to track even empty lines
2234 2236 stripped = line.strip()
2235 2237
2236 2238 if not stripped:
2237 2239 if not continue_prompt:
2238 2240 self.outputcache.prompt_count -= 1
2239 2241 return self.handle_normal(line_info)
2240 2242
2241 2243 # print '***cont',continue_prompt # dbg
2242 2244 # special handlers are only allowed for single line statements
2243 2245 if continue_prompt and not self.rc.multi_line_specials:
2244 2246 return self.handle_normal(line_info)
2245 2247
2246 2248
2247 2249 # See whether any pre-existing handler can take care of it
2248 2250 rewritten = self.hooks.input_prefilter(stripped)
2249 2251 if rewritten != stripped: # ok, some prefilter did something
2250 2252 rewritten = line_info.pre + rewritten # add indentation
2251 2253 return self.handle_normal(prefilter.LineInfo(rewritten,
2252 2254 continue_prompt))
2253 2255
2254 2256 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2255 2257
2256 2258 return prefilter.prefilter(line_info, self)
2257 2259
2258 2260
2259 2261 def _prefilter_dumb(self, line, continue_prompt):
2260 2262 """simple prefilter function, for debugging"""
2261 2263 return self.handle_normal(line,continue_prompt)
2262 2264
2263 2265
2264 2266 def multiline_prefilter(self, line, continue_prompt):
2265 2267 """ Run _prefilter for each line of input
2266 2268
2267 2269 Covers cases where there are multiple lines in the user entry,
2268 2270 which is the case when the user goes back to a multiline history
2269 2271 entry and presses enter.
2270 2272
2271 2273 """
2272 2274 out = []
2273 2275 for l in line.rstrip('\n').split('\n'):
2274 2276 out.append(self._prefilter(l, continue_prompt))
2275 2277 return '\n'.join(out)
2276 2278
2277 2279 # Set the default prefilter() function (this can be user-overridden)
2278 2280 prefilter = multiline_prefilter
2279 2281
2280 2282 def handle_normal(self,line_info):
2281 2283 """Handle normal input lines. Use as a template for handlers."""
2282 2284
2283 2285 # With autoindent on, we need some way to exit the input loop, and I
2284 2286 # don't want to force the user to have to backspace all the way to
2285 2287 # clear the line. The rule will be in this case, that either two
2286 2288 # lines of pure whitespace in a row, or a line of pure whitespace but
2287 2289 # of a size different to the indent level, will exit the input loop.
2288 2290 line = line_info.line
2289 2291 continue_prompt = line_info.continue_prompt
2290 2292
2291 2293 if (continue_prompt and self.autoindent and line.isspace() and
2292 2294 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2293 2295 (self.buffer[-1]).isspace() )):
2294 2296 line = ''
2295 2297
2296 2298 self.log(line,line,continue_prompt)
2297 2299 return line
2298 2300
2299 2301 def handle_alias(self,line_info):
2300 2302 """Handle alias input lines. """
2301 2303 tgt = self.alias_table[line_info.iFun]
2302 2304 # print "=>",tgt #dbg
2303 2305 if callable(tgt):
2304 2306 if '$' in line_info.line:
2305 2307 call_meth = '(_ip, _ip.itpl(%s))'
2306 2308 else:
2307 2309 call_meth = '(_ip,%s)'
2308 2310 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2309 2311 line_info.iFun,
2310 2312 make_quoted_expr(line_info.line))
2311 2313 else:
2312 2314 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2313 2315
2314 2316 # pre is needed, because it carries the leading whitespace. Otherwise
2315 2317 # aliases won't work in indented sections.
2316 2318 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2317 2319 make_quoted_expr( transformed ))
2318 2320
2319 2321 self.log(line_info.line,line_out,line_info.continue_prompt)
2320 2322 #print 'line out:',line_out # dbg
2321 2323 return line_out
2322 2324
2323 2325 def handle_shell_escape(self, line_info):
2324 2326 """Execute the line in a shell, empty return value"""
2325 2327 #print 'line in :', `line` # dbg
2326 2328 line = line_info.line
2327 2329 if line.lstrip().startswith('!!'):
2328 2330 # rewrite LineInfo's line, iFun and theRest to properly hold the
2329 2331 # call to %sx and the actual command to be executed, so
2330 2332 # handle_magic can work correctly. Note that this works even if
2331 2333 # the line is indented, so it handles multi_line_specials
2332 2334 # properly.
2333 2335 new_rest = line.lstrip()[2:]
2334 2336 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2335 2337 line_info.iFun = 'sx'
2336 2338 line_info.theRest = new_rest
2337 2339 return self.handle_magic(line_info)
2338 2340 else:
2339 2341 cmd = line.lstrip().lstrip('!')
2340 2342 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2341 2343 make_quoted_expr(cmd))
2342 2344 # update cache/log and return
2343 2345 self.log(line,line_out,line_info.continue_prompt)
2344 2346 return line_out
2345 2347
2346 2348 def handle_magic(self, line_info):
2347 2349 """Execute magic functions."""
2348 2350 iFun = line_info.iFun
2349 2351 theRest = line_info.theRest
2350 2352 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2351 2353 make_quoted_expr(iFun + " " + theRest))
2352 2354 self.log(line_info.line,cmd,line_info.continue_prompt)
2353 2355 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2354 2356 return cmd
2355 2357
2356 2358 def handle_auto(self, line_info):
2357 2359 """Hande lines which can be auto-executed, quoting if requested."""
2358 2360
2359 2361 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2360 2362 line = line_info.line
2361 2363 iFun = line_info.iFun
2362 2364 theRest = line_info.theRest
2363 2365 pre = line_info.pre
2364 2366 continue_prompt = line_info.continue_prompt
2365 2367 obj = line_info.ofind(self)['obj']
2366 2368
2367 2369 # This should only be active for single-line input!
2368 2370 if continue_prompt:
2369 2371 self.log(line,line,continue_prompt)
2370 2372 return line
2371 2373
2372 2374 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2373 2375 auto_rewrite = True
2374 2376
2375 2377 if pre == self.ESC_QUOTE:
2376 2378 # Auto-quote splitting on whitespace
2377 2379 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2378 2380 elif pre == self.ESC_QUOTE2:
2379 2381 # Auto-quote whole string
2380 2382 newcmd = '%s("%s")' % (iFun,theRest)
2381 2383 elif pre == self.ESC_PAREN:
2382 2384 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2383 2385 else:
2384 2386 # Auto-paren.
2385 2387 # We only apply it to argument-less calls if the autocall
2386 2388 # parameter is set to 2. We only need to check that autocall is <
2387 2389 # 2, since this function isn't called unless it's at least 1.
2388 2390 if not theRest and (self.rc.autocall < 2) and not force_auto:
2389 2391 newcmd = '%s %s' % (iFun,theRest)
2390 2392 auto_rewrite = False
2391 2393 else:
2392 2394 if not force_auto and theRest.startswith('['):
2393 2395 if hasattr(obj,'__getitem__'):
2394 2396 # Don't autocall in this case: item access for an object
2395 2397 # which is BOTH callable and implements __getitem__.
2396 2398 newcmd = '%s %s' % (iFun,theRest)
2397 2399 auto_rewrite = False
2398 2400 else:
2399 2401 # if the object doesn't support [] access, go ahead and
2400 2402 # autocall
2401 2403 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2402 2404 elif theRest.endswith(';'):
2403 2405 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2404 2406 else:
2405 2407 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2406 2408
2407 2409 if auto_rewrite:
2408 2410 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2409 2411
2410 2412 try:
2411 2413 # plain ascii works better w/ pyreadline, on some machines, so
2412 2414 # we use it and only print uncolored rewrite if we have unicode
2413 2415 rw = str(rw)
2414 2416 print >>Term.cout, rw
2415 2417 except UnicodeEncodeError:
2416 2418 print "-------------->" + newcmd
2417 2419
2418 2420 # log what is now valid Python, not the actual user input (without the
2419 2421 # final newline)
2420 2422 self.log(line,newcmd,continue_prompt)
2421 2423 return newcmd
2422 2424
2423 2425 def handle_help(self, line_info):
2424 2426 """Try to get some help for the object.
2425 2427
2426 2428 obj? or ?obj -> basic information.
2427 2429 obj?? or ??obj -> more details.
2428 2430 """
2429 2431
2430 2432 line = line_info.line
2431 2433 # We need to make sure that we don't process lines which would be
2432 2434 # otherwise valid python, such as "x=1 # what?"
2433 2435 try:
2434 2436 codeop.compile_command(line)
2435 2437 except SyntaxError:
2436 2438 # We should only handle as help stuff which is NOT valid syntax
2437 2439 if line[0]==self.ESC_HELP:
2438 2440 line = line[1:]
2439 2441 elif line[-1]==self.ESC_HELP:
2440 2442 line = line[:-1]
2441 2443 self.log(line,'#?'+line,line_info.continue_prompt)
2442 2444 if line:
2443 2445 #print 'line:<%r>' % line # dbg
2444 2446 self.magic_pinfo(line)
2445 2447 else:
2446 2448 page(self.usage,screen_lines=self.rc.screen_length)
2447 2449 return '' # Empty string is needed here!
2448 2450 except:
2449 2451 # Pass any other exceptions through to the normal handler
2450 2452 return self.handle_normal(line_info)
2451 2453 else:
2452 2454 # If the code compiles ok, we should handle it normally
2453 2455 return self.handle_normal(line_info)
2454 2456
2455 2457 def getapi(self):
2456 2458 """ Get an IPApi object for this shell instance
2457 2459
2458 2460 Getting an IPApi object is always preferable to accessing the shell
2459 2461 directly, but this holds true especially for extensions.
2460 2462
2461 2463 It should always be possible to implement an extension with IPApi
2462 2464 alone. If not, contact maintainer to request an addition.
2463 2465
2464 2466 """
2465 2467 return self.api
2466 2468
2467 2469 def handle_emacs(self, line_info):
2468 2470 """Handle input lines marked by python-mode."""
2469 2471
2470 2472 # Currently, nothing is done. Later more functionality can be added
2471 2473 # here if needed.
2472 2474
2473 2475 # The input cache shouldn't be updated
2474 2476 return line_info.line
2475 2477
2476 2478
2477 2479 def mktempfile(self,data=None):
2478 2480 """Make a new tempfile and return its filename.
2479 2481
2480 2482 This makes a call to tempfile.mktemp, but it registers the created
2481 2483 filename internally so ipython cleans it up at exit time.
2482 2484
2483 2485 Optional inputs:
2484 2486
2485 2487 - data(None): if data is given, it gets written out to the temp file
2486 2488 immediately, and the file is closed again."""
2487 2489
2488 2490 filename = tempfile.mktemp('.py','ipython_edit_')
2489 2491 self.tempfiles.append(filename)
2490 2492
2491 2493 if data:
2492 2494 tmp_file = open(filename,'w')
2493 2495 tmp_file.write(data)
2494 2496 tmp_file.close()
2495 2497 return filename
2496 2498
2497 2499 def write(self,data):
2498 2500 """Write a string to the default output"""
2499 2501 Term.cout.write(data)
2500 2502
2501 2503 def write_err(self,data):
2502 2504 """Write a string to the default error output"""
2503 2505 Term.cerr.write(data)
2504 2506
2505 2507 def exit(self):
2506 2508 """Handle interactive exit.
2507 2509
2508 2510 This method sets the exit_now attribute."""
2509 2511
2510 2512 if self.rc.confirm_exit:
2511 2513 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2512 2514 self.exit_now = True
2513 2515 else:
2514 2516 self.exit_now = True
2515 2517
2516 2518 def safe_execfile(self,fname,*where,**kw):
2517 2519 """A safe version of the builtin execfile().
2518 2520
2519 2521 This version will never throw an exception, and knows how to handle
2520 2522 ipython logs as well.
2521 2523
2522 2524 :Parameters:
2523 2525 fname : string
2524 2526 Name of the file to be executed.
2525 2527
2526 2528 where : tuple
2527 2529 One or two namespaces, passed to execfile() as (globals,locals).
2528 2530 If only one is given, it is passed as both.
2529 2531
2530 2532 :Keywords:
2531 2533 islog : boolean (False)
2532 2534
2533 2535 quiet : boolean (True)
2534 2536
2535 2537 exit_ignore : boolean (False)
2536 2538 """
2537 2539
2538 2540 def syspath_cleanup():
2539 2541 """Internal cleanup routine for sys.path."""
2540 2542 if add_dname:
2541 2543 try:
2542 2544 sys.path.remove(dname)
2543 2545 except ValueError:
2544 2546 # For some reason the user has already removed it, ignore.
2545 2547 pass
2546 2548
2547 2549 fname = os.path.expanduser(fname)
2548 2550
2549 2551 # Find things also in current directory. This is needed to mimic the
2550 2552 # behavior of running a script from the system command line, where
2551 2553 # Python inserts the script's directory into sys.path
2552 2554 dname = os.path.dirname(os.path.abspath(fname))
2553 2555 add_dname = False
2554 2556 if dname not in sys.path:
2555 2557 sys.path.insert(0,dname)
2556 2558 add_dname = True
2557 2559
2558 2560 try:
2559 2561 xfile = open(fname)
2560 2562 except:
2561 2563 print >> Term.cerr, \
2562 2564 'Could not open file <%s> for safe execution.' % fname
2563 2565 syspath_cleanup()
2564 2566 return None
2565 2567
2566 2568 kw.setdefault('islog',0)
2567 2569 kw.setdefault('quiet',1)
2568 2570 kw.setdefault('exit_ignore',0)
2569 2571
2570 2572 first = xfile.readline()
2571 2573 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2572 2574 xfile.close()
2573 2575 # line by line execution
2574 2576 if first.startswith(loghead) or kw['islog']:
2575 2577 print 'Loading log file <%s> one line at a time...' % fname
2576 2578 if kw['quiet']:
2577 2579 stdout_save = sys.stdout
2578 2580 sys.stdout = StringIO.StringIO()
2579 2581 try:
2580 2582 globs,locs = where[0:2]
2581 2583 except:
2582 2584 try:
2583 2585 globs = locs = where[0]
2584 2586 except:
2585 2587 globs = locs = globals()
2586 2588 badblocks = []
2587 2589
2588 2590 # we also need to identify indented blocks of code when replaying
2589 2591 # logs and put them together before passing them to an exec
2590 2592 # statement. This takes a bit of regexp and look-ahead work in the
2591 2593 # file. It's easiest if we swallow the whole thing in memory
2592 2594 # first, and manually walk through the lines list moving the
2593 2595 # counter ourselves.
2594 2596 indent_re = re.compile('\s+\S')
2595 2597 xfile = open(fname)
2596 2598 filelines = xfile.readlines()
2597 2599 xfile.close()
2598 2600 nlines = len(filelines)
2599 2601 lnum = 0
2600 2602 while lnum < nlines:
2601 2603 line = filelines[lnum]
2602 2604 lnum += 1
2603 2605 # don't re-insert logger status info into cache
2604 2606 if line.startswith('#log#'):
2605 2607 continue
2606 2608 else:
2607 2609 # build a block of code (maybe a single line) for execution
2608 2610 block = line
2609 2611 try:
2610 2612 next = filelines[lnum] # lnum has already incremented
2611 2613 except:
2612 2614 next = None
2613 2615 while next and indent_re.match(next):
2614 2616 block += next
2615 2617 lnum += 1
2616 2618 try:
2617 2619 next = filelines[lnum]
2618 2620 except:
2619 2621 next = None
2620 2622 # now execute the block of one or more lines
2621 2623 try:
2622 2624 exec block in globs,locs
2623 2625 except SystemExit:
2624 2626 pass
2625 2627 except:
2626 2628 badblocks.append(block.rstrip())
2627 2629 if kw['quiet']: # restore stdout
2628 2630 sys.stdout.close()
2629 2631 sys.stdout = stdout_save
2630 2632 print 'Finished replaying log file <%s>' % fname
2631 2633 if badblocks:
2632 2634 print >> sys.stderr, ('\nThe following lines/blocks in file '
2633 2635 '<%s> reported errors:' % fname)
2634 2636
2635 2637 for badline in badblocks:
2636 2638 print >> sys.stderr, badline
2637 2639 else: # regular file execution
2638 2640 try:
2639 2641 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2640 2642 # Work around a bug in Python for Windows. The bug was
2641 2643 # fixed in in Python 2.5 r54159 and 54158, but that's still
2642 2644 # SVN Python as of March/07. For details, see:
2643 2645 # http://projects.scipy.org/ipython/ipython/ticket/123
2644 2646 try:
2645 2647 globs,locs = where[0:2]
2646 2648 except:
2647 2649 try:
2648 2650 globs = locs = where[0]
2649 2651 except:
2650 2652 globs = locs = globals()
2651 2653 exec file(fname) in globs,locs
2652 2654 else:
2653 2655 execfile(fname,*where)
2654 2656 except SyntaxError:
2655 2657 self.showsyntaxerror()
2656 2658 warn('Failure executing file: <%s>' % fname)
2657 2659 except SystemExit,status:
2658 2660 # Code that correctly sets the exit status flag to success (0)
2659 2661 # shouldn't be bothered with a traceback. Note that a plain
2660 2662 # sys.exit() does NOT set the message to 0 (it's empty) so that
2661 2663 # will still get a traceback. Note that the structure of the
2662 2664 # SystemExit exception changed between Python 2.4 and 2.5, so
2663 2665 # the checks must be done in a version-dependent way.
2664 2666 show = False
2665 2667
2666 2668 if sys.version_info[:2] > (2,5):
2667 2669 if status.message!=0 and not kw['exit_ignore']:
2668 2670 show = True
2669 2671 else:
2670 2672 if status.code and not kw['exit_ignore']:
2671 2673 show = True
2672 2674 if show:
2673 2675 self.showtraceback()
2674 2676 warn('Failure executing file: <%s>' % fname)
2675 2677 except:
2676 2678 self.showtraceback()
2677 2679 warn('Failure executing file: <%s>' % fname)
2678 2680
2679 2681 syspath_cleanup()
2680 2682
2681 2683 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now