WEB开发网
开发学院软件开发Python 统计代码行数 阅读

统计代码行数

 2012-05-25 07:53:41 来源:WEB开发网   
核心提示: 输入一个目录,统计目录及子目录下所有代码的总行数,统计代码行数,初学python,参考了Moody _"Kuuy"_ Wizmann的相关代码

 输入一个目录,统计目录及子目录下所有代码的总行数。初学python,参考了Moody _"Kuuy"_ Wizmann的相关代码。
也可以用shell命令直接统计,例如统计当前目录下的cpp文件总行数:
find ./ -name "*.cpp" | xargs cat | wc -l

#/usr/bin/python
import os

#count the line of a single file
def CountLine(path):
        tempfile = open(path)
        res = 0
        for lines in tempfile:
                res += 1
        print "%s %d" %(path, res) #output the file path and lines
        return res

#count the total line of a folder, sub folder included
def TotalLine(path):
        total = 0
        for root, dirs, files in os.walk(path):
                for item in files:
                        ext = item.split('.')
                        ext = ext[-1]  #get the postfix of the file
                        if(ext in ["cpp", "c", "h", "java", "py", "php"]):
                                subpath = root + "/" + item
                                total += CountLine(subpath)
        return total

print "Input Path"
path = raw_input()
print TotalLine(path)

Tags:统计 代码

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接