ITeye博客

统计python代码量

dongin · 2007-12-04 18:33 · 工作乐趣 · Markdown

今天闲着没事,花了一点时间写了一个程序来统计一个目录或多个目录下python文件的代码总行数、注释总行数、空行总行数、真正代码总行数。具体代码如下:

python 代码

  1. class CalculateCode():
  2. def __init__(self):
  3. self.total_count = 0
  4. self.code_count = 0
  5. self.comment_count = 0
  6. self.blank_count = 0
  7. def calculate_file(self, filename):
  8. file = open(filename, 'r')
  9. lines = file.readlines()
  10. line_count = 0
  11. line_len = len(lines)
  12. self.total_count += line_len
  13. while line_count < line_len:
  14. line_without_space = lines[line_count].strip()
  15. if not line_without_space:
  16. self.blank_count += 1
  17. line_count += 1
  18. elif line_without_space.startswith('#'):
  19. self.comment_count += 1
  20. line_count += 1
  21. elif line_without_space.startswith("'''"):
  22. self.comment_count += 1
  23. line_count += 1
  24. if not line_without_space.endswith("'''"):
  25. while line_count < line_len:
  26. comment_line = lines[line_count].strip()
  27. self.comment_count += 1
  28. line_count += 1
  29. if comment_line.endswith("'''"):
  30. break
  31. else:
  32. self.code_count += 1
  33. line_count += 1
  34. def calculate_directory(self, directory):
  35. import os
  36. if os.path.isfile(directory):
  37. if os.path.splitext(directory)[1] == '.py':
  38. self.calculate_file(directory)
  39. else:
  40. raise Exception('The file must be a python file')
  41. elif os.path.isdir(directory):
  42. for path in os.listdir(directory):
  43. if os.path.isdir(directory+'\\'+path):
  44. self.calculate_directory(directory+'\\'+path)
  45. elif os.path.splitext(path)[1] == '.py':
  46. self.calculate_file(directory+'\\'+path)
  47. else:
  48. pass
  49. else:
  50. raise Exception('No this directory or file!')
  51. def calculate_directories(self, directories):
  52. for directory in directories:
  53. self.calculate_directory(directory)
  54. def show_result(self):
  55. print 'total_count: %d\ncode_count: %d\ncomment_count: %d\nblank_count: %d\n' \
  56. %(self.total_count,self.code_count,self.comment_count,self.blank_count)
  57. if __name__ == '__main__':
  58. import sys
  59. if len(sys.argv) > 1:
  60. path_list = sys.argv[1:]
  61. calculate_code = CalculateCode()
  62. calculate_code.calculate_directories(path_list)
  63. calculate_code.show_result()
  64. else:
  65. print 'Please use command like this:\n"python calculatecode.py directory1 directory2 ..."'

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。