10人参与 • 2025-10-26 • Python
作为一名开发者,你是否经常需要统计项目中的代码行数?是否厌倦了使用命令行工具或者在线工具的繁琐操作?今天,我将分享如何使用pyqt5开发一款功能强大、界面美观的python代码行数统计工具。
在日常开发中,我们经常需要:
传统的解决方案往往存在以下问题:
因此,我决定开发一款集成度高、操作简便的图形化工具。
1.拖拽支持
2.智能统计
3.批量处理
4.结果展示
5.导出功能

@staticmethod
def count_lines(file_path: str) -> dict[str, int]:
"""智能统计代码行数"""
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
except exception:
return {'total': 0, 'code': 0, 'comment': 0, 'blank': 0}
total_lines = len(lines)
code_lines = 0
comment_lines = 0
blank_lines = 0
in_multiline_string = false
multiline_quote = none
for line in lines:
stripped = line.strip()
# 空行处理
if not stripped:
blank_lines += 1
continue
# 多行字符串处理
if in_multiline_string:
if multiline_quote in stripped:
quote_count = stripped.count(multiline_quote)
if quote_count % 2 == 1:
in_multiline_string = false
multiline_quote = none
comment_lines += 1
continue
# 检查多行字符串开始
if '"""' in stripped or "'''" in stripped:
# ... 处理逻辑
# 单行注释
if stripped.startswith('#'):
comment_lines += 1
continue
# 代码行
code_lines += 1
return {
'total': total_lines,
'code': code_lines,
'comment': comment_lines,
'blank': blank_lines
}
class droparea(qlabel):
"""支持拖拽的区域"""
files_dropped = pyqtsignal(list)
def __init__(self):
super().__init__()
self.setacceptdrops(true)
self.setalignment(qt.aligncenter)
# 设置样式和提示文本
def dragenterevent(self, event: qdragenterevent):
if event.mimedata().hasurls():
event.acceptproposedaction()
# 更新视觉反馈
def dropevent(self, event: qdropevent):
files = []
for url in event.mimedata().urls():
file_path = url.tolocalfile()
if os.path.exists(file_path):
files.append(file_path)
if files:
self.files_dropped.emit(files)
class counterthread(qthread):
"""后台统计线程"""
progress_updated = pyqtsignal(int, int)
file_processed = pyqtsignal(str, dict)
directory_processed = pyqtsignal(str, dict)
finished = pyqtsignal()
def run(self):
# 收集所有文件
all_files = []
for path in self.paths:
if os.path.isfile(path) and path.endswith('.py'):
all_files.append(path)
elif os.path.isdir(path):
py_files = self.counter.scan_directory(path)
all_files.extend(py_files)
# 逐个处理文件
for i, file_path in enumerate(all_files):
stats = self.counter.count_lines(file_path)
self.file_processed.emit(file_path, stats)
self.progress_updated.emit(i + 1, len(all_files))
使用css样式表打造现代化界面:
self.setstylesheet("""
qmainwindow {
background-color: #f5f5f5;
}
qpushbutton {
background-color: #0078d4;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
font-weight: bold;
}
qpushbutton:hover {
background-color: #106ebe;
}
""")
相比简单的行数统计,本工具能够:
快速了解项目规模
分析代码质量
生成项目报告
检查注释覆盖率
评估代码文档化程度
识别冗余代码
统一代码规范
制定开发计划
设定质量目标
# 1. 克隆项目 git clone [项目地址] # 2. 安装依赖 pip install pyqt5 # 3. 运行程序 python code_counter.py
难点: python的多行字符串可能跨越多行,需要正确识别开始和结束位置。
解决方案: 使用状态机模式,跟踪当前是否在多行字符串内部。
难点: python文件可能使用不同的编码格式。
解决方案: 优先使用utf-8,失败时使用errors='ignore’参数。
难点: 大型项目包含大量文件,可能导致界面卡顿。
解决方案: 使用qthread进行后台处理,通过信号更新界面。
通过这个项目,我们成功打造了一款功能完整、界面美观的代码统计工具。项目展示了:
这不仅仅是一个工具,更是一次完整的软件开发实践。希望这个项目能够为你的开发工作带来便利,也希望能够启发你创造出更多有用的工具。
以上就是python+pyqt5打造一个代码行数统计工具的详细内容,更多关于python代码行数统计的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论