[原创]Python小工具 —— 计算 文件 或 文件夹及其所有子文件夹中所有文件 的 代码行数

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2012 - Yang Zhao <yangzhao3d@gmail.com>

import sys, codecs, os, traceback

print 'Count Code Lines of Files In Current File or Folder with All It\'s Subfolders'
print 'Copyright (c) 2012 - Yang Zhao <yangzhao3d@gmail.com>\n'

all_line_count = 0
file_count = 0
def process_file(path):
    global all_line_count, file_count
    file_count = file_count + 1
    current_line_count = 0
    with open(path, 'r') as fr:
        for line in fr:
            all_line_count = all_line_count + 1
            current_line_count = current_line_count + 1
    #print '%d. File: %s, lines: %d' % (file_count, path, current_line_count)
def process_para(path):
    if not os.path.isdir(path) and not os.path.isfile(path):
        return False
    if os.path.isfile(path):
        process_file(path)
    else:
        for item in os.listdir(path): # process the whole directory
            subpath = os.path.join(path, item)
            process_para(subpath)
def print_usage():
    print 'Usage:\n%s [input file or directory]' % os.path.basename(sys.argv[0])


try:
    process_para(sys.argv[1])
    print '-- All File Count: %d, lines: %d --' % (file_count, all_line_count)
except:
    print_usage()
    print traceback.print_exc()
    sys.exit(1)

posted @ 2012-08-31 08:36  杨钊  阅读(176)  评论(0编辑  收藏  举报