Created
December 28, 2017 07:01
-
-
Save yattom/4db42a1560c653fcbd9f714db90c1df2 to your computer and use it in GitHub Desktop.
du.py
This file contains 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
import sys | |
from du import main | |
if __name__=='__main__': | |
if len(sys.argv) > 1: | |
main.main(sys.argv[1]) | |
else: | |
main.main() |
This file contains 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
import os | |
import os.path | |
import sys | |
def humanize(num): | |
""" | |
>>> humanize(500) | |
'500' | |
>>> humanize(1000) | |
'1.0k' | |
>>> humanize(21000) | |
'21k' | |
>>> humanize(321000) | |
'321k' | |
>>> humanize(4321000) | |
'4.3m' | |
>>> humanize(54321000) | |
'54m' | |
>>> humanize(654321000) | |
'654m' | |
>>> humanize(7654321000) | |
'7.6g' | |
""" | |
if num < 1000: | |
return str(num) | |
order = " kmgt"[(len(str(num)) - 1) // 3] | |
head = str(num)[0:len(str(num)) - ((len(str(num)) - 1) // 3) * 3] | |
if len(head) == 1: | |
head += "." + str(num)[1] | |
return head + order | |
def total_size(path): | |
total = 0 | |
if os.path.isdir(path): | |
for dirpath, dirnames, filenames in os.walk(path): | |
for f in filenames + dirnames: | |
try: | |
total += os.stat(os.path.join(dirpath, f)).st_size | |
except FileNotFoundError: | |
pass | |
else: | |
total = os.stat(path).st_size | |
return total | |
def main(start=None): | |
if start: | |
dirs = [start] | |
else: | |
dirs = os.listdir(start) | |
for path in dirs: | |
print("{0:>4} {1}".format(humanize(total_size(path)), path)) | |
if __name__=='__main__': | |
if len(sys.argv) > 1: | |
main(sys.argv[1]) | |
else: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment