查找sys.path下所有py文件的,并比较文件大小和文件行数

2020-08-25  本文已影响0人  喵呜e喵星人
import os,sys,pprint

trace = 0 #1 代表目录,2代表加上文件
visited ={}
allsize =[]



for srcdir in sys.path:
    for thisDir,subsHere,filesHere in os.walk(srcdir):
        if trace > 0: print(thisDir)
        thisDir = os.path.normpath(thisDir)  #规范路径字符串
        fixcase = os.path.normcase(thisDir)   #规范化路径
        if fixcase in visited:
            continue
        else:
            visited[fixcase] = True
        for filename in filesHere:
            if filename.endswith('.py'):
                if trace>1: print('...',filename)
                pypath = os.path.join(thisDir,filename)
                try:
                    pysize = os.path.getsize(pypath)
                except os.error:
                    print("skipping",pysize,sys.exc_info()[0])
                else:
                    pylines = len(open(pypath,'rb').readlines())
                    allsize.append((pysize,pylines,pypath))

print('By size........')
allsize.sort()
pprint.pprint(allsize[:3])
pprint.pprint(allsize[-3:])

print('By lines..............')
allsize.sort(key=lambda x:x[1])
pprint.pprint(allsize[:3])
pprint.pprint(allsize[-3:])
上一篇 下一篇

猜你喜欢

热点阅读