python3使用GUI统计代码量

yipeiwu_com6年前Python基础

本文实例为大家分享了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('取消了统计代码行操作')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python+matplotlib绘制饼图散点图实例代码

python+matplotlib绘制饼图散点图实例代码

本文是从matplotlib官网上摘录下来的一个实例,实现的功能是Python+matplotlib绘制自定义饼图作为散点图的标记,具体如下。 首先看下演示效果 实例代码: imp...

Python字典,函数,全局变量代码解析

字典 dict1 = {'name':'han','age':18,'class':'first'} print(dict1.keys()) #打印所有的key值 print(...

Python实现图片添加文字

在工作中有时候会给图上添加文字,常用的是PS工具,不过我想通过代码的方式来给图片添加文字。 需要使用的Python的图像库:PIL.更加详细的知识点如下: Imaga模块:用来创建,打开...

对python的输出和输出格式详解

对python的输出和输出格式详解

输出 1. 普通的输出 # 打印提示 print('hello world') 用print()在括号中加上字符串,就可以向屏幕上输出指定的文字。比如输出'hello, world...

Pytorch 计算误判率,计算准确率,计算召回率的例子

无论是官方文档还是各位大神的论文或搭建的网络很多都是计算准确率,很少有计算误判率, 下面就说说怎么计算准确率以及误判率、召回率等指标 1.计算正确率 获取每批次的预判正确个数 train...