Skip to content

Instantly share code, notes, and snippets.

@dorthrithil
Created May 2, 2015 05:41
Show Gist options
  • Save dorthrithil/d9d2f454fdc56b9f48dd to your computer and use it in GitHub Desktop.
Save dorthrithil/d9d2f454fdc56b9f48dd to your computer and use it in GitHub Desktop.
calculates & prints loc and ncloc of python files
import tokenize
from token import *
def print_metrics(path):
"""prints LOC and NCLOC of the input file"""
fo = open(path, "rb") # open file in byte mode
tokens = tokenize.tokenize(fo.readline) # tokenize it
# counters
ncloc = -2 # we don't want to count endmarker & encoding
loc = -2
tokens = list(tokens)
for i, token in enumerate(tokens):
if token.start[0] != tokens[i-1].start[0]: # this way we only count whole-line comments
loc += 1
ncloc += 1
if tok_name[token.type] == "COMMENT": # comment detected
ncloc -= 1
elif tok_name[token.type] == "NL": # empty line detected
ncloc -= 1
print("LOC in \"{0}\": {1}".format(fo.name, loc))
print("NCLOC in \"{0}\": {1}".format(fo.name, ncloc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment