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 接口_从协议到抽象基类详解

python 接口_从协议到抽象基类详解

抽象基类的常见用途:实现接口时作为超类使用。然后,说明抽象基类如何检查具体子类是否符合接口定义,以及如何使用注册机制声明一个类实现了某个接口,而不进行子类化操作。最后,说明如何让抽象基类...

python tkinter canvas 显示图片的示例

先来看一下该方法的说明 create_image(position, **options) [#] Draws an image on the canvas. position I...

python在不同层级目录import模块的方法

使用python进行程序编写时,经常会使用第三方模块包。这种包我们可以通过python setup install 进行安装后,通过import XXX或from XXX import...

解决Django layui {{}}冲突的问题

layui的table的自定义模板需要用到{{}},但是和Django的{{}}冲突了,layui的{{}}失效了 解决方法:从Django 1.5开始,支持{% verbatim %}...

Python实现利用163邮箱远程关电脑脚本

学了一个礼拜Python之后写的,代码很粗糙,只是为了完成利用163邮箱远程关电脑功能。直接把代码发上来吧。要执行的话得先安装一些模块,看import语句。 十月初写的,写完这个之后就没...