1 #!/usr/bin/env python2 #_*_ coding:utf-8 _*_3 #to calculate the size of the entire directory, the script accepts the-h parameter to add the appropriate units4 #function like du on par5 6 ImportOs,sys7 fromOptparseImportOptionparser8 9 Ten defoption (): OneParser =Optionparser () AParser.add_option ('- H','--human', dest='Human', action='store_true', default=false,help='print sizes in human readable format') -Option,args =Parser.parse_args () - returnOption,args the - defFindFile (dirpath): -Path =Os.walk (Dirpath) - forRoots,dirs,filesinchPath: + forFileinchFiles: - yieldOs.path.join (roots,file) + A at deffilesize (option,file): -Size =os.path.getsize (file) - if notoption: - returnStr (size) - Else: - ifSize >= 1024000000: in returnSTR (size/1024/1024/1024) +'G' - elifSize >= 1024000: to returnSTR (size/1024/1024) +'M' + elifSize >= 4096: - returnSTR (size/1024) +'K' the Else: * return '4.0K' $ Panax Notoginseng - defMain (): theOptions,args =option () + Try: APath =Args[0] the exceptIndexerror as E: +Sys.exit ('%s need a directory'%__file__) - forFileinchfindfile (path): $Size =filesize (options.human,file) $ PrintSize,file - - the if __name__=='__main__': - Main ()Wuyi
Writing a class du command python script