1. 程式人生 > 程式設計 >Python實現程式碼統計工具

Python實現程式碼統計工具

本文例項為大家分享了Python實現程式碼統計工具的具體程式碼,供大家參考,具體內容如下

思路:首先獲取所有檔案,然後統計每個檔案中程式碼的行數,最後將行數相加.

實現的功能:

統計每個檔案的行數;

統計總行數;

支援指定統計檔案型別,排除不想統計的檔案型別;

排除空行;

排除註釋行

import os
import sys
import os.path
#for i in sys.argv:
# print (i)

# 判斷單個檔案的程式碼行數
def count_file_lines(file_path):
 line_count = 0
 flag=True
 try:
  fp = open(file_path,"r",encoding="utf-8")
  encoding_type="utf-8"
  fp.close()
 except:
  encoding_type="gbk"
 with open(file_path,encoding=encoding_type) as fp:
  for line in fp:
  #print (line_count)
   if line.strip()=="":
    continue
   else:
    if line.strip().endswith("'''") and flag == False:
     flag=True
     continue
    if line.strip().endswith('"""') and flag == False:
     flag=True
     continue
    if flag == False:
     continue
    if line.strip().startswith("#encoding") or line.strip().startswith("#-*-"):
     line_count += 1
    #elif line.strip().startswith('"""') and line.strip().endswith('"""') and line.strip()!='"""':
  #continue
    #elif line.strip().startswith("'''") and line.strip().endswith("'''") and line.strip()!="'''":
  #continue
    elif line.strip().startswith('#'):
     continue
    elif line.strip().startswith("'''") and flag == True:
     flag = False
     continue
    elif line.strip().startswith('"""') and flag == True:
     flag = False
     continue
    else:
     line_count += 1
 return line_count

def count_code_lines(path,file_types=[]):
 # 判斷路徑是否存在
 if not os.path.exists(path):
  print("您輸入的目錄或檔案路徑不存在")
  return 0

 line_count=0 #程式碼行總數
 file_lines_dict={} #每個檔案程式碼行數

 # 判斷是否為檔案
 if os.path.isfile(path):
  file_type = os.path.splitext(path)[1][1:] #取到檔案字尾名

 # 判斷檔案型別是否滿足條件
 if len(file_types)==0:
  file_types=["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"]
 if file_type in file_types:
  line_count = count_file_lines(path)
  return line_count
 else:
  file_path = []
  for root,dirs,files in os.walk(path):
   for file in files:
    file_path.append(os.path.join(root,file))
    for f in file_path:
     file_type = os.path.splitext(f)[1][1:]
     if len(file_types)==0:
      file_types=

["py","sh"]
     if file_type not in file_types:
      continue
      line_num = count_file_lines(f)
      line_count += line_num
      file_lines_dict[f] = line_num
    return line_count,file_lines_dict
 

if __name__=="__main__":
 print (sys.argv)
 if len(sys.argv) < 2:
  print ("請輸入待統計行數的程式碼絕對路徑!")
  sys.exit()
 count_path = sys.argv[1]
 file_types = []
 if len(sys.argv) >2:
  for i in sys.argv[2:]:
   file_types.append(i)

#print(count_path,file_types)
print(count_code_lines(count_path,file_types))
#print(count_file_lines("b.py"))

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。