#!/usr/bin/python import re,time """IMPROVEMENTS: Let CodeRE allow code lines with ending comments and a comma to still be counted. Allow all .py files to be counted. Allow a recursive count of all .py files in a directory. """ class CountingError(Exception): """Generic exception for CodeCounter""" pass class CodeCounter: def __init__(self,file): self.file=file self.date=(0,0,0,0,0,0,0,0,0) self.code=0 self.doc=0 def count(self): self.date=time.gmtime() DocRE=re.compile(r'.*"""') CodeRE=re.compile(r'\s*[^#].+[^,]$') try: FILE=open(self.file,'r') FILELines=FILE.readlines() finally: FILE.close() doc=0 for line in FILELines: if doc: if DocRE.match(line): self.doc=self.doc+1 doc=0 continue else: self.doc=self.doc+1 continue elif DocRE.match(line): self.doc=self.doc+1 doc=1 continue elif CodeRE.match(line): self.code=self.code+1 continue return 1 class TextCounter(CodeCounter): def __repr__(self): return '' % (self.file, self.date[0], self.date[1], self.date[2], self.date[3], self.date[4], self.date[5], self.code, self.doc) def output(self): print print 'For %s (%s-%s-%s %s:%s:%s UTC):' % (self.file, self.date[0], self.date[1], self.date[2], self.date[3], self.date[4], self.date[5]) print print 'Lines of code --\t\t%s' % self.code print 'Lines of doc strings --\t\t%s' % self.doc print '-'*70 print 'TOTAL --\t\t\t%s' % (self.code+self.doc) if self.code > self.doc: print '(more lines of code than doc strings)' else: print '(more lines of doc strings than code)' def prompt(): flag=1 while flag: file=raw_input('Enter the path of the file:') if not os.path.isfile(file): print 'I am sorry, but that is not a valid path...\n' else: linecount=TextCounter(file) flag=0 print print 'counting...' linecount.count() print print linecount.output() if __name__=='__main__': prompt()