python实现代码统计程序


Posted in Python onSeptember 19, 2019

本文实例为大家分享了python实现代码统计程序的具体代码,供大家参考,具体内容如下

# encoding="utf-8"

"""
统计代码行数
"""

import sys
import os

def count_file_line(path):
 """统计文件的有效行数"""
 countLine = 0
 # 设置一个标志位,当遇到以"""或者'''开头或者结尾的时候,置为False
 flag = True

 # 使用utf-8格式的编码方式读取文件,如果读取失败,将使用gbk编码方式读取文件
 try:
 fp = open(path, "r", encoding="utf-8")
 encoding_type = "utf-8"
 fp.close()
 except:
 encoding_type = "gbk"

 with open(path, "r", encoding=encoding_type) as fp:
 for line in fp:
  # 空行不统计
  if line.strip():
  line = line.strip()
  # 注意下面的这两个elif必须要前面,这样子当('"""')结束之后及时将flag置为True
  if line.endswith('"""') and flag == False:
   flag = True
   continue
  if line.endswith("'''") and flag == False:
   flag = True
   continue
  if flag == False:
   continue
  if line.startswith("#!") or line.startswith("#-*-") or line.startswith("# encoding"):
   countLine += 1
  # 如果以“#”号开头的,不统计
  elif line.startswith("#"):
   continue
  # 如果同时以("'''")或者('"""')开头或者结尾(比如:"""aaa"""),那么不统计
  elif line.startswith('"""') and line.endswith('"""') and line != '"""':
   continue
  elif line.startswith("'''") and line.endswith("'''") and line != "'''":
   continue
  # 如果以("'''")或者('"""')开头或者结尾(比如:aaa"""或者"""bbb),那么不统计
  # 注意下面的这两个elif必须要放后面
  elif line.startswith('"""') and flag == True:
   flag = False
   continue
  elif line.startswith("'''") and flag == True:
   flag = False
   continue
  else:
   countLine += 1
 return countLine

def count_codes(path,file_types=[]):
 """统计所有文件代码行"""
 # 判断path是目录还是文件,如果是目录的话,遍历目录下所有的文件
 if not os.path.exists(path):
 print("您输入的路径不存在!")
 return 0
 countTotalLine = 0
 file_paths = {}
 if os.path.isdir(path):
 for root,dirs,files in os.walk(path):
  for name in files:
  if not file_types:
   file_types = ["txt","py"]
   # print(file_types)
  if os.path.splitext(name)[1][1:] in file_types:
   file_path = os.path.normpath(os.path.join(root,name))
   # print(file_path)
   file_lines = count_file_line(file_path)
   countTotalLine += file_lines
   file_paths[file_path] = file_lines
 else:
 if not file_types:
  file_types = ["txt","py"]
 if os.path.splitext(path)[1][1:] in file_types:
  countTotalLine = count_file_line(path)
  file_paths[path] = count_file_line(path)

 return countTotalLine,file_paths


if __name__ == "__main__":
 # 打印出命令行输入的参数
 # print(sys.argv)
 if len(sys.argv) < 2:
 print("请输入路径!")
 sys.exit()
 path = sys.argv[1]
 # print(path)
 file_types = sys.argv[2:]
 # print(file_types)
 print(count_codes(path,file_types))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python Web开发模板引擎优缺点总结
May 06 Python
Python引用(import)文件夹下的py文件的方法
Aug 26 Python
使用Python3编写抓取网页和只抓网页图片的脚本
Aug 20 Python
Python爬虫_城市公交、地铁站点和线路数据采集实例
Jan 10 Python
win10 64bit下python NLTK安装教程
Sep 19 Python
python网络编程之多线程同时接受和发送
Sep 03 Python
pytorch 实现打印模型的参数值
Dec 30 Python
python图形开发GUI库pyqt5的详细使用方法及各控件的属性与方法
Feb 14 Python
vue学习笔记之动态组件和v-once指令简单示例
Feb 29 Python
python学习将数据写入文件并保存方法
Jun 07 Python
使用Dajngo 通过代码添加xadmin用户和权限(组)
Jul 03 Python
python线程池 ThreadPoolExecutor 的用法示例
Oct 10 Python
python tkinter图形界面代码统计工具(更新)
Sep 18 #Python
python3获取url文件大小示例代码
Sep 18 #Python
弄懂这56个Python使用技巧(轻松掌握Python高效开发)
Sep 18 #Python
python3使用GUI统计代码量
Sep 18 #Python
django中的图片验证码功能
Sep 18 #Python
python tkinter图形界面代码统计工具
Sep 18 #Python
Python自动生成代码 使用tkinter图形化操作并生成代码框架
Sep 18 #Python
You might like
php mssql 时间格式问题
2009/01/13 PHP
常见的PHP五种设计模式小结
2011/03/23 PHP
jQuery EasyUI API 中文文档 - DateBox日期框
2011/10/15 PHP
php实现的统计字数函数定义与使用示例
2017/07/26 PHP
详解PHP实现支付宝小程序用户授权的工具类
2018/12/25 PHP
基于PHP实现邮箱验证激活过程详解
2020/10/28 PHP
Some tips of wmi scripting in jscript (1)
2007/04/03 Javascript
ExtJS DOM元素操作经验分享
2013/08/28 Javascript
javascript控制Div层透明属性由浅变深由深变浅逐渐显示
2013/11/12 Javascript
jquery实现Li滚动时滚动条自动添加样式的方法
2015/08/10 Javascript
Web程序员必备的7个JavaScript函数
2016/06/14 Javascript
javascript 解决浏览器不支持的问题
2016/09/24 Javascript
typescript编写微信小程序创建项目的方法
2021/01/29 Javascript
three.js如何实现3D动态文字效果
2021/03/03 Javascript
[07:03]显微镜下的DOTA2第九期——430圣堂刺客杀戮秀
2014/06/20 DOTA
浅谈Python数据类型之间的转换
2016/06/08 Python
pycharm中连接mysql数据库的步骤详解
2017/05/02 Python
详解Python计算机视觉 图像扭曲(仿射扭曲)
2019/03/27 Python
Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str
2019/08/07 Python
python TK库简单应用(实时显示子进程输出)
2019/10/29 Python
Python中xml和dict格式转换的示例代码
2019/11/07 Python
关于Theano和Tensorflow多GPU使用问题
2020/06/19 Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
2020/07/14 Python
HTML5 input新增type属性color颜色拾取器的实例代码
2018/08/27 HTML / CSS
一些网络技术方面的面试题
2014/05/01 面试题
应届毕业生自我鉴定范文
2013/12/27 职场文书
拉歌口号大全
2014/06/13 职场文书
信访稳定工作汇报
2014/10/27 职场文书
2014年电话客服工作总结
2014/12/09 职场文书
护士实习自荐信
2015/03/06 职场文书
排球赛新闻稿
2015/07/17 职场文书
工作简报怎么写
2015/07/21 职场文书
交通事故责任认定书
2015/08/06 职场文书
应用最多的公文《通知》如何写?
2019/04/02 职场文书
js实现上传图片到服务器
2021/04/11 Javascript
5个实用的JavaScript新特性
2022/06/16 Javascript