Next Spaceship

Driving into future…

Python Code for Counting LOC(Lines of Code)

| Comments

Before I know CLOC, SourceCounter or Ohcount, I write this script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Created by Leon <i@leons.im> in 2012
# This code is for Python 2.x

import os, sys

exts = ['.py', '.ini', '.c', '.h']
count_empty_line = True
here = os.path.abspath(os.path.dirname(sys.argv[0]))

def read_line_count(fname):
    count = 0
    for line in open(fname).readlines():
        if count_empty_line or len(line.strip()) > 0:
            count += 1
    return count
if __name__ == '__main__':
    line_count = 0
    file_count = 0
    for base, dirs, files in os.walk(here):
        for file in files:
            # Check the sub directorys            
            if file.find('.') < 0:
                continue
            ext = (file[file.rindex('.'):]).lower()
            try:
                if exts.index(ext) >= 0:
                    file_count += 1
                    path = (base + '/'+ file)
                    c = read_line_count(path)
                    print ".%s : %d" % (path[len(here):], c)
                    line_count += c
            except:
                pass
    print 'File count : %d' % file_count
    print 'Line count : %d' % line_count

Copy and save the script as analytics.py and modify the exts list to include all the file extensions in your project, and put this script in your source code folder, then run:

python analytics.py

Comments