简易统计Python有效代码行数

来源:互联网 发布:手机锁帧软件 编辑:程序博客网 时间:2024/05/16 09:59

有的时候看源码或者py文件时,想知道有效代码行数是多少,即除了注释外的所有行数,比如requests源码中,sessions.py文件,带注释共有712行(不知道有没有更新。。。),去除注释后统计行数为326行,你看,这一下子就少了一半多,看源码是不是更有动力了。。。(我使用的版本requests去除注释后才2146行(不包括使用的packages里面的包))

以下为我的实现代码,聊作参考~

# -*- coding: utf-8 -*-# @Author: xiaodong# @Date:   2017-12-18 18:54:56# @Last Modified by:   xiaodong# @Last Modified time: 2017-12-18 19:05:10'''简易统计Python代码行数'''def count_code_nums(file):    """    :param file: 文件路径,.py文件    :rtype :int    """    with open(file,encoding='utf-8') as data:        count, flag = 0, 0        begin = ('"""', "'''")        for line in data:            line2 = line.strip()            if line2.startswith('#'):continue            elif line2.startswith(begin):                if line2.endswith(begin) and len(line2) > 3:                    flag = 0                    continue                elif flag == 0:                    flag = 1                else:                    flag = 0                    continue            elif flag == 1 and line2.endswith(begin):                flag = 0                continue            if flag == 0 and line2:                count += 1    return countdef detect_rows(begin=0, root='.'):    """    统计指定文件夹内所有py文件代码量    :param begin: 起始,一般使用默认0即可    :param root: 需要统计的文件(文件夹)路径    :rtype :int    """    import os, glob    for file in glob.glob(os.path.join(root, '*')):        if os.path.isdir(file):            begin += detect_rows(0, file)        elif file.endswith('.py'):            begin += count_code_nums(file)    return beginif __name__ == '__main__':    print (count_code_nums(__file__))    print (detect_rows())