dirsize.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2011, Intel Corporation.
  4. #
  5. # SPDX-License-Identifier: GPL-2.0-or-later
  6. #
  7. # Display details of the root filesystem size, broken up by directory.
  8. # Allows for limiting by size to focus on the larger files.
  9. #
  10. # Author: Darren Hart <dvhart@linux.intel.com>
  11. #
  12. import os
  13. import sys
  14. import stat
  15. class Record:
  16. def create(path):
  17. r = Record(path)
  18. s = os.lstat(path)
  19. if stat.S_ISDIR(s.st_mode):
  20. for p in os.listdir(path):
  21. pathname = path + "/" + p
  22. ss = os.lstat(pathname)
  23. if not stat.S_ISLNK(ss.st_mode):
  24. r.records.append(Record.create(pathname))
  25. r.size += r.records[-1].size
  26. r.records.sort(reverse=True)
  27. else:
  28. r.size = os.lstat(path).st_size
  29. return r
  30. create = staticmethod(create)
  31. def __init__(self, path):
  32. self.path = path
  33. self.size = 0
  34. self.records = []
  35. def __lt__(this, that):
  36. if that is None:
  37. return False
  38. if not isinstance(that, Record):
  39. raise TypeError
  40. if len(this.records) > 0 and len(that.records) == 0:
  41. return False
  42. if this.size > that.size:
  43. return False
  44. return True
  45. def show(self, minsize):
  46. total = 0
  47. if self.size <= minsize:
  48. return 0
  49. print("%10d %s" % (self.size, self.path))
  50. for r in self.records:
  51. total += r.show(minsize)
  52. if len(self.records) == 0:
  53. total = self.size
  54. return total
  55. def main():
  56. minsize = 0
  57. if len(sys.argv) == 2:
  58. minsize = int(sys.argv[1])
  59. rootfs = Record.create(".")
  60. total = rootfs.show(minsize)
  61. print("Displayed %d/%d bytes (%.2f%%)" % \
  62. (total, rootfs.size, 100 * float(total) / rootfs.size))
  63. if __name__ == "__main__":
  64. main()