Python實現代碼行數統計工具


我們經常想要統計項目的代碼行數,但是如果想統計功能比較完善可能就不是那么簡單了, 今天我們來看一下如何用python來實現一個代碼行統計工具。

思路:首先獲取所有文件,然后統計每個文件中代碼的行數,最后將行數相加.

實現的功能:

統計每個文件的行數;

統計總行數;

統計運行時間;

支持指定統計文件類型,排除不想統計的文件類型;

遞歸統計文件夾下包括子文件件下的文件的行數;

排除空行;

 

# coding=utf-8
import os
import time
basedir = '/root/script'
filelists = []
# 指定想要統計的文件類型
whitelist = ['php', 'py']
#遍歷文件, 遞歸遍歷文件夾中的所有
def getFile(basedir):
    global filelists
    for parent,dirnames,filenames in os.walk(basedir):
        #for dirname in dirnames:
        #    getFile(os.path.join(parent,dirname)) #遞歸
        for filename in filenames:
            ext = filename.split('.')[-1]
            #只統計指定的文件類型,略過一些log和cache文件
            if ext in whitelist:
                filelists.append(os.path.join(parent,filename))
#統計一個文件的行數
def countLine(fname):
    count = 0
    for file_line in open(fname).xreadlines():
        if file_line != '' and file_line != '\n': #過濾掉空行
            count += 1
    print fname + '----' , count
    return count
if __name__ == '__main__' :
    startTime = time.clock()
    getFile(basedir)
    totalline = 0
    for filelist in filelists:
        totalline = totalline + countLine(filelist)
    print 'total lines:',totalline
    print 'Done! Cost Time: %0.2f second' % (time.clock() - startTime)

 

結果:

[root@pythontab script]# python countCodeLine.py 
/root/script/test/gametest.php---- 16
/root/script/smtp.php---- 284
/root/script/gametest.php---- 16
/root/script/countCodeLine.py---- 33
/root/script/sendmail.php---- 17
/root/script/test/gametest.php---- 16
total lines: 382
Done! Cost Time: 0.00 second
[root@pythontab script]#

 

只會統計php和python文件,非常方便。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM