---
title: "统计python代码量"
author: "dongin"
date: "2007-12-04T18:33:44Z"
tags: []
slug: "python"
draft: false
lastmod: "2007-12-04T18:33:44Z"
id: 145970
url: "https://openexperience.iteye.com/blog/145970"
---

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

python 代码

01. class CalculateCode():
02. def \_\_init\_\_(self):
03. self.total\_count = 0
04. self.code\_count = 0
05. self.comment\_count = 0
06. self.blank\_count = 0
07. def calculate\_file(self, filename):
08. file = open(filename, 'r')
09. lines = file.readlines()
10. line\_count = 0
11. line\_len = len(lines)
12. self.total\_count += line\_len
13. while line\_count &lt; 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 &lt; 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) &gt; 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 ..."'