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

本文实例讲述了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程序设计有所帮助。

Posted in 未分类