Last active
August 29, 2017 15:22
-
-
Save dhilst/97ebca7e784e8a92c0fbdeb3af0e3a5a to your computer and use it in GitHub Desktop.
Print the top 20 folder that are using more space.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Copyright 2017 Daniel Hilst Selli | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| import subprocess | |
| def yieldindex(lines): | |
| for line in lines: | |
| siz, path = line.split(maxsplit=1) | |
| yield siz, path.split('/')[1:] | |
| def createindex(foldr): | |
| g = (line.rstrip() for line in subprocess.Popen(['find', foldr, '-xdev', '-printf', '%k %p\\n'], | |
| stdout=subprocess.PIPE, universal_newlines=True).stdout.readlines()) | |
| yield from yieldindex(g) | |
| def readindex(index): | |
| with open(index) as f: | |
| yield from yieldindex(f.readlines()) | |
| def genindex(indexgen): | |
| index = {} | |
| for siz, path in indexgen: | |
| for folder in ('/'.join(path[:n]) for n in range(1, len(path)+1)): | |
| index[folder] = int(siz) if not folder in index else index[folder] + int(siz) | |
| return index | |
| def printindex(idx, max_=20): | |
| for e,(k,v) in enumerate(sorted(idx.items(), key=lambda x: x[1], reverse=True)): | |
| print(v, k) | |
| if e > max_: | |
| break | |
| if __name__ == '__main__': | |
| import sys | |
| try: | |
| printindex(genindex(readindex(sys.argv[1]))) | |
| except IsADirectoryError: | |
| printindex(genindex(createindex(sys.argv[1]))) | |
| except IndexError: | |
| print('Usage: diskindex.py index.txt\n' | |
| 'Index can be constructed with `find <MOUNT_POINT> -xdev -print "%k %p\\n" > diskindex.txt`.\n' | |
| 'or\n' | |
| 'diskindex.py <DIRECTORY>\n' | |
| 'In this case the index is created automatically\n') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment