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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

详解Python装饰器

1. 定义 本质是函数,用来装饰其他函数,为其他函数添加附加功能 2. 原则 a. 不能修改被装饰函数的源代码 b. 不能修改被装饰的函数的调用方式 3. 实现装饰器知识储备 a. 函数...

django框架实现一次性上传多个文件功能示例【批量上传】

django框架实现一次性上传多个文件功能示例【批量上传】

本文实例讲述了django框架实现一次性上传多个文件功能。分享给大家供大家参考,具体如下: 在用django 写文件上传的时候,从request.FILES['myfiles'] 获取到...

Django contenttypes 框架详解(小结)

Django contenttypes 框架详解(小结)

一、什么是Django ContentTypes? Django ContentTypes是由Django框架提供的一个核心功能,它对当前项目中所有基于Django驱动的model提供了...

使用Pyinstaller转换.py文件为.exe可执行程序过程详解

使用Pyinstaller转换.py文件为.exe可执行程序过程详解

 前言 pyinstaller能够在Windows、Linux等操作系统下将Python脚本打包成可直接运行程序。使Python脚本可以在没有安装Python的环境中直接运行,...

python实现在pickling的时候压缩的方法

本文实例讲述了python实现在pickling的时候压缩的方法。分享给大家供大家参考。 具体方法如下: import cPickle,gzip def save(filename,...