Exceptions raised during renaming in rotating file handlers are now passed to handleE...
[python.git] / Lib / linecache.py
blob2ccc6c67cb1248f0f2a686072153e3cd19539e8e
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
11 __all__ = ["getline", "clearcache", "checkcache"]
13 def getline(filename, lineno):
14 lines = getlines(filename)
15 if 1 <= lineno <= len(lines):
16 return lines[lineno-1]
17 else:
18 return ''
21 # The cache
23 cache = {} # The cache
26 def clearcache():
27 """Clear the cache entirely."""
29 global cache
30 cache = {}
33 def getlines(filename):
34 """Get the lines for a file from the cache.
35 Update the cache if it doesn't contain an entry for this file already."""
37 if filename in cache:
38 return cache[filename][2]
39 else:
40 return updatecache(filename)
43 def checkcache(filename=None):
44 """Discard cache entries that are out of date.
45 (This is not checked upon each call!)"""
47 if filename is None:
48 filenames = cache.keys()
49 else:
50 if filename in cache:
51 filenames = [filename]
52 else:
53 return
55 for filename in filenames:
56 size, mtime, lines, fullname = cache[filename]
57 try:
58 stat = os.stat(fullname)
59 except os.error:
60 del cache[filename]
61 continue
62 if size != stat.st_size or mtime != stat.st_mtime:
63 del cache[filename]
66 def updatecache(filename):
67 """Update a cache entry and return its list of lines.
68 If something's wrong, print a message, discard the cache entry,
69 and return an empty list."""
71 if filename in cache:
72 del cache[filename]
73 if not filename or filename[0] + filename[-1] == '<>':
74 return []
75 fullname = filename
76 try:
77 stat = os.stat(fullname)
78 except os.error, msg:
79 # Try looking through the module search path.
80 basename = os.path.split(filename)[1]
81 for dirname in sys.path:
82 # When using imputil, sys.path may contain things other than
83 # strings; ignore them when it happens.
84 try:
85 fullname = os.path.join(dirname, basename)
86 except (TypeError, AttributeError):
87 # Not sufficiently string-like to do anything useful with.
88 pass
89 else:
90 try:
91 stat = os.stat(fullname)
92 break
93 except os.error:
94 pass
95 else:
96 # No luck
97 ## print '*** Cannot stat', filename, ':', msg
98 return []
99 try:
100 fp = open(fullname, 'rU')
101 lines = fp.readlines()
102 fp.close()
103 except IOError, msg:
104 ## print '*** Cannot open', fullname, ':', msg
105 return []
106 size, mtime = stat.st_size, stat.st_mtime
107 cache[filename] = size, mtime, lines, fullname
108 return lines