dirsize.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2011, Intel Corporation.
  4. # All rights reserved.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. #
  20. #
  21. # Display details of the root filesystem size, broken up by directory.
  22. # Allows for limiting by size to focus on the larger files.
  23. #
  24. # Author: Darren Hart <dvhart@linux.intel.com>
  25. #
  26. import os
  27. import sys
  28. import stat
  29. class Record:
  30. def create(path):
  31. r = Record(path)
  32. s = os.lstat(path)
  33. if stat.S_ISDIR(s.st_mode):
  34. for p in os.listdir(path):
  35. pathname = path + "/" + p
  36. ss = os.lstat(pathname)
  37. if not stat.S_ISLNK(ss.st_mode):
  38. r.records.append(Record.create(pathname))
  39. r.size += r.records[-1].size
  40. r.records.sort(reverse=True)
  41. else:
  42. r.size = os.lstat(path).st_size
  43. return r
  44. create = staticmethod(create)
  45. def __init__(self, path):
  46. self.path = path
  47. self.size = 0
  48. self.records = []
  49. def __cmp__(this, that):
  50. if that is None:
  51. return 1
  52. if not isinstance(that, Record):
  53. raise TypeError
  54. if len(this.records) > 0 and len(that.records) == 0:
  55. return -1
  56. if len(this.records) == 0 and len(that.records) > 0:
  57. return 1
  58. if this.size < that.size:
  59. return -1
  60. if this.size > that.size:
  61. return 1
  62. return 0
  63. def show(self, minsize):
  64. total = 0
  65. if self.size <= minsize:
  66. return 0
  67. print "%10d %s" % (self.size, self.path)
  68. for r in self.records:
  69. total += r.show(minsize)
  70. if len(self.records) == 0:
  71. total = self.size
  72. return total
  73. def main():
  74. minsize = 0
  75. if len(sys.argv) == 2:
  76. minsize = int(sys.argv[1])
  77. rootfs = Record.create(".")
  78. total = rootfs.show(minsize)
  79. print "Displayed %d/%d bytes (%.2f%%)" % \
  80. (total, rootfs.size, 100 * float(total) / rootfs.size)
  81. if __name__ == "__main__":
  82. main()