Created
May 2, 2015 05:41
-
-
Save dorthrithil/d9d2f454fdc56b9f48dd to your computer and use it in GitHub Desktop.
calculates & prints loc and ncloc of python files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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