前序

前两天工作需要用java写了一个Java工程代码量统计工具,最近在学习python,想着锻炼一下,把java代码翻译成python。

使用方法

# -e 文件扩展名
# -f 要统计代码量的文件夹
py StatisticCodeLines.py -e java -f d:\test
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   StatisticCodeLines.py
@Time    :   2021/03/30 17:05:25
@Author  :   Liang Haijiang 
@Version :   1.0
@Contact :   lianghj@geovis.com.cn
@Desc    :   None
'''

# here put the import lib
import os
import argparse
import re

#正常代码
global NORMAL_LINES
NORMAL_LINES = 0
#空白行代码
global WHILE_LINES
WHILE_LINES = 0
#注释代码
global COMMENT_LINES
COMMENT_LINES = 0

def statisticCode(args):
    extName = args.ext
    path = args.folder
    if os.path.exists(path):
        traverseFolder(path,extName)
    total = NORMAL_LINES + WHILE_LINES + COMMENT_LINES
    print('有效行数:' + str(NORMAL_LINES))
    print('空白行数:' + str(WHILE_LINES))
    print('注释行数:' + str(COMMENT_LINES))
    print('总计行数:' + str(total))

def traverseFolder(path,extName):
    if os.path.isdir(path):
        files = os.listdir(path)
        for file in files:
            childPath = os.path.join(path,file)
            traverseFolder(childPath,extName)
    if os.path.isfile(path) and path.endswith(extName):
        parseFile(path)

def parseFile(path):
    global COMMENT_LINES
    global WHILE_LINES
    global NORMAL_LINES

    comment = False
    tempWhiteLines = 0
    tempCommentLines = 0
    tempNormalLines = 0

    fo = open(path,"r",encoding='UTF-8')
    lines = fo.readlines()
    for line in lines:
        line = line.strip()
        if len(line) == 0:
            tempWhiteLines += 1
        elif line.startswith('/*'):
            tempCommentLines += 1
            comment = not line.endswith('*/')
        elif comment and not line.endswith('*/'):
             tempCommentLines += 1
        elif comment and line.endswith('*/'):
            tempCommentLines += 1
            comment = False
        elif line.startswith('//'):
            tempCommentLines += 1
        else:
            tempNormalLines += 1
    fo.close()

    print(path + '::' + str(tempCommentLines) + ':' + str(tempNormalLines) + ':' + str(tempWhiteLines))
    WHILE_LINES += tempWhiteLines
    COMMENT_LINES += tempCommentLines
    NORMAL_LINES += tempNormalLines
if __name__ == "__main__":
    argpaarser = argparse.ArgumentParser()
    argpaarser.add_argument('-e','--ext',help=u'文件后缀名')
    argpaarser.add_argument('-f','--folder',help=u'统计文件夹')
    argpaarser.set_defaults(func = statisticCode)
    args = argpaarser.parse_args()
    args.func(args)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐