1 #!/usr/bin/env python 2 #_*_ coding:utf-8 _*_ 3 #计算整个目录的大小,脚本接受-H参数,来加上适当的单位 4 #功能像du看齐 5 6 import os,sys 7 from optparse import OptionParser 8 9 10 def option(): 11 parser = OptionParser() 12 parser.add_option('-H','--Human',dest='human',action='store_true',default=False,help='print sizes in human readable format') 13 option,args = parser.parse_args() 14 return option,args 15 16 def findfile(dirpath): 17 path = os.walk(dirpath) 18 for roots,dirs,files in path: 19 for file in files: 20 yield os.path.join(roots,file) 21 22 23 def filesize(option,file): 24 size = os.path.getsize(file) 25 if not option: 26 return str(size) 27 else: 28 if size >= 1024000000: 29 return str(size/1024/1024/1024) + 'G' 30 elif size >= 1024000: 31 return str(size/1024/1024) + 'M' 32 elif size >= 4096: 33 return str(size/1024) + 'K' 34 else: 35 return '4.0K' 36 37 38 def main(): 39 options,args = option() 40 try: 41 path = args[0] 42 except IndexError as e: 43 sys.exit('%s need a directory' % __file__) 44 for file in findfile(path): 45 size = filesize(options.human,file) 46 print size,file 47 48 49 if __name__ == '__main__': 50 main() 51