今天闲着没事,花了一点时间写了一个程序来统计一个目录或多个目录下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 ..."'