python统计代码行数

时间:2023-03-09 06:46:46
python统计代码行数

以前写了一个java的统计代码行数的小程序,最近在看python,于是就参考前辈的代码,写了一个统计文件夹下面各种程序的代码的小程序,这里贴出来供大家参考

参考链接:

https://gist.github.com/linmingren/58d14b5a5fa24e6410af

http://www.cnblogs.com/MikeZhang/archive/2012/08/23/linesCountPython20120823.html

1.运行效果:

python统计代码行数

2.主要的包,函数:

os.path

os.walk(path)

os.path.split(path)[1]

3..代码:

# -*- coding: utf-8 -*-

"""
this is the moduler to count code lines in the given directory.
It ignore blank line but counts the note line.such as #...,//...
__author__ = 'R'
time: 2017.4.21
""" import sys,os filetype = ['.c', '.cpp', '.java', '.py', '.h']
linescount = 0
filescount = 0
c_count = 0
cpp_count = 0
java_count = 0
py_count = 0
h_count = 0 defaultPath = 'D://programmer/python' def countLines(filepath):
global c_count,cpp_count,java_count,py_count,h_count
lines = 0
#这里打开文件经常有无法编码或者无法解码的问题;
with open(filepath, 'rb') as f:
temp = os.path.split(filepath)[1]
for line in f:
if line.strip() != '':
if temp.endswith(filetype[0]):
c_count += 1
lines += 1
elif temp.endswith(filetype[1]):
cpp_count += 1
lines += 1
elif temp.endswith(filetype[2]):
java_count += 1
lines += 1
elif temp.endswith(filetype[3]):
py_count += 1
lines += 1
elif temp.endswith(filetype[4]):
h_count += 1
lines += 1
#这样会导致将所有文件的行数都统计进去了,比如.txt,二进制;
#lines += 1
#print(line)
return lines def countFilesLines(path):
lines = 0
global linescount,filescount
for rootpath, subdirs, filenames in os.walk(path):
for f in filenames:
lines += countLines(os.path.join(rootpath, f))
filescount += 1
linescount = lines
return
if __name__ == '__main__':
print ('counting...')
if len(sys.argv) >= 2:
countFilesLines(sys.argv[1])
else:
countFilesLines(defaultPath)
print ("total files: " , str(filescount))
print ('total code lines: ' + str(linescount))
print ('total c conde lines: ' + str(c_count))
print ('total cpp code lines: ' + str(cpp_count))
print ('total java code lines: ' + str(java_count))
print ('total python code lines: ' + str(py_count))
print ('total .h code lines: ' + str(h_count))