14.11.11

Simple Source Code Count (Python)

Here is a simple way to count your lines of source code using python.

The command-line tool takes a source directory and a comma-delimited list of valid file extensions.

#Source Lines of Code ----------------------------------------------

import os
import sys

from optparse import OptionParser

def main(source_directory, extensions):
    files = get_file_path_list(source_directory, extensions)
    counts = [get_line_count(f) for f in files]
    
    print 'file count: %i' % len(files)
    print 'line count: %i' % sum(counts)

def get_file_path_list(root_directory, extensions):
    files = []
    for directory, dirnames, filenames in os.walk(root_directory):
        for f in filenames:
            ext = os.path.splitext(f)[1]
            if ext in extensions:
                files.append(os.path.join(directory, f))
    return files

def get_line_count(path):
    f = open(path, 'r')
    lineCount = len(f.readlines())
    f.close()
    return lineCount

def parseListOption(option, opt, value, parser):
    setattr(parser.values, option.dest, value.split(','))


if __name__ == '__main__':
    
    parser = OptionParser(usage="usage: %prog [options] filename",
                          version="%prog 1.0")
    
    parser.add_option("-d", "--dir",
                      dest="source_directory",
                      help="Path to directory of source code")

    parser.add_option("-e", "--exts",
                      type='string',
                      action='callback',
                      dest="extensions",
                      callback=parseListOption,
                      help="Path to directory of source code")
    
    (options, args) = parser.parse_args()

    main(options.source_directory, options.extensions)

I'm on a windows environment, so I run the tool with the following command on powershell:


PS > python countDirectoryLineCount.py -d source_directory -e extensions (.py,.as,.mxml,.cs,.java)

No comments:

Post a Comment