1. 程式人生 > 程式設計 >python3使用GUI統計程式碼量

python3使用GUI統計程式碼量

本文例項為大家分享了python3使用GUI統計程式碼量的具體程式碼,供大家參考,具體內容如下

# coding=utf-8
'''
選擇一個路徑
遍歷路徑下的每一個檔案,統計程式碼量
字典儲存 每一種型別檔案的程式碼行數,eg: *.py -> 行數
全域性變數 總行數

需要注意的是,這裡僅僅能開啟utf-8編碼的檔案,其他型別的檔案無法開啟,會出現解碼錯誤
解決方法:使用try-except語句,遇到解碼錯誤就跳過,即 except UnicodeDecodeError:
'''
import easygui as g
import sys
import os

# 全域性變數 總行數
total_line_num = 0
# 字典儲存 每一種型別檔案的程式碼行數,eg: *.py -> 行數
code_file_dict = {}


def func1(file_path):
  if os.path.isdir(file_path):
    file_list = os.listdir(file_path) # 列出當前路徑下的全部內容
    for each in file_list:
      path_plus = file_path + os.sep + each
      if os.path.isdir(path_plus):
        if os.path.basename(path_plus) in [
            'venv','.idea']: # 如果目錄為venv或者.idea,則跳過,不統計
          pass
        else:
          func1(path_plus)
      elif os.path.isfile(path_plus):
        try:
          with open(path_plus,'r') as f:
            # 每個檔案的程式碼行數
            line_num = 0
            for eachline in f:
              global total_line_num # 宣告全域性變數
              total_line_num += 1
              line_num += 1
            '''
            將each分割出字尾名,儲存在字典中
            '''
            (temp_path,temp_name) = os.path.basename(each).split('.')
            temp = '.' + temp_name
            global code_file_dict
            if temp not in code_file_dict:
              code_file_dict[temp] = line_num
            else:
              code_file_dict[temp] += line_num
        except UnicodeDecodeError:
          pass
  else:
    g.msgbox('該路徑只是一個檔案','提示')
    sys.exit(0)


if __name__ == '__main__':
  try:
    dir = g.diropenbox('請選擇的你的程式碼庫','瀏覽資料夾',default='.')
    func1(dir)
    print(code_file_dict)
    g.textbox(
      '總行數為:{}\n已經完成了{}%\n離十萬行程式碼還差{}行'.format(
        total_line_num,(total_line_num / 100000) * 100,100000 - total_line_num),title='統計結果',text=[
        '{a}型別的程式碼有{b}行\n'.format(a=k,b=v) for k,v in code_file_dict.items()],codebox=1)
  except TypeError as reason:
    g.msgbox('取消了統計程式碼行操作')

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