PCM_Report/debug_report_stuck.py

220 lines
6.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""
调试报告生成卡住问题的专用脚本
"""
import json
import sys
import os
import time
from pathlib import Path
def analyze_json_data():
"""分析JSON数据结构"""
# 你提供的实际JSON数据
json_data = {
"tables": [{
"token": "scriptTable1",
"startRow": 0,
"startCol": 0,
"cells": [
{"row": 4, "col": 0, "value": "23.2"},
{"row": 4, "col": 1, "value": "27.5"},
# ... 更多数据
{"row": 20, "col": 6, "value": "28.5"},
{"row": 1, "col": 1, "value": "2025-11-27 11:30:00"},
{"row": 1, "col": 3, "value": "2025-11-27 15:00:00"},
{"row": 0, "col": 1, "value": "16.5"}
]
}]
}
print("JSON数据分析:")
print("=" * 50)
table = json_data["tables"][0]
cells = table["cells"]
print(f"表格token: {table['token']}")
print(f"总单元格数: {len(cells)}")
# 分析行列分布
rows = set()
cols = set()
for cell in cells:
rows.add(cell["row"])
cols.add(cell["col"])
print(f"涉及行数: {len(rows)} (范围: {min(rows)} - {max(rows)})")
print(f"涉及列数: {len(cols)} (范围: {min(cols)} - {max(cols)})")
# 检查可能的问题数据
problematic_cells = []
for i, cell in enumerate(cells):
value = cell.get("value", "")
if value is None:
problematic_cells.append(f"Cell {i}: NULL value at ({cell['row']}, {cell['col']})")
elif str(value).strip() == "":
problematic_cells.append(f"Cell {i}: Empty value at ({cell['row']}, {cell['col']})")
elif len(str(value)) > 100:
problematic_cells.append(f"Cell {i}: Very long value at ({cell['row']}, {cell['col']}) - {len(str(value))} chars")
if problematic_cells:
print("\n可能有问题的单元格:")
for issue in problematic_cells[:10]: # 只显示前10个
print(f" {issue}")
else:
print("\n✓ 没有发现明显的数据问题")
return json_data
def simulate_word_processing(json_data):
"""模拟Word处理过程找出可能卡住的地方"""
print("\n模拟Word处理过程:")
print("=" * 50)
table = json_data["tables"][0]
cells = table["cells"]
# 模拟report_generator.py的处理逻辑
start_time = time.time()
# 1. 解析表格数据
print("步骤1: 解析表格数据...")
time.sleep(0.1) # 模拟处理时间
print("✓ 表格数据解析完成")
# 2. 确定表格尺寸
print("步骤2: 确定表格尺寸...")
max_row = max(cell["row"] for cell in cells)
max_col = max(cell["col"] for cell in cells)
print(f"✓ 需要的表格尺寸: {max_row + 1} 行 x {max_col + 1}")
# 3. 模拟Word COM操作
print("步骤3: 模拟Word COM操作...")
processed_count = 0
skipped_count = 0
for i, cell_info in enumerate(cells):
if i % 20 == 0: # 每20个单元格报告一次进度
print(f" 处理进度: {i}/{len(cells)} ({i/len(cells)*100:.1f}%)")
# 模拟我们的优化逻辑
value = cell_info.get("value", "")
if value is None:
skipped_count += 1
continue
text = str(value)
if text.strip() == "":
skipped_count += 1
continue
# 模拟Word写入操作这里可能是卡住的地方
row = cell_info.get("row", 0)
col = cell_info.get("col", 0)
# 检查是否是可能导致问题的单元格
if row > 50 or col > 20:
print(f" 警告: 单元格位置异常 ({row}, {col})")
if len(text) > 50:
print(f" 警告: 单元格内容过长 ({row}, {col}): {len(text)} 字符")
processed_count += 1
time.sleep(0.001) # 模拟COM操作延迟
elapsed_time = time.time() - start_time
print(f"\n处理完成:")
print(f" 处理的单元格: {processed_count}")
print(f" 跳过的单元格: {skipped_count}")
print(f" 总耗时: {elapsed_time:.2f}")
if elapsed_time > 5:
print("⚠️ 处理时间较长,可能存在性能问题")
else:
print("✓ 处理时间正常")
def check_word_environment():
"""检查Word环境"""
print("\nWord环境检查:")
print("=" * 50)
try:
import win32com.client
print("✓ win32com.client 可用")
# 尝试创建Word应用程序对象
try:
word_app = win32com.client.Dispatch("Word.Application")
print("✓ Word应用程序可以创建")
# 检查Word版本
try:
version = word_app.Version
print(f"✓ Word版本: {version}")
except:
print("⚠️ 无法获取Word版本")
# 清理
try:
word_app.Quit()
except:
pass
except Exception as e:
print(f"✗ Word应用程序创建失败: {e}")
print(" 可能的原因:")
print(" - Word未安装")
print(" - Word进程被占用")
print(" - 权限问题")
except ImportError:
print("✗ win32com.client 不可用")
print(" 需要安装: pip install pywin32")
def suggest_solutions():
"""建议解决方案"""
print("\n建议的解决方案:")
print("=" * 50)
solutions = [
"1. 检查Word模板文件是否损坏",
"2. 确保Word应用程序没有被其他进程占用",
"3. 尝试以管理员权限运行程序",
"4. 检查系统内存是否充足",
"5. 临时关闭杀毒软件",
"6. 使用任务管理器结束所有Word进程后重试",
"7. 重启计算机后重试",
"8. 检查Word插件是否冲突",
"9. 尝试使用不同的Word模板",
"10. 添加更多调试日志定位具体卡住的位置"
]
for solution in solutions:
print(f" {solution}")
def main():
print("报告生成卡住问题调试")
print("=" * 60)
# 分析JSON数据
json_data = analyze_json_data()
# 模拟Word处理
simulate_word_processing(json_data)
# 检查Word环境
check_word_environment()
# 建议解决方案
suggest_solutions()
print("\n" + "=" * 60)
print("调试完成")
if __name__ == "__main__":
main()