You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

linecache.py 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """Cache lines from files.
  2. This is intended to read lines from modules imported -- hence if a filename
  3. is not found, it will look down the module search path for a file by
  4. that name.
  5. """
  6. import sys
  7. import os
  8. from stat import *
  9. __all__ = ["getline","clearcache","checkcache"]
  10. def getline(filename, lineno):
  11. lines = getlines(filename)
  12. if 1 <= lineno <= len(lines):
  13. return lines[lineno-1]
  14. else:
  15. return ''
  16. # The cache
  17. cache = {} # The cache
  18. def clearcache():
  19. """Clear the cache entirely."""
  20. global cache
  21. cache = {}
  22. def getlines(filename):
  23. """Get the lines for a file from the cache.
  24. Update the cache if it doesn't contain an entry for this file already."""
  25. if cache.has_key(filename):
  26. return cache[filename][2]
  27. else:
  28. return updatecache(filename)
  29. def checkcache():
  30. """Discard cache entries that are out of date.
  31. (This is not checked upon each call!)"""
  32. for filename in cache.keys():
  33. size, mtime, lines, fullname = cache[filename]
  34. try:
  35. stat = os.stat(fullname)
  36. except os.error:
  37. del cache[filename]
  38. continue
  39. if size != stat[ST_SIZE] or mtime != stat[ST_MTIME]:
  40. del cache[filename]
  41. def updatecache(filename):
  42. """Update a cache entry and return its list of lines.
  43. If something's wrong, print a message, discard the cache entry,
  44. and return an empty list."""
  45. if cache.has_key(filename):
  46. del cache[filename]
  47. if not filename or filename[0] + filename[-1] == '<>':
  48. return []
  49. fullname = filename
  50. try:
  51. stat = os.stat(fullname)
  52. except os.error, msg:
  53. # Try looking through the module search path
  54. basename = os.path.split(filename)[1]
  55. for dirname in sys.path:
  56. fullname = os.path.join(dirname, basename)
  57. try:
  58. stat = os.stat(fullname)
  59. break
  60. except os.error:
  61. pass
  62. else:
  63. # No luck
  64. ## print '*** Cannot stat', filename, ':', msg
  65. return []
  66. try:
  67. fp = open(fullname, 'r')
  68. lines = fp.readlines()
  69. fp.close()
  70. except IOError, msg:
  71. ## print '*** Cannot open', fullname, ':', msg
  72. return []
  73. size, mtime = stat[ST_SIZE], stat[ST_MTIME]
  74. cache[filename] = size, mtime, lines, fullname
  75. return lines