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
6import os
7import sys
8
9
10def RemoveAllStalePycFiles(base_dir):
11  """Scan directories for old .pyc files without a .py file and delete them."""
12  for dirname, _, filenames in os.walk(base_dir):
13    if '.svn' in dirname or '.git' in dirname:
14      continue
15    for filename in filenames:
16      root, ext = os.path.splitext(filename)
17      if ext != '.pyc':
18        continue
19
20      pyc_path = os.path.join(dirname, filename)
21      py_path = os.path.join(dirname, root + '.py')
22
23      try:
24        if not os.path.exists(py_path):
25          os.remove(pyc_path)
26      except OSError:
27        # Wrap OS calls in try/except in case another process touched this file.
28        pass
29
30    try:
31      os.removedirs(dirname)
32    except OSError:
33      # Wrap OS calls in try/except in case another process touched this dir.
34      pass
35
36
37if __name__ == '__main__':
38  for path in sys.argv[1:]:
39    RemoveAllStalePycFiles(path)
40