1 | n/a | #! /usr/bin/env python3 |
---|
2 | n/a | # Check that all ".pyc" files exist and are up-to-date |
---|
3 | n/a | # Uses module 'os' |
---|
4 | n/a | |
---|
5 | n/a | import sys |
---|
6 | n/a | import os |
---|
7 | n/a | from stat import ST_MTIME |
---|
8 | n/a | import importlib.util |
---|
9 | n/a | |
---|
10 | n/a | # PEP 3147 compatibility (PYC Repository Directories) |
---|
11 | n/a | cache_from_source = (importlib.util.cache_from_source if sys.implementation.cache_tag |
---|
12 | n/a | else lambda path: path + 'c') |
---|
13 | n/a | |
---|
14 | n/a | |
---|
15 | n/a | def main(): |
---|
16 | n/a | if len(sys.argv) > 1: |
---|
17 | n/a | verbose = (sys.argv[1] == '-v') |
---|
18 | n/a | silent = (sys.argv[1] == '-s') |
---|
19 | n/a | else: |
---|
20 | n/a | verbose = silent = False |
---|
21 | n/a | MAGIC = importlib.util.MAGIC_NUMBER |
---|
22 | n/a | if not silent: |
---|
23 | n/a | print('Using MAGIC word', repr(MAGIC)) |
---|
24 | n/a | for dirname in sys.path: |
---|
25 | n/a | try: |
---|
26 | n/a | names = os.listdir(dirname) |
---|
27 | n/a | except OSError: |
---|
28 | n/a | print('Cannot list directory', repr(dirname)) |
---|
29 | n/a | continue |
---|
30 | n/a | if not silent: |
---|
31 | n/a | print('Checking ', repr(dirname), '...') |
---|
32 | n/a | for name in sorted(names): |
---|
33 | n/a | if name.endswith('.py'): |
---|
34 | n/a | name = os.path.join(dirname, name) |
---|
35 | n/a | try: |
---|
36 | n/a | st = os.stat(name) |
---|
37 | n/a | except OSError: |
---|
38 | n/a | print('Cannot stat', repr(name)) |
---|
39 | n/a | continue |
---|
40 | n/a | if verbose: |
---|
41 | n/a | print('Check', repr(name), '...') |
---|
42 | n/a | name_c = cache_from_source(name) |
---|
43 | n/a | try: |
---|
44 | n/a | with open(name_c, 'rb') as f: |
---|
45 | n/a | magic_str = f.read(4) |
---|
46 | n/a | mtime_str = f.read(4) |
---|
47 | n/a | except IOError: |
---|
48 | n/a | print('Cannot open', repr(name_c)) |
---|
49 | n/a | continue |
---|
50 | n/a | if magic_str != MAGIC: |
---|
51 | n/a | print('Bad MAGIC word in ".pyc" file', end=' ') |
---|
52 | n/a | print(repr(name_c)) |
---|
53 | n/a | continue |
---|
54 | n/a | mtime = get_long(mtime_str) |
---|
55 | n/a | if mtime in {0, -1}: |
---|
56 | n/a | print('Bad ".pyc" file', repr(name_c)) |
---|
57 | n/a | elif mtime != st[ST_MTIME]: |
---|
58 | n/a | print('Out-of-date ".pyc" file', end=' ') |
---|
59 | n/a | print(repr(name_c)) |
---|
60 | n/a | |
---|
61 | n/a | |
---|
62 | n/a | def get_long(s): |
---|
63 | n/a | if len(s) != 4: |
---|
64 | n/a | return -1 |
---|
65 | n/a | return s[0] + (s[1] << 8) + (s[2] << 16) + (s[3] << 24) |
---|
66 | n/a | |
---|
67 | n/a | |
---|
68 | n/a | if __name__ == '__main__': |
---|
69 | n/a | main() |
---|