本程序基于linux平台,使用python开发,用于统计某个多层文件夹下的源程序的代码行数,程序去掉了以#、//和/*xxx*/的注释行。

#!/usr/bin/env python
import os
import re
import getopt
import sys

total = 0
file_list = []

def trace(dir):
 '''define a function for count the line of source code!'''
 if not os.path.isdir(dir):
  print "You should input a source directory !!!"
  return
 for file in os.listdir(dir):
  fullfile = os.path.join(dir,file)
  if os.path.isfile(fullfile):
   file_list.append(fullfile)
   continue
  if os.path.isdir(fullfile):
  # print 'directory',file
   trace(fullfile)
def count(file):
 starflag = 0
 number = 0
 if not os.path.isfile(file):
  return 0
 f = open(file)
 line = f.readline()
 while(line):
  #print line
  if isNoneLine(line) == 2:
   line = f.readline()
   starflag = 1
   continue
  if isNoneLine(line) == 3:
   line = f.readline()
   starflag = 0
   continue
  if starflag == 1:
   line = f.readline()
   continue
  if isNoneLine(line):
   line = f.readline()
   continue
  else:
   number = number + 1
  line = f.readline()
 return number

def isNoneLine(line):
 patNoneLine = re.compile(r'[\s| ]*\n')
 patdefine = re.compile(r'^#+')
 patsline = re.compile(r'[\s| ]*//')
 patstars = re.compile(r'[\s| ]*/\*[\s|\S]*')
 patstare = re.compile(r'[\s|\S]*\*/$')

 if patdefine.match(line):
  return 1
 if patsline.match(line):
  return 1
 if patstars.match(line):
  return 2
 if patstare.match(line):
  return 3
 if patNoneLine.match(line):
  return 1
 else:
  return 0

def main():
 global file_list
 global total
 try:
  opts, args = getopt.getopt(sys.argv[1:],"d:")
 except:
  print "Usage: ",sys.argv[0],"-d directory"
  sys.exit()
 for o,dir in opts:
  if o == '-d':
   trace(dir)
  else:
   trace(os.getcwd())
 for file in file_list:
  total = total + count(file)
 print total

if __name__ == '__main__':
 main()