dutree.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #! /usr/bin/env python3
  2. # Format du output in a tree shape
  3. import os, sys, errno
  4. def main():
  5. p = os.popen('du ' + ' '.join(sys.argv[1:]), 'r')
  6. total, d = None, {}
  7. for line in p.readlines():
  8. i = 0
  9. while line[i] in '0123456789': i = i+1
  10. size = eval(line[:i])
  11. while line[i] in ' \t': i = i+1
  12. filename = line[i:-1]
  13. comps = filename.split('/')
  14. if comps[0] == '': comps[0] = '/'
  15. if comps[len(comps)-1] == '': del comps[len(comps)-1]
  16. total, d = store(size, comps, total, d)
  17. try:
  18. display(total, d)
  19. except IOError as e:
  20. if e.errno != errno.EPIPE:
  21. raise
  22. def store(size, comps, total, d):
  23. if comps == []:
  24. return size, d
  25. if comps[0] not in d:
  26. d[comps[0]] = None, {}
  27. t1, d1 = d[comps[0]]
  28. d[comps[0]] = store(size, comps[1:], t1, d1)
  29. return total, d
  30. def display(total, d):
  31. show(total, d, '')
  32. def show(total, d, prefix):
  33. if not d: return
  34. list = []
  35. sum = 0
  36. for key in d.keys():
  37. tsub, dsub = d[key]
  38. list.append((tsub, key))
  39. if tsub is not None: sum = sum + tsub
  40. ## if sum < total:
  41. ## list.append((total - sum, os.curdir))
  42. list.sort()
  43. list.reverse()
  44. width = len(repr(list[0][0]))
  45. for tsub, key in list:
  46. if tsub is None:
  47. psub = prefix
  48. else:
  49. print(prefix + repr(tsub).rjust(width) + ' ' + key)
  50. psub = prefix + ' '*(width-1) + '|' + ' '*(len(key)+1)
  51. if key in d:
  52. show(tsub, d[key][1], psub)
  53. if __name__ == '__main__':
  54. main()