• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python实现的代码行数统计代码

python 水墨上仙 1701次浏览

python实现的代码行数统计代码

'''
      Author: liupengfei
    Function: count lines of code in a folder iteratively
Shell-format: cmd [dir]
   Attention: default file encode is utf8 and default file type is java-source-file. But users can customize this script by just modifing global variables.
'''
import sys
import os
import codecs
from _pyio import open
totalCount = 0;
fileType = '.java'
descLineBegin = '//'
descBlockBegin = r'/**'
descBlockEnd = r'*/'
fileEncode = 'utf-8'
def main():
    DIR = os.getcwd()
    if len(sys.argv) >= 2:
        DIR = sys.argv[1]
    if os.path.exists(DIR) and os.path.isdir(DIR):
        print('target directory is %s' % DIR)
        countDir(DIR)
        print('total code line is %d' % totalCount)
    else:
        print('target should be a directory!')
def isFileType(file):
    return len(fileType) + file.find(fileType) == len(file)
def countDir(DIR):
    for file in os.listdir(DIR):
        absPath = DIR + os.path.sep + file;
        if os.path.exists(absPath):
            if os.path.isdir(absPath):
                countDir(absPath)
            elif isFileType(absPath):
                try:
                    countFile(absPath)
                except UnicodeDecodeError:
                    print(
                        '''encode of %s is different, which
is not supported in this version!'''
                        )
def countFile(file):
    global totalCount
    localCount = 0
    isInBlockNow = False
    f = codecs.open(file, 'r', fileEncode);
    for line in f:
        if (not isInBlockNow) and line.find(descLineBegin) == 0:
            pass;
        elif (not isInBlockNow) and line.find(descBlockBegin) >= 0:
            if line.find(descBlockBegin) > 0:
                localCount += 1
            isInBlockNow = True;
        elif isInBlockNow and line.find(descBlockEnd) >= 0:
            if line.find(descBlockEnd) + len(descBlockEnd) < len(line):
                localCount += 1
            isInBlockNow = False;
        elif (not isInBlockNow) and len(line.replace('\\s+', '')) > 0:
            localCount += 1
    f.close()
    totalCount += localCount
    print('%s : %d' % (file, localCount))
if __name__ == '__main__':
    main();


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python实现的代码行数统计代码
喜欢 (0)
加载中……