remove_stale_pyc_files.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env python
  2. # Copyright 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. import os
  6. import sys
  7. def RemoveAllStalePycFiles(base_dir):
  8. """Scan directories for old .pyc files without a .py file and delete them."""
  9. for dirname, _, filenames in os.walk(base_dir, topdown=False):
  10. if '.svn' in dirname or '.git' in dirname:
  11. continue
  12. for filename in filenames:
  13. root, ext = os.path.splitext(filename)
  14. if ext != '.pyc':
  15. continue
  16. pyc_path = os.path.join(dirname, filename)
  17. py_path = os.path.join(dirname, root + '.py')
  18. try:
  19. if not os.path.exists(py_path):
  20. os.remove(pyc_path)
  21. except OSError:
  22. # Wrap OS calls in try/except in case another process touched this file.
  23. pass
  24. try:
  25. os.removedirs(dirname)
  26. except OSError:
  27. # Wrap OS calls in try/except in case another process touched this dir.
  28. pass
  29. if __name__ == '__main__':
  30. for path in sys.argv[1:]:
  31. RemoveAllStalePycFiles(path)