"""Calculate LOC (lines of code) for a given package directory.""" import os import re def loc(path, pattern="^.*\.py$"): """Return the number of lines of code for all files in the given path. If the 'pattern' argument is provided, it must be a regular expression against which each filename will be matched. By default, all filenames ending in ".py" are analyzed. """ lines = 0 for root, dirs, files in os.walk(path): for name in files: if re.match(pattern, name): f = open(os.path.join(root, name), 'rb') for line in f: line = line.strip() if line and not line.startswith("#"): lines += 1 f.close() return lines