Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 1 | # Module 'dircache' |
| 2 | # |
| 3 | # Return a sorted list of the files in a POSIX directory, using a cache |
| 4 | # to avoid reading the directory more often than necessary. |
| 5 | # Also contains a subroutine to append slashes to directories. |
| 6 | |
| 7 | import posix |
| 8 | import path |
| 9 | |
| 10 | cache = {} |
| 11 | |
| 12 | def listdir(path): # List directory contents, using cache |
| 13 | try: |
| 14 | cached_mtime, list = cache[path] |
| 15 | del cache[path] |
| 16 | except RuntimeError: |
| 17 | cached_mtime, list = -1, [] |
| 18 | try: |
| 19 | mtime = posix.stat(path)[8] |
| 20 | except posix.error: |
| 21 | return [] |
| 22 | if mtime <> cached_mtime: |
| 23 | try: |
| 24 | list = posix.listdir(path) |
| 25 | except posix.error: |
| 26 | return [] |
| 27 | list.sort() |
| 28 | cache[path] = mtime, list |
| 29 | return list |
| 30 | |
| 31 | opendir = listdir # XXX backward compatibility |
| 32 | |
| 33 | def annotate(head, list): # Add '/' suffixes to directories |
| 34 | for i in range(len(list)): |
Guido van Rossum | 784ca6c | 1991-08-16 13:28:23 +0000 | [diff] [blame] | 35 | if path.isdir(path.join(head, list[i])): |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 36 | list[i] = list[i] + '/' |