標籤:工作 += end def dirname 功能 圖片 wal 計數
我們在工作或學習代碼的過程中,經常會想知道自己寫了多少行代碼,今天在項目環境寫了個指令碼統計了項目代碼的數量。
功能:
1.統計代碼總行數
2.統計空行數
3.統計注釋行數
# coding=utf-8import os#定義代碼所在的目錄base_path = ‘/home/yhl/workspace/xtp_test‘#在指定目錄下統計所有的py檔案,以列表形式返回def collect_files(dir): filelist = [] for parent,dirnames,filenames in os.walk(dir): for filename in filenames: if filename.endswith(‘.py‘): #將檔案名稱和目錄名拼成絕對路徑,添加到列表裡 filelist.append(os.path.join(parent,filename)) return filelist#計算單個檔案內的程式碼數def calc_linenum(file): with open(file) as fp: content_list = fp.readlines() code_num = 0 #當前檔案程式碼數計數變數 blank_num = 0 #當前檔案空行數計數變數 annotate_num =0 #當前檔案注釋行數計數變數 for content in content_list: content = content.strip() # 統計空行 if content == ‘‘: blank_num += 1 # 統計注釋行 elif content.startswith(‘#‘): annotate_num += 1 # 統計程式碼 else: code_num += 1 # 傳回碼行數,空行數,注釋行數 return code_num,blank_num,annotate_numif __name__ == ‘__main__‘: files = collect_files(base_path) total_code_num = 0 #統計檔案程式碼數計數變數 total_blank_num = 0 #統計檔案空行數計數變數 total_annotate_num = 0 #統計檔案注釋行數計數變數 for f in files: code_num, blank_num, annotate_num = calc_linenum(f) total_code_num += code_num total_blank_num += blank_num total_annotate_num += annotate_num print u‘代碼總行數為: %s‘ % total_code_num print u‘空行總行數為: %s‘ % total_blank_num print u‘注釋行總行數為: %s‘ % total_annotate_num
執行結果:
python統計代碼總行數(程式碼、空行、注釋行)