An automatic statistic instance of code line in Python implementation

Source: Internet
Author: User
Tags trim python script in python

This feature is addressed with 2 Common Python standard library OS and SYS modules.

Probably because of this time in a Python project, with a company's internal IDE environment, and this IDE environment generated the PY code is not stored in text, are placed in binary files.

Since the language is barely accessible, there is no code-counting program for it. It is very difficult to count the number of lines of code after a module is completed, so it is not in line with the style of our programmers to count words to operate only by hand.

I've been looking at the Python language for a while, but haven't actually written a python program yet. Today I wrote a simple code-counting program using the time of noon break. A recursive lookup code file for the input path calculates the number of comment lines, blank lines, and real lines of code for each code file.

Count lines of code Python code is as follows:

The code is as follows Copy Code
#coding =utf-8


#iplaypython. 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 ();



We see that the code extension = = '. txt ' or extension = = '. Hol ' is used to determine the suffix name of the file, and whether you want to calculate the number of lines of code.

If Eachline.find ('--') = 0: is used to determine whether the current row is a single-line annotation, in order to be able to run on other machines, using the Py2exe to generate the executable exe for the Python script.

  code is as follows copy code
from Distutils.core Import Setup
Import py2exe

Setup (
 
    Version = "0.0.1",
    Description = "LineCount",
    name = "LineCount",
 
  &nb Sp console = ["linecount.py"],
   )




use Python to count source code lines and to format source code

Recently wrote a software need to do software copyright registration, the need to count the source code lines and the submission of some source code, just use Python to write such a small tool.

Usage is as follows:

In the Windows Command Line window, use the Python python_count_line.py source_code_root_directory.

The source_code_root_directory is the root of the source code that needs to be counted, and can be recursively traversed if there are other subdirectories in the source directory.

The source code is as follows:

The code is as follows Copy Code
Import Os,sys





def count_line (filename):


"" "Count the line number of file" "


with open (filename) as file:


lines = File.readlines ()


File.close ()


Return Len (lines)





def read_lines_and_write_to_target (Source_filename,target_file,begin_linenum):


LineNum = Begin_linenum


With open (Source_filename) as Source_file:


lines = Source_file.readlines ()


For I in range (len (lines)):


Target_file.write ("%4d"%linenum+ "")


Target_file.write (Lines[i])


LineNum = linenum+1


Source_file.close ()


Return LineNum





def flatten (LST):


For x in LST:


If Isinstance (x,list):


For x in Flatten (x):


Yield x


Else


Yield x





def count_files (Root_dir,file_filter):


Process_list = Get_process_files (root_dir,file_filter)





Process_list = List (Flatten (process_list))


Print "Flatten Process List",


Print Process_list





Line_Count = 0


For file in Process_list:


Line_Count = Line_Count + count_line (file)


Print file, "Line_number", Line_Count





#Generate Source Files in one


Line_Count = 1


target_filename=root_dir+ "" + "Result.txt"


With open (Target_filename, "w") as Target_file:


For file in Process_list:


Target_file.write ("///////" +file+ "///////n")


Line_Count = Read_lines_and_write_to_target (File,target_file,line_count)


Target_file.close ()


Print ' result was generated in target file: ', Target_filename








def get_process_files (Root_dir,file_filter):


"" Process all files in directory this matches File_filter "" "


Cur_dir = Os.path.abspath (Root_dir)


File_list = Os.listdir (Cur_dir)


Print File_list


Process_list=[]


#processing the file_list, retrieve all target files to Process_list


For file in File_list:


FullFile = cur_dir+ "" +file


Print FullFile


If Os.path.isfile (fullfile):


print ' is file '


Found_flag = False


For filter in File_filter:


If File.rfind (filter)!=-1:


Print "match!", File


Process_list.append (FullFile)


Found_flag = True


If Found_flag==false:


Print "Pass this file", FullFile


Elif Os.path.isdir (fullfile):


print ' is Dir,recursive '


Dir_extra_list = Get_process_files (fullfile,file_filter)


Print Dir_extra_list


If Len (dir_extra_list)!=0:


Process_list.append (Dir_extra_list)


Else


Print "Not defined"


Return process_list








if __name__ = = ' __main__ ':


Print SYS.ARGV


Root_dir = sys.argv[1]


Print "Info:root_dir:", Root_dir


File_filter = [". cpp", ". H"]


Count_files (Root_dir,file_filter)




Count the number of source lines in a folder Python script


Write a script that counts the number of lines of source code in a folder

Support for C + + Java python only

There is a need to be able to change the program on their own, I have to do the expansion of this script is very high

It's easy to make it support other text-language codes

or email me and I'll help you with your onezeros@yahoo.cn.

Automatically generated code for MFC should be excluded

You can use a less rigorous approach: first count the number of MFC generated engineering code

Then, when analyzing the folder, according to some characteristics of MFC files to determine whether the target folder is MFC engineering

If yes, subtract the amount of code generated

The code is as follows Copy Code
#!/usr/bin/python


#codelines. py short for files in directory


Import Sys


Import OS


Import Os.path





Class Element:


_fileamount=0#number of files


_codelines=0 #line number of files


_commandlines=0 #standalone Command lines





extension={' C ': 0, ' CPP ': 0, ' C ': 0, ' cc ': 0, ' cxx ': 0,


' H ': 0, ' hpp ': 0, ' hxx ': 0, ' java ': 1, ' py ': 2}


Language=[' C + + ', ' java ', ' py '


Statistics=[element () for X in range (0,len (language))]





#count lines in a file


def fileparser (File,ext):


Global Extension,statistics


Try


F=open (file, ' R ')


Except


Print ("Failed to open" +file)


Print ("Parsing file" +file)


#print ("extension" +str (Extension[ext))


Statistics[extension[ext]]._fileamount+=1


Try


Context=f.readlines ()


I=-1;


While I<len (context):


I+=1


Line=context[i].strip ()


If line== ':


Continue


Else


If extension[ext]==0 or ext== ' java ': #c/cpp#java


If line[0:2]== '//':


Statistics[extension[ext]]._commandlines+=1


Elif line[0:2]== '/* ':


While Line.find ('/* ') ==-1:


I+=1;


Line=context[i].strip ()


Statistics[extension[ext]]._commandlines+=1


Statistics[extension[ext]]._commandlines+=1


Else


Statistics[extension[ext]]._codelines+=1


elif ext== ' py ': #python


If line[0]== ' # ':


Statistics[extension[ext]]._commandlines+=1


Else


Statistics[extension[ext]]._codelines+=1


Except


Pass


F.close ()


Return


#find source code file by analyzing extension


def extparser (file):


Global extension


Ext=os.path.splitext (file) [1][1:]


#print ("extension" +ext)


If ext in extension:


#print ("in Extparing" +file)


Fileparser (File,ext)


Else


Pass


Return





#parse a directory to find files


def dirparser (directory):


Print ("Parsing directory" +directory)


Try


Dirlist=os.listdir (directory)


For I in Dirlist:


fullpath=directory+ '//' +i


if (Os.path.isdir (FullPath) ==true):


Dirparser (FullPath)


Else


Extparser (FullPath)


Except


Pass


Return





if __name__ = = "__main__":


if (Os.path.isdir (sys.argv[1]) ==false):


Print ('%s is not a correct path ', sys.argv[1]);


Sys.exit (0)


Dirparser (Sys.argv[1])


Length=[len (' language: '), Len (' File amount: '),


Len (' Code amount: '), Len (' Command amount ')]


Print (' Language:file amount:code amount:command amount ')


For I,lang in Enumerate (language):


Print (repr (lang). Ljust (Length[0]),


Repr (Statistics[i]._fileamount). Ljust (Length[1]),


Repr (Statistics[i]._codelines). Ljust (Length[1]),


Repr (Statistics[i]._commandlines). Ljust (length[1))





Print (' Done ')


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.