The Last Day Of Summer

.NET技术 C# ASP.net ActiveReport SICP 代码生成 报表应用 RDLC
posts - 305, comments - 1896, trackbacks - 68, articles - 3
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

使用python写的代码行数统计程序

Posted on 2006-04-18 19:33 Cure 阅读(1172) 评论(8)  编辑 收藏 所属分类: Python
因为最近在作的项目很特殊,所使用的语言是一个公司内部的IDE环境,而这个IDE所产生的代码并不是以文本方式存放的,都是放在二进制文件中,而且由于这门语言外界几乎接触不到,所以没有针对它的代码统计程序,当一个模块完成后要统计代码行数会很困难,要统计的话必须先把代码编辑器中的内容拷贝到一个文本类型的文件中。
正好一直在关注python,还没有用python写过程序,今天就利用中午休息的时间写了一个简单的代码统计程序。
对输入的路径作递归,查找代码文件,对每一个代码文件计算它的注释行数,空行数,真正的代码行数。
自己用的程序,就写的粗糙了,也没加异常处理。
主要的python脚本文件LineCount.py的内容如下:
import sys;
import os;

class LineCount:
    
def trim(self,docstring):
        
if not docstring:
            
return ''
        lines 
= docstring.expandtabs().splitlines()
        
        indent 
= sys.maxint
        
for line in lines[1:]:
            stripped 
= line.lstrip()
            
if stripped:
                indent 
= min(indent, len(line) - len(stripped))
        
        trimmed 
= [lines[0].strip()]
        
if indent < sys.maxint:
            
for line in lines[1:]:
                trimmed.append(line[indent:].rstrip())
        
        
while trimmed and not trimmed[-1]:
            trimmed.pop()
        
while trimmed and not trimmed[0]:
            trimmed.pop(0)
        
        
return '\n'.join(trimmed)
    
    
def FileLineCount(self,filename):
        (filepath,tempfilename) 
= os.path.split(filename);
        (shotname,extension) 
= os.path.splitext(tempfilename);
        
if extension == '.txt' or extension == '.hol' : # file type 
            file = open(filename,'r');
            self.sourceFileCount 
+= 1;
            allLines 
= file.readlines();
            file.close();
            
            lineCount    
=0;
            commentCount 
= 0;
            blankCount   
= 0;
            codeCount    
= 0;
            
for eachLine in allLines:
                
if eachLine != " " :
                    eachLine 
= eachLine.replace(" ",""); #remove space
                    eachLine = self.trim(eachLine);      #remove tabIndent
                    if  eachLine.find('--'== 0 :  #LINECOMMENT 
                        commentCount += 1;
                    
else :
                        
if eachLine == "":
                            blankCount 
+= 1;
                        
else :
                            codeCount 
+= 1;
                lineCount 
= lineCount + 1;
            self.all 
+= lineCount;
            self.allComment 
+= commentCount;
            self.allBlank 
+= blankCount;
            self.allSource 
+= codeCount;
            
print filename;
            
print '           Total      :',lineCount ;
            
print '           Comment    :',commentCount;
            
print '           Blank      :',blankCount;
            
print '           Source     :',codeCount;
                    
    
def CalulateCodeCount(self,filename):
        
if os.path.isdir(filename) :
            
if not filename.endswith('\\'):
                filename 
+= '\\'
            
for file in os.listdir(filename):
                
if os.path.isdir(filename + file):
                    self.CalulateCodeCount(filename 
+ file);
                
else:
                    self.FileLineCount(filename 
+ file);
        
else:
            self.FileLineCount(filename);

    
# Open File
    def __init__(self):
        self.all 
= 0;
        self.allComment 
=0;
        self.allBlank 
= 0;
        self.allSource 
= 0;
        self.sourceFileCount 
= 0;
        filename 
= raw_input('Enter file name: ');
        self.CalulateCodeCount(filename);
        
if self.sourceFileCount == 0 :
            
print 'No Code File';
            
pass;
        
print '\n';
        
print '*****************  All Files  **********************';
        
print '    Files      :',self.sourceFileCount;
        
print '    Total      :',self.all;
        
print '    Comment    :',self.allComment;
        
print '    Blank      :',self.allBlank;
        
print '    Source     :',self.allSource;
        
print '****************************************************';

myLineCount 
= LineCount();

可以看到extension == '.txt' or extension == '.hol'这句是判断文件的后缀,来确定是否要计算代码行数。
if  eachLine.find('--') == 0 :这句来判断当前行是不是单行注释(我们的这门语言不支持块注释)。
为了能在其他机器上运行,使用了py2exe来把python脚本生成可执行的exe,setup.py脚本内容如下:
from distutils.core import setup
import py2exe

setup(
   
    version 
= "0.0.1",
    description 
= "LineCount",
    name 
= "LineCount",

    console 
= ["LineCount.py"],
    )

不过生成exe后程序臃肿很多,有3M多。
感觉使用python确实是件很惬意的事。

Feedback

#1楼    回复  引用  查看    

2006-04-19 11:42 by FantasySoft      
哈哈,真巧! 前段时间我也用Python写了一个统计文本文件中相同文本块的小程序,煞是惬意啊! :)

#2楼 [楼主]   回复  引用  查看    

2006-04-19 13:04 by Cure      
python中对文件的操作确实是很方便啊。
python的中外资料太少啦,我都是一边查一边写的:(

#3楼    回复  引用    

2006-12-08 11:08 by DestinyController [未注册用户]
countLine = 0
for fileLine in open(thefilepath).xreadlines( ):
countLine += 1
其实读行数就这一句就够了

#4楼 [楼主]   回复  引用  查看    

2006-12-08 12:35 by Cure      
@DestinyController
多谢指点,我现在还是用C#的习惯套python呢,精髓还没领悟到,呵呵。

#5楼    回复  引用    

2007-07-08 16:22 by snake [未注册用户]
我把要统计的文件test.txt放在c:\下,我在PythonWin下运行后,在弹出的对话框里输c:/test.txt(c:\test.txt或c://test.txt或c:\\test.txt)后出现以下错误是怎么回事啊?


Traceback (most recent call last):
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
File "C:\Documents and Settings\rwzhang.IBM-RWZHANG\桌面\LineCount.py", line 96, in ?
myLineCount = LineCount();
File "C:\Documents and Settings\rwzhang.IBM-RWZHANG\桌面\LineCount.py", line 83, in __init__
self.CalulateCodeCount(filename);
File "C:\Documents and Settings\rwzhang.IBM-RWZHANG\桌面\LineCount.py", line 73, in CalulateCodeCount
self.FileLineCount(self,filename);
TypeError: FileLineCount() takes exactly 2 arguments (3 given)

#6楼 [楼主]   回复  引用  查看    

2007-07-09 15:18 by Cure      
@snake
是self.FileLineCount(self,filename);这一行出现了错误,这个分支自己写的时候没有测到,呵呵,还是太粗心了,刚刚改过了。

#7楼    回复  引用    

2007-07-17 17:28 by simon robin [未注册用户]
这样不可以统计么?

len(opel(filename).readlines())

#8楼 [楼主]   回复  引用  查看    

2007-07-17 22:22 by Cure      
@simon robin
主要是还要算出空行和注释

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2007-07-09 15:17 编辑过


相关链接: