Last set of CW Pro 5 projects (probably)
[python/dscho.git] / Lib / linecache.py
blobbca40b291cda8d19623d69c78efb6d3ea7ef8aee
1 """Cache lines from files.
3 This is intended to read lines from modules imported -- hence if a filename
4 is not found, it will look down the module search path for a file by
5 that name.
6 """
8 import sys
9 import os
10 from stat import *
12 def getline(filename, lineno):
13 lines = getlines(filename)
14 if 1 <= lineno <= len(lines):
15 return lines[lineno-1]
16 else:
17 return ''
20 # The cache
22 cache = {} # The cache
25 def clearcache():
26 """Clear the cache entirely."""
28 global cache
29 cache = {}
32 def getlines(filename):
33 """Get the lines for a file from the cache.
34 Update the cache if it doesn't contain an entry for this file already."""
36 if cache.has_key(filename):
37 return cache[filename][2]
38 else:
39 return updatecache(filename)
42 def checkcache():
43 """Discard cache entries that are out of date.
44 (This is not checked upon each call!)"""
46 for filename in cache.keys():
47 size, mtime, lines, fullname = cache[filename]
48 try:
49 stat = os.stat(fullname)
50 except os.error:
51 del cache[filename]
52 continue
53 if size <> stat[ST_SIZE] or mtime <> stat[ST_MTIME]:
54 del cache[filename]
57 def updatecache(filename):
58 """Update a cache entry and return its list of lines.
59 If something's wrong, print a message, discard the cache entry,
60 and return an empty list."""
62 if cache.has_key(filename):
63 del cache[filename]
64 if not filename or filename[0] + filename[-1] == '<>':
65 return []
66 fullname = filename
67 try:
68 stat = os.stat(fullname)
69 except os.error, msg:
70 # Try looking through the module search path
71 basename = os.path.split(filename)[1]
72 for dirname in sys.path:
73 fullname = os.path.join(dirname, basename)
74 try:
75 stat = os.stat(fullname)
76 break
77 except os.error:
78 pass
79 else:
80 # No luck
81 ## print '*** Cannot stat', filename, ':', msg
82 return []
83 try:
84 fp = open(fullname, 'r')
85 lines = fp.readlines()
86 fp.close()
87 except IOError, msg:
88 ## print '*** Cannot open', fullname, ':', msg
89 return []
90 size, mtime = stat[ST_SIZE], stat[ST_MTIME]
91 cache[filename] = size, mtime, lines, fullname
92 return lines