ulinecache.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Wrapper around linecache which decodes files to unicode according to PEP 263.
  2. This is only needed for Python 2 - linecache in Python 3 does the same thing
  3. itself.
  4. """
  5. import functools
  6. import linecache
  7. import sys
  8. from IPython.utils import py3compat
  9. from IPython.utils import openpy
  10. if py3compat.PY3:
  11. getline = linecache.getline
  12. # getlines has to be looked up at runtime, because doctests monkeypatch it.
  13. @functools.wraps(linecache.getlines)
  14. def getlines(filename, module_globals=None):
  15. return linecache.getlines(filename, module_globals=module_globals)
  16. else:
  17. def getlines(filename, module_globals=None):
  18. """Get the lines (as unicode) for a file from the cache.
  19. Update the cache if it doesn't contain an entry for this file already."""
  20. filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding())
  21. lines = linecache.getlines(filename, module_globals=module_globals)
  22. # The bits we cache ourselves can be unicode.
  23. if (not lines) or isinstance(lines[0], py3compat.unicode_type):
  24. return lines
  25. readline = openpy._list_readline(lines)
  26. try:
  27. encoding, _ = openpy.detect_encoding(readline)
  28. except SyntaxError:
  29. encoding = 'ascii'
  30. return [l.decode(encoding, 'replace') for l in lines]
  31. # This is a straight copy of linecache.getline
  32. def getline(filename, lineno, module_globals=None):
  33. lines = getlines(filename, module_globals)
  34. if 1 <= lineno <= len(lines):
  35. return lines[lineno-1]
  36. else:
  37. return ''