A little source file analyzer
DFS
nospam at dfs.com
Wed Oct 26 16:47:21 EDT 2022
Nothing special, but kind of fun to use
$python progname.py sourcefile.py
---------------------------------------------------------
#count blank lines, comments, source code
import sys
#counters
imports, blanks,comments, source = 0,0,0,0
functions, dbexec, total = 0,0,0
#python builtins
builtins = 0
bins =
['abs','aiter','all','any','anext','ascii','bin','bool','breakpoint','bytearray','bytes','callable','chr','classmethod','compile','complex','delattr','dict','dir','divmod','enumerate','eval','exec','filter','float','format','frozenset','getattr','globals','hasattr','hash','help','hex','id','input','int','isinstance','issubclass','iter','len','list','locals','map','max','memoryview','min','next','object','oct','open','ord','pow','property','range','repr','reversed','round','set','setattr','slice','sorted','staticmethod','str','sum','super','tuple','type','vars','zip']
bins2,bins3 = [],[]
for bi in bins: bins2.append(' ' + bi + '(') #look for leading space
then builtin then open paren
#todo use for source files other than .py
ccomments = 0
py_comment = ['#','~','@']
c_comment = ['/*','//']
#read file
f = open(sys.argv[1], encoding='utf-8')
lines = f.read().splitlines()
f.close()
#print builtin usage count
#def binusage():
#iterate file
linenbr = 0
for line in lines:
line = line.strip()
linenbr += 1
if line == '' : blanks += 1
if line != '':
if line[0:1] == '#' : comments += 1
if line[0:3] == '"""' : comments += 1
if line[-3:1] == '"""' : comments += 1
if line[0:1] not in ['#','"']:
source += 1
if line[0:3] == 'def' and line[-2:] == '):' : functions += 1
if '.execute' in line : dbexec += 1
if 'commit()' in line : dbexec += 1
if 'import' in line : imports += 1
if 'print(' in line : bins3.append('print')
for bi in bins2: #usage of a python builtin function
if bi in line:
bins3.append(bi[1:-1])
total += 1
#output
print('imports : ' + str(imports))
print('source : ' + str(source))
print('-functions: ' + str(functions))
print('-db exec : ' + str(dbexec) + 'x')
ctxt = ''
x = [(i,bins3.count(i)) for i in sorted(set(bins3))]
for bi,cnt in x: ctxt += bi + '('+ str(cnt) + '), '
print('-builtins : ' + str(len(bins3)) + 'x [' + ctxt[:-2] + ']')
print('comments : ' + str(comments))
print('blanks : ' + str(blanks))
print('Total : ' + str(total))
---------------------------------------------------------
More information about the Python-list
mailing list