python实现代码行数统计示例分享

yipeiwu_com5年前Python基础

复制代码 代码如下:

#!/usr/bin/python

'''
        File      : count.py
        Author    : Mike
        E-Mail    : Mike_Zhang@live.com
'''
import sys,os

extens = [".c",".cpp",".hpp",".h"]
linesCount = 0
filesCount = 0

def funCount(dirName):
    global extens,linesCount,filesCount
    for root,dirs,fileNames in os.walk(dirName):
        for f in fileNames:
            fname = os.path.join(root,f)
            try :
                ext = f[f.rindex('.'):]
                if(extens.count(ext) > 0):
                    print 'support'
                    filesCount += 1
                    print fname
                    l_count = len(open(fname).readlines())
                    print fname," : ",l_count
                    linesCount += l_count
                else:
                    print ext," : not support"
            except:
                print "Error occur!"
                pass


if len(sys.argv) > 1 :
    for m_dir in sys.argv[1:]:       
        print m_dir
        funCount(m_dir)
else :
    funCount(".")       

print "files count : ",filesCount
print "lines count : ",linesCount

raw_input("Press Enter to continue")

使用方法
1、针对本目录

复制代码 代码如下:

./count.py

2、统计多个目录

复制代码 代码如下:

./count.py /tmp ~

相关文章

对python中的*args与**kwgs的含义与作用详解

在定义函数的时候参数通常会使用 *args与**kwgs,形参与实参的区别不再赘述,我们来解释一下这两个的作用。 *args是非关键字参数,用于元组,**kw是关键字参数 例如下面的代...

Python获取时间范围内日期列表和周列表的函数

Python获取时间范围内日期列表和周列表的函数

Python获取时间范围内日期列表和周列表的函数 1、获取日期列表 # -*- coding=utf-8 -*- import datetime def dateRange(beg...

浅谈python为什么不需要三目运算符和switch

对于三目运算符(ternary operator),python可以用conditional expressions来替代 如对于x<5?1:0可以用下面的方式来实现...

Python scikit-learn 做线性回归的示例代码

Python scikit-learn 做线性回归的示例代码

一、概述 机器学习算法在近几年大数据点燃的热火熏陶下已经变得被人所“熟知”,就算不懂得其中各算法理论,叫你喊上一两个著名算法的名字,你也能昂首挺胸脱口而出。当然了,算法之林虽大,但能者...

Python2.5/2.6实用教程 入门基础篇

起步走 复制代码 代码如下: #! /usr/bin/python a=2 b=3 c="test" c=a+b print "execution result: %i"%c 知识点...