dirsize.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python3
  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 __lt__(this, that):
  50. if that is None:
  51. return False
  52. if not isinstance(that, Record):
  53. raise TypeError
  54. if len(this.records) > 0 and len(that.records) == 0:
  55. return False
  56. if this.size > that.size:
  57. return False
  58. return True
  59. def show(self, minsize):
  60. total = 0
  61. if self.size <= minsize:
  62. return 0
  63. print("%10d %s" % (self.size, self.path))
  64. for r in self.records:
  65. total += r.show(minsize)
  66. if len(self.records) == 0:
  67. total = self.size
  68. return total
  69. def main():
  70. minsize = 0
  71. if len(sys.argv) == 2:
  72. minsize = int(sys.argv[1])
  73. rootfs = Record.create(".")
  74. total = rootfs.show(minsize)
  75. print("Displayed %d/%d bytes (%.2f%%)" % \
  76. (total, rootfs.size, 100 * float(total) / rootfs.size))
  77. if __name__ == "__main__":
  78. main()