zoukankan      html  css  js  c++  java
  • 编写类du命令Python脚本

     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             
  • 相关阅读:
    C++_学习随笔_牛郎织女迷宫
    UE4复习5_蓝图接口简单应用
    UE4复习4_射线检测
    今日份学习: Spring中使用AOP并实现redis缓存?
    动态代理,AOP和Spring
    今日份学习:初步的springboot
    HTML常用标签
    关于类的笔记
    关于编码的一个笔记
    Java Socket例程3 UDP
  • 原文地址:https://www.cnblogs.com/dachenzi/p/6802232.html
Copyright © 2011-2022 走看看