cpython/Tools/scripts/checkpyc.py

70 lines
2.2 KiB
Python
Raw Normal View History

#! /usr/bin/env python3
1991-12-18 13:38:27 +00:00
# Check that all ".pyc" files exist and are up-to-date
1992-03-30 11:15:26 +00:00
# Uses module 'os'
1991-12-18 13:38:27 +00:00
import sys
1992-03-30 11:15:26 +00:00
import os
1991-12-18 13:38:27 +00:00
from stat import ST_MTIME
import importlib.util
1991-12-18 13:38:27 +00:00
# PEP 3147 compatibility (PYC Repository Directories)
cache_from_source = (importlib.util.cache_from_source if sys.implementation.cache_tag
else lambda path: path + 'c')
1991-12-18 13:38:27 +00:00
def main():
if len(sys.argv) > 1:
verbose = (sys.argv[1] == '-v')
silent = (sys.argv[1] == '-s')
else:
verbose = silent = False
MAGIC = importlib.util.MAGIC_NUMBER
2001-01-17 08:48:39 +00:00
if not silent:
print('Using MAGIC word', repr(MAGIC))
2001-01-17 08:48:39 +00:00
for dirname in sys.path:
try:
names = os.listdir(dirname)
except OSError:
print('Cannot list directory', repr(dirname))
2001-01-17 08:48:39 +00:00
continue
if not silent:
print('Checking ', repr(dirname), '...')
for name in sorted(names):
if name.endswith('.py'):
2001-01-17 08:48:39 +00:00
name = os.path.join(dirname, name)
try:
st = os.stat(name)
except OSError:
print('Cannot stat', repr(name))
2001-01-17 08:48:39 +00:00
continue
if verbose:
print('Check', repr(name), '...')
name_c = cache_from_source(name)
2001-01-17 08:48:39 +00:00
try:
with open(name_c, 'rb') as f:
magic_str = f.read(4)
mtime_str = f.read(4)
2001-01-17 08:48:39 +00:00
except IOError:
print('Cannot open', repr(name_c))
2001-01-17 08:48:39 +00:00
continue
2008-05-16 15:23:30 +00:00
if magic_str != MAGIC:
print('Bad MAGIC word in ".pyc" file', end=' ')
print(repr(name_c))
2001-01-17 08:48:39 +00:00
continue
mtime = get_long(mtime_str)
if mtime in {0, -1}:
print('Bad ".pyc" file', repr(name_c))
2008-05-16 15:23:30 +00:00
elif mtime != st[ST_MTIME]:
print('Out-of-date ".pyc" file', end=' ')
print(repr(name_c))
1991-12-18 13:38:27 +00:00
1991-12-18 13:38:27 +00:00
def get_long(s):
2008-05-16 15:23:30 +00:00
if len(s) != 4:
2001-01-17 08:48:39 +00:00
return -1
return s[0] + (s[1] << 8) + (s[2] << 16) + (s[3] << 24)
1991-12-18 13:38:27 +00:00
if __name__ == '__main__':
main()