python統計代碼總行數(程式碼、空行、注釋行)

來源:互聯網
上載者:User

標籤:工作   +=   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統計代碼總行數(程式碼、空行、注釋行)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.