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
10 def getline(filename
, lineno
):
11 lines
= getlines(filename
)
12 if 1 <= lineno
<= len(lines
):
13 return lines
[lineno
-1]
20 cache
= {} # The cache
23 # Clear the cache entirely
30 # Get the lines for a file from the cache.
31 # Update the cache if it doesn't contain an entry for this file already.
33 def getlines(filename
):
34 if cache
.has_key(filename
):
35 return cache
[filename
][2]
37 return updatecache(filename
)
40 # Discard cache entries that are out of date.
41 # (This is not checked upon each call!)
44 for filename
in cache
.keys():
45 size
, mtime
, lines
, fullname
= cache
[filename
]
47 stat
= os
.stat(fullname
)
51 if size
<> stat
[ST_SIZE
] or mtime
<> stat
[ST_MTIME
]:
55 # Update a cache entry and return its list of lines.
56 # If something's wrong, print a message, discard the cache entry,
57 # and return an empty list.
59 def updatecache(filename
):
60 if cache
.has_key(filename
):
62 if not filename
or filename
[0] + filename
[-1] == '<>':
66 stat
= os
.stat(fullname
)
68 # Try looking through the module search path
69 basename
= os
.path
.split(filename
)[1]
70 for dirname
in sys
.path
:
71 fullname
= os
.path
.join(dirname
, basename
)
73 stat
= os
.stat(fullname
)
79 print '*** Cannot stat', filename
, ':', msg
82 fp
= open(fullname
, 'r')
83 lines
= fp
.readlines()
86 print '*** Cannot open', fullname
, ':', msg
88 size
, mtime
= stat
[ST_SIZE
], stat
[ST_MTIME
]
89 cache
[filename
] = size
, mtime
, lines
, fullname