《Python Case系列》一.Python实现统计项目的代码行数
2016-10-21 19:28
1016 查看
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
相关文章推荐
- Python脚本实现代码行数统计代码分享
- python实现统计代码行数的方法
- 统计项目的代码行数(python处女作)
- 代码行数统计(python实现)
- Python脚本实现代码行数统计代码分享
- python实现代码行数统计示例分享
- 统计C#项目有效代码行数的实现过程
- 代码行数统计(python实现)
- python实现的代码行数统计(纯代码)
- python实现统计代码行数的方法
- 代码行数统计的Java和Python实现
- python实现代码行数统计示例分享
- 统计代码行数(python实现)
- python实现代码行数统计
- python 统计代码行数,注释行数的简单实现
- 应用eclipse统计项目代码行数
- 统计项目代码行数Count Lines of Code(CLOC)
- 递归统计项目中的非空白代码行数
- python写的代码行数统计程序
- [JAVA实用应用] 项目代码行数统计器,帮助你统计项目一共有多少行代码