robot 源码解读1【代码量】

  1. 先看看多少代码量


import os


file_types = ['py',
             'html',
             'css',
             'js',
             ]


def count_code_nums(file):
    """获取单个文件的行数
    """
    with open(file, mode='rb') as f:
        return len(f.readlines())


def count_code_nums_pro(file):
    """获取单个文件的行数-去注解,utf8代码
    """
    with open(file, mode ='r',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
            else:
                # 不用处理,flag == 1 的中间注释行
                pass
            # 标志没有置上的有效行才计数
            if flag == 0 and line2:
                count += 1
    return count


def get_all_file_in_paths(path, end_with=['py','html','css','js']):
    """获取给定路径下所有子文件路径
    """
    res = []
    for r_path in os.walk(path):
        for f_name in r_path[2]:
            str_list = f_name.rsplit('.', maxsplit=1)
            if end_with:
                if str_list.pop() in end_with:
                    # print(f_name)
                    res.append(os.path.join(r_path[0], f_name))
            else:
                res.append(os.path.join(r_path[0], f_name))
    return res


def file_path(path, pro_mode=True, file_type=file_types):
    total_line = 0
    file_list = get_all_file_in_paths(path, end_with=file_type)
    for file in file_list:
        if pro_mode:
            line_num = count_code_nums_pro(file)
        else:
            line_num = count_code_nums(file)
        total_line += line_num
    return total_line


if __name__ == '__main__':

    dir_path = r'C:\Python\site-packages\robot'
    lines = file_path(dir_path, pro_mode=False,file_type=None ) # 计算注解,所有文件类型          # 64063
    # lines = file_path(dir_path, pro_mode=False, ) # 计算注解,文件类型 ['py','html','css','js'] # 46128
    # lines = file_path(dir_path, pro_mode=True)    # 去掉注解,文件类型 ['py','html','css','js'] # 26409
    print('robot is:', lines)
posted @ 2021-03-27 08:48  该显示昵称已被使用了  阅读(104)  评论(0编辑  收藏  举报