如何统计Python代码行数

import os
import sys

# Scan all python files name and path.
def _scan_file_by_type(file_path, last_dir, file_type, file_list):

    if last_dir == '':
        full_path = file_path
    else:
        full_path = file_path + '/' + last_dir

    if os.path.isdir(full_path):
        _list_dir = os.listdir(full_path)
        for _ele in _list_dir:
            _scan_file_by_type(full_path, _ele, file_type, file_list)
    else:
        if last_dir.endswith(".py"):
            file_list.append(file_path + '/' + last_dir)


def stat_py_files(project_path):

    # Get files list.
    py_file_list = list()
    _scan_file_by_type(project_path, '', 'py', py_file_list)

    # Start to statics files line.
    comment_num = 0
    blank_num = 0
    code_num = 0

    for py_file in py_file_list:
        py_file_handle = file(py_file)
        is_comment_start = False

        while True:
            _line = py_file_handle.readline()
            if _line:

                # comment ''' line.
                mark_num = _line.count("'''")
                if mark_num:
                    if mark_num % 2 == 1:
                        is_comment_start = False if is_comment_start else True
                    comment_num += 1
                    continue

                # comment """ line.
                mark_num = _line.count('"""')
                if mark_num:
                    if mark_num % 2 == 1:
                        is_comment_start = False if is_comment_start else True
                    comment_num += 1
                    continue

                # comment # line.
                mark_num = _line.count('#')
                if mark_num:
                    comment_num += 1
                    continue

                # blank line.
                mark_num = _line.count(' ') + _line.count('\n')
                if mark_num == len(_line):
                    blank_num += 1
                    continue

                # Code Line.
                if is_comment_start is False:
                    code_num += 1
                else:
                    comment_num += 1
            else:
                print '%s...OK' % py_file
                break

    total_line = comment_num + blank_num + code_num
    print '****** Result ******'
    print 'Total    : %d' % total_line
    print 'Comment  : %d  %.2f %%' % (comment_num, float(comment_num)*100/float(total_line))
    print 'Blank    : %d  %.2f %%' % (blank_num, float(blank_num)*100/float(total_line))
    print 'Code     : %d  %.2f %%' % (code_num, float(code_num)*100/float(total_line))
    print '********************'

def main(argv):
    stat_py_files(argv)    
if __name__ == '__main__':
    main(sys.argv[1])

posted on 2015-10-29 15:36  ruce.fan  阅读(205)  评论(0编辑  收藏  举报

导航