import os
import re
def getPyFilesInDir(dirpath):
flist = os.listdir(dirpath)
pyFileList = []
for name in flist:
filepath = dirpath + "/" + name
if os.path.isfile(filepath) and name.endswith(".py"):
pyFileList.append(filepath)
elif os.path.isfile(filepath) and not name.endswith(".py"):
print("%s不是py源代码文件" % (name))
pass
elif os.path.isdir(filepath):
pyFileList += getPyFilesInDir(filepath)
else:
print("wtf")
return pyFileList
def printListClearly(mlist):
print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
for path in mlist:
print(path)
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
def analyzeCodeFile(path):
totalLines = 0
commentLines = 0
blankLines = 0
effectiveLines = 0
betweenMultipleComment = False
try:
file = open(path, "r", encoding="utf-8")
lineList = file.readlines()
totalLines = len(lineList)
for line in lineList:
if line == "\n":
blankLines += 1
elif re.match("^\s*'''.*'''\s*$", line):
print("%s劳资是自结束多行注释结尾" % (line))
commentLines += 1
betweenMultipleComment = False
elif re.match(r"^\s*'''", line) != None and betweenMultipleComment == False:
betweenMultipleComment = True
commentLines += 1
print("%s劳资是多行注释开头" % (line))
elif re.match(r".*'''\s*$", line) != None and betweenMultipleComment == True:
betweenMultipleComment = False
commentLines += 1
print("%s劳资是多行注释结尾" % (line))
elif betweenMultipleComment:
commentLines += 1
print("%s劳资是多行注释内容" % (line))
elif betweenMultipleComment == False and re.match(r"^\s*#", line) != None:
commentLines += 1
print("%s劳资是单行注释" % (line))
else:
print("%s劳资是单行代码" % (line))
effectiveLines += 1
pass
print("在文件%s中:" % (path))
print("totalLines=", totalLines)
print("commentLines=", commentLines)
print("blankLines=", blankLines)
print("effectiveLines=", effectiveLines)
if effectiveLines < commentLines:
print("\n\n\n\n\n可疑对象\n\n\n\n\n", path)
file.close()
return {"totalLines": totalLines, "commentLines": commentLines, "blankLines": blankLines,
"effectiveLines": effectiveLines}
except UnicodeDecodeError:
print("读取%s发生编码错误" % (path))
pass
def run():
FILE_PATH = r"D:\PycharmProjects\demos\W3"
pyFileList = getPyFilesInDir(FILE_PATH)
printListClearly(pyFileList)
totalLines = 0
commentLines = 0
blankLines = 0
effectiveLines = 0
for path in pyFileList:
resdict = analyzeCodeFile(path)
totalLines += resdict["totalLines"]
commentLines += resdict["commentLines"]
blankLines += resdict["blankLines"]
effectiveLines += resdict["effectiveLines"]
pass
print("==================================================")
print("在文件夹%s中:" % (FILE_PATH))
print("总代码量:%d" % (totalLines))
print("总注释量:%d,占比%.2f%%" % (commentLines, commentLines * 100 / totalLines))
print("总空行数:%d,占比%.2f%%" % (blankLines, blankLines * 100 / totalLines))
print("有效代码:", effectiveLines)
print("==================================================")
if __name__ == '__main__':
run()
pass