really the last log entry for 1.1
[python/dscho.git] / Lib / linecache.py
blobf5726e9eb8dfff2cea55dc420ad6f752a4ee45e4
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.
6 import sys
7 import os
8 from stat import *
10 def getline(filename, lineno):
11 lines = getlines(filename)
12 if 1 <= lineno <= len(lines):
13 return lines[lineno-1]
14 else:
15 return ''
18 # The cache
20 cache = {} # The cache
23 # Clear the cache entirely
25 def clearcache():
26 global cache
27 cache = {}
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]
36 else:
37 return updatecache(filename)
40 # Discard cache entries that are out of date.
41 # (This is not checked upon each call!)
43 def checkcache():
44 for filename in cache.keys():
45 size, mtime, lines, fullname = cache[filename]
46 try:
47 stat = os.stat(fullname)
48 except os.error:
49 del cache[filename]
50 continue
51 if size <> stat[ST_SIZE] or mtime <> stat[ST_MTIME]:
52 del cache[filename]
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):
61 del cache[filename]
62 if not filename or filename[0] + filename[-1] == '<>':
63 return []
64 fullname = filename
65 try:
66 stat = os.stat(fullname)
67 except os.error, msg:
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)
72 try:
73 stat = os.stat(fullname)
74 break
75 except os.error:
76 pass
77 else:
78 # No luck
79 print '*** Cannot stat', filename, ':', msg
80 return []
81 try:
82 fp = open(fullname, 'r')
83 lines = fp.readlines()
84 fp.close()
85 except IOError, msg:
86 print '*** Cannot open', fullname, ':', msg
87 return []
88 size, mtime = stat[ST_SIZE], stat[ST_MTIME]
89 cache[filename] = size, mtime, lines, fullname
90 return lines