今天接到一個電話面試,對方問我在一個項目中維護了多少行代碼。
我懵逼了,從來沒有統計過啊,怎么還會有這種需求?
當時一臉茫然的想了想,回答了一個,呃...差不多兩千多行吧...感覺很心虛
掛完電話之后大概看了一下最近的一個項目,光其中某一個頂層文件就一千多行了好吧,感覺自己回答的好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)
部分結果如下:
兩萬行被我說成了兩千行,哭暈在廁所