2007-12-04
统计python代码量
关键字: python今天闲着没事,花了一点时间写了一个程序来统计一个目录或多个目录下python文件的代码总行数、注释总行数、空行总行数、真正代码总行数。具体代码如下:
python 代码
- class CalculateCode():
- def __init__(self):
- self.total_count = 0
- self.code_count = 0
- self.comment_count = 0
- self.blank_count = 0
- def calculate_file(self, filename):
- file = open(filename, 'r')
- lines = file.readlines()
- line_count = 0
- line_len = len(lines)
- self.total_count += line_len
- while line_count < line_len:
- line_without_space = lines[line_count].strip()
- if not line_without_space:
- self.blank_count += 1
- line_count += 1
- elif line_without_space.startswith('#'):
- self.comment_count += 1
- line_count += 1
- elif line_without_space.startswith("'''"):
- self.comment_count += 1
- line_count += 1
- if not line_without_space.endswith("'''"):
- while line_count < line_len:
- comment_line = lines[line_count].strip()
- self.comment_count += 1
- line_count += 1
- if comment_line.endswith("'''"):
- break
- else:
- self.code_count += 1
- line_count += 1
- def calculate_directory(self, directory):
- import os
- if os.path.isfile(directory):
- if os.path.splitext(directory)[1] == '.py':
- self.calculate_file(directory)
- else:
- raise Exception('The file must be a python file')
- elif os.path.isdir(directory):
- for path in os.listdir(directory):
- if os.path.isdir(directory+'\\'+path):
- self.calculate_directory(directory+'\\'+path)
- elif os.path.splitext(path)[1] == '.py':
- self.calculate_file(directory+'\\'+path)
- else:
- pass
- else:
- raise Exception('No this directory or file!')
- def calculate_directories(self, directories):
- for directory in directories:
- self.calculate_directory(directory)
- def show_result(self):
- print 'total_count: %d\ncode_count: %d\ncomment_count: %d\nblank_count: %d\n' \
- %(self.total_count,self.code_count,self.comment_count,self.blank_count)
- if __name__ == '__main__':
- import sys
- if len(sys.argv) > 1:
- path_list = sys.argv[1:]
- calculate_code = CalculateCode()
- calculate_code.calculate_directories(path_list)
- calculate_code.show_result()
- else:
- print 'Please use command like this:\n"python calculatecode.py directory1 directory2 ..."'
发表评论
- 浏览: 5140 次
- 性别:

- 来自: 北京

- 详细资料
搜索本博客
最近加入圈子
链接
最新评论
-
初步接触pentaho
Pentaho1.7GA版本发布了 欢迎您来http://pentaho.52o ...
-- by keynes.soft -
python利用PIL产生验证码 ...
你可以用Image Module的transform方法来做图片的变形,具体可以 ...
-- by dongin -
python利用PIL产生验证码 ...
我也在找python的验证码程序。 也自己写过比较简单的,但是不太满意。 我希望 ...
-- by guotie






评论排行榜