#代码统计工具
1 通过参数指定一个绝对路径,sys.argv
2 如果是文件,就直接统计文件的行数,并打印结果
3 判断一下是否为目录,就遍历,统计
找到这个目录下所有的文件,用os.walk可以找到,拼成绝对路径。
规则:
一种是开头是#encoding #-*-
还有一种是''' 或者""",判断某几行是'''或者"""开头,并且是'''或者"""
结尾
空行
两个变量:一个是统计当前文件的行数,还有累计行数
每个文件的路径和代码行,我想到存到字典
import os
import sys
import os.path
#for i in sys.argv:
# print (i)
def count_file_lines(file_path):
line_count = 0
flag =True
try:
fp = open(file_path,"r",encoding="utf-8")
encoding_type="utf-8"
fp.close()
except:
encoding_type="gbk"
with open(file_path,"r",encoding=encoding_type) as fp:
for line in fp:
if line.strip() == "":
continue
else:
if line.strip().endswith("'''") and flag == False:
flag = True
continue
if line.strip().endswith('"""') and flag == False:
flag = True
continue
if flag == False:
continue
if line.strip().startswith("#encoding") \
or line.strip().startswith("#-*-"):
line_count += 1
elif line.strip().startswith('"""') and line.strip().endswith('"""') and line.strip() != '"""':
continue
elif line.strip().startswith("'''") and line.strip().endswith("'''") and line.strip() != "'''":
continue
elif line.strip().startswith("#"):
continue
elif line.strip().startswith("'''") and flag == True:
flag = False
continue
elif line.strip().startswith('"""') and flag == True:
flag = False
continue
else:
line_count += 1
return line_count
def count_code_lines(path,file_types=[]):
if not os.path.exists(path):
print("您输入的目录或者文件路径不存在")
return 0
line_count =0
file_lines_dict ={}
if os.path.isfile(path):
#print("path:",path)
file_type = os.path.splitext(path)[1][1:]
#print(file_type)
#print (file_type in file_types)
if len(file_types)==0:
file_types=["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"]
if file_type in file_types:
line_count=count_file_lines(path)
return line_count
else:
file_path = []
for root, dirs,files in os.walk(path):
for file in files:
file_path.append(os.path.join(root,file))
for f in file_path:
file_type = os.path.splitext(f)[1][1:]
if len(file_types)==0:
file_types=["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"]
if file_type not in file_types:
continue
print (f)
line_num=count_file_lines(f)
line_count+=line_num
file_lines_dict[f]= line_num
return line_count,file_lines_dict
if __name__ == "__main__":
print (sys.argv)
if len(sys.argv) <2:
print ("请输入待统计行数的代码绝对路径!")
sys.exit()
count_path = sys.argv[1]
file_types = []
if len(sys.argv) >2:
for i in sys.argv[2:]:
file_types.append(i)
print (count_path,file_types)
#print(count_code_lines(count_path,file_types))
print(count_file_lines("e:\\b.py"))