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