今天接到一个电话面试,对方问我在一个项目中维护了多少行代码。
我懵逼了,从来没有统计过啊,怎么还会有这种需求?
当时一脸茫然的想了想,回答了一个,呃...差不多两千多行吧...感觉很心虚
挂完电话之后大概看了一下最近的一个项目,光其中某一个顶层文件就一千多行了好吧,感觉自己回答的好low
但是又不能自己挨个去统计每个文件中到底有多少行代码啊,还要去掉注释和空格,一个文件一个文件的去计算,这显然不是程序员的风格
所以又不务正业了一下,拿python写了个小程序,用来统计某个目录下一个有多少.v文件,有多少行代码。
当然,子目录也是可以统计的。
用法:把以下代码复制到新建的py文件中,将该文件放到你想统计的工程的根目录,运行一下,统计结果会生成到该PY文件的同一级目录,文件名为"code_line_count.txt"
代码如下:
1 # -*- coding: utf-8 -*- 2 import sys 3 import os 4 import codecs 5 6 exts = ['.v','.vhd'] 7 def read_line_count(fname): 8 count = 0 9 with open('code_line_count.txt','a') as f: 10 f.write('fname:%s\n' % fname) 11 with open(fname,'r',encoding='utf8') as f: 12 for file_line in f.readlines(): 13 file_line = file_line.strip() 14 if not len(file_line) or file_line.startswith('//'): 15 continue 16 count += 1 17 with open('code_line_count.txt','a') as f: 18 f.write('line count::%s\n' % count) 19 return count 20 21 if __name__ == '__main__': 22 with open('code_line_count.txt','w') as f: 23 f.write('\n') 24 count = 0 25 fcount = 0 26 for root,dirs,files in os.walk(os.getcwd()): 27 for f in files: 28 # Check the sub directorys 29 print(f) 30 fname = (root + '\\'+ f).lower() 31 if os.path.splitext(f)[1]: 32 ext = f[f.rindex('.'):] 33 try: 34 if(exts.index(ext) >= 0): 35 fcount += 1 36 c = read_line_count(fname) 37 count += c 38 with open('code_line_count.txt','a') as f: 39 f.write('total count:%s\n' % count) 40 except: 41 pass 42 43 with open('code_line_count.txt','a') as f: 44 f.write('\n') 45 f.write('--------------------------------------\n') 46 f.write('total file count:%d\n' % fcount) 47 f.write('total line count:%d\n' % count)
部分结果如下:
两万行被我说成了两千行,哭晕在厕所
转载请注明出处!转载请注明出处!转载请注明出处!