您当前的位置:首页 > 计算机 > 编程开发 > Python

用python3统计代码行数

时间:01-20来源:作者:点击数:
CDSY,CDSY.XYZ

今天接到一个电话面试,对方问我在一个项目中维护了多少行代码。

我懵逼了,从来没有统计过啊,怎么还会有这种需求?

当时一脸茫然的想了想,回答了一个,呃...差不多两千多行吧...感觉很心虚

挂完电话之后大概看了一下最近的一个项目,光其中某一个顶层文件就一千多行了好吧,感觉自己回答的好low

但是又不能自己挨个去统计每个文件中到底有多少行代码啊,还要去掉注释和空格,一个文件一个文件的去计算,这显然不是程序员的风格

所以又不务正业了一下,拿python写了个小程序,用来统计某个目录下一个有多少.v文件,有多少行代码。

当然,子目录也是可以统计的。

用法:把以下代码复制到新建的py文件中,将该文件放到你想统计的工程的根目录,运行一下,统计结果会生成到该PY文件的同一级目录,文件名为"code_line_count.txt"

代码如下:

# -*- coding: utf-8 -*-
import sys
import os
import codecs

exts = ['.v','.vhd']
def read_line_count(fname):
    count = 0
    with open('code_line_count.txt','a') as f:
        f.write('fname:%s\n' % fname)
    with open(fname,'r',encoding='utf8') as f:
        for file_line in f.readlines():
            file_line = file_line.strip()
            if not len(file_line) or file_line.startswith('//'):
                continue
            count += 1
    with open('code_line_count.txt','a') as f:
        f.write('line count::%s\n' % count)
    return count

if __name__ == '__main__':
    with open('code_line_count.txt','w') as f:
        f.write('\n')
    count = 0
    fcount = 0
    for root,dirs,files in os.walk(os.getcwd()):
        for f in files:
            # Check the sub directorys
            print(f)
            fname = (root + '\\'+ f).lower()
            if os.path.splitext(f)[1]:
                ext = f[f.rindex('.'):]
                try:
                    if(exts.index(ext) >= 0):
                        fcount += 1
                        c = read_line_count(fname)
                        count += c
                        with open('code_line_count.txt','a') as f:
                            f.write('total count:%s\n' % count)
                except:
                    pass

    with open('code_line_count.txt','a') as f:
        f.write('\n')
        f.write('--------------------------------------\n')
        f.write('total file count:%d\n' % fcount)
        f.write('total line count:%d\n' % count)

部分结果如下:

CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门