《Python Case系列》一.Python实现统计项目的代码行数

0.背景

前一段时间看Mybatis源码时,突然想看看Mybatis的源码到底有多少号(不算空行)。然后就想用Python写一个。开始的版本是参考网上,现在忘了地址了。。。大概思路是:
1.使用os.walk函数来遍历一个路径下的所有文件,将文件的绝对路径存放在一个list中

2.遍历文件list,统计每一文件去除空行后的行数。

3.输出统计的总行数。

1.完善

第一版的要统计的项目路径时写死在程序中的,文件类型也是。后来我继续完善写成了第二版。在运行Python脚本时,可以将路径和文件类型作为参数,文件类型可以写多个。以下是运行截图:
这里写图片描述

-p之后跟的是路径
-t之后跟的文件的后缀名,多个文件后缀名用空格隔开

2. 源代码

#! /usr/bin/python
# encoding=utf-8

import os
import optparse
import time

file_list = []
type_list = []
def get_file(path):

    if os.path.isdir(path): 
        for parent, dirNames, fileNames in os.walk(path,topdown=True):
            for fileName in fileNames:
                sufix = fileName.split('.')[-1]
                if sufix in type_list:
                    file_list.append(os.path.join(parent, fileName))
    elif os.path.isfile(path):
        file_list.append(path)



def count_line(file):
    count = 0
    for file_line in open(file).xreadlines():
        if file_line != '' and file_line != '\n':
            count += 1

    print file, count
    return count


def main():
    parser = optparse.OptionParser("-p project_path -t file_type1 file_type2...")
    parser.add_option('-p', '--path', dest='path', type='string', help='project path')
    parser.add_option('-t', '--type', dest='type', type='string', help='file type')
    (options, args) = parser.parse_args()
    path = options.path
    file_type = options.type
    args.append(file_type)
    if (path == None) | (file_type == None):
        print('[-] You must specify a project path and serveral file types.')
        return

    for fileType in args:
        type_list.append(fileType)

    start_time = time.clock() 

    total_count = 0
    get_file(path)
    for file in file_list:
        total_count += count_line(file)

    print('=== total line count:%s ===' % total_count)
    print('time:%0.2f second.' % (time.clock() - start_time))

if __name__ == '__main__':
    main()

更多Python case 请参考我的github:https://github.com/Smart-Ha/pycase

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值