利用Python统计源代码行数以及对源代码排版

近段时间写的一个软件需要做软件著作权登记,需要统计源代码行数以及提交部分源代码,刚好利用Python写了这么一个小工具。

用法如下:

在windows命令行窗口,使用python python_count_line.py source_code_root_directory即可。

其中,source_code_root_directory为需要统计的源代码的根目录,源代码目录中如果有其它子目录,也可以递归遍历。


源代码如下:

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 is generated in target file:",target_filename


def get_process_files(root_dir,file_filter):
	""" process all files in directory that 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)
	

也许以后还用得着。


REF:

http://rosettacode.org/wiki/Flatten_a_list


你可能感兴趣的:(windows,list,python,File,filter,import)