您的位置:首页 > 编程语言 > Python开发

《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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: