dxfedit/01_Aspose_CAD_Python/debug_dwg_structure.py
2025-09-09 18:42:30 +08:00

254 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DWG文件结构调试脚本
功能详细分析DWG文件的内部结构找出所有可访问的属性和方法
作者AI Assistant
日期2024
"""
import os
import sys
from pathlib import Path
import aspose.cad as cad
from aspose.cad.imageoptions import CadRasterizationOptions, PngOptions
from aspose.cad import Color
def print_separator(title=""):
"""打印分隔线"""
print("=" * 60)
if title:
print(f" {title} ")
print("=" * 60)
def analyze_object_structure(obj, name="Object", max_depth=2, current_depth=0):
"""递归分析对象结构"""
if current_depth >= max_depth:
return
print(f"{' ' * current_depth}{name}: {type(obj).__name__}")
# 获取所有属性
attrs = []
methods = []
for attr_name in dir(obj):
if not attr_name.startswith('_'):
try:
attr_value = getattr(obj, attr_name)
if callable(attr_value):
methods.append(attr_name)
else:
attrs.append((attr_name, attr_value))
except:
pass
# 打印属性
if attrs:
print(f"{' ' * (current_depth + 1)}属性:")
for attr_name, attr_value in attrs[:10]: # 只显示前10个属性
try:
if hasattr(attr_value, '__len__') and not isinstance(attr_value, str):
print(f"{' ' * (current_depth + 2)}{attr_name}: {type(attr_value).__name__} (长度: {len(attr_value)})")
else:
print(f"{' ' * (current_depth + 2)}{attr_name}: {attr_value}")
except:
print(f"{' ' * (current_depth + 2)}{attr_name}: <无法访问>")
# 打印方法
if methods:
print(f"{' ' * (current_depth + 1)}方法:")
for method_name in methods[:10]: # 只显示前10个方法
print(f"{' ' * (current_depth + 2)}{method_name}()")
print()
def debug_dwg_structure(dwg_path):
"""调试DWG文件结构"""
print_separator("DWG文件结构分析")
if not os.path.exists(dwg_path):
print(f"✗ 文件不存在: {dwg_path}")
return
try:
# 获取文件基本信息
file_size = os.path.getsize(dwg_path)
print(f"文件路径: {dwg_path}")
print(f"文件大小: {file_size:,} 字节 ({file_size/1024/1024:.2f} MB)")
# 加载DWG文件
print("正在加载DWG文件...")
with cad.Image.load(dwg_path) as image:
print(f"✓ 成功加载DWG文件")
# 分析图像对象
print_separator("图像对象分析")
analyze_object_structure(image, "Image", max_depth=1)
# 尝试访问各种可能的属性
print_separator("尝试访问图像属性")
# 基本属性
basic_attrs = ['width', 'height', 'size', 'format', 'bounds']
for attr in basic_attrs:
try:
value = getattr(image, attr)
print(f"{attr}: {value}")
except Exception as e:
print(f"{attr}: {e}")
# CAD相关属性
cad_attrs = ['entities', 'blocks', 'layers', 'styles', 'dimensions', 'texts', 'lines']
for attr in cad_attrs:
try:
value = getattr(image, attr)
if value is not None:
print(f"{attr}: {type(value).__name__} (长度: {len(value) if hasattr(value, '__len__') else 'N/A'})")
# 如果是集合,分析第一个元素
if hasattr(value, '__len__') and len(value) > 0:
print(f" 第一个元素类型: {type(value[0]).__name__}")
analyze_object_structure(value[0], f"{attr}[0]", max_depth=1)
else:
print(f"{attr}: None")
except Exception as e:
print(f"{attr}: {e}")
# 尝试其他可能的属性
other_attrs = ['drawing', 'model', 'layout', 'paper_space', 'model_space']
for attr in other_attrs:
try:
value = getattr(image, attr)
if value is not None:
print(f"{attr}: {type(value).__name__}")
analyze_object_structure(value, attr, max_depth=1)
else:
print(f"{attr}: None")
except Exception as e:
print(f"{attr}: {e}")
# 尝试遍历所有属性
print_separator("所有可用属性")
all_attrs = []
for attr_name in dir(image):
if not attr_name.startswith('_'):
try:
attr_value = getattr(image, attr_name)
all_attrs.append((attr_name, type(attr_value).__name__))
except:
all_attrs.append((attr_name, "无法访问"))
# 按类型分组显示
type_groups = {}
for attr_name, attr_type in all_attrs:
if attr_type not in type_groups:
type_groups[attr_type] = []
type_groups[attr_type].append(attr_name)
for attr_type, attrs in type_groups.items():
print(f"{attr_type}: {', '.join(attrs[:5])}{'...' if len(attrs) > 5 else ''}")
# 尝试获取CAD特定信息
print_separator("CAD特定信息")
try:
# 检查是否是CAD图像
if hasattr(image, 'is_cad'):
print(f"is_cad: {image.is_cad}")
# 检查CAD版本
if hasattr(image, 'cad_version'):
print(f"cad_version: {image.cad_version}")
# 检查单位
if hasattr(image, 'units'):
print(f"units: {image.units}")
# 检查坐标系
if hasattr(image, 'coordinate_system'):
print(f"coordinate_system: {image.coordinate_system}")
except Exception as e:
print(f"获取CAD特定信息失败: {e}")
# 尝试不同的访问方法
print_separator("尝试不同的访问方法")
# 方法1尝试获取所有实体
try:
if hasattr(image, 'get_entities'):
entities = image.get_entities()
print(f"get_entities(): {type(entities).__name__} (长度: {len(entities) if hasattr(entities, '__len__') else 'N/A'})")
except Exception as e:
print(f"get_entities(): {e}")
# 方法2尝试获取所有块
try:
if hasattr(image, 'get_blocks'):
blocks = image.get_blocks()
print(f"get_blocks(): {type(blocks).__name__} (长度: {len(blocks) if hasattr(blocks, '__len__') else 'N/A'})")
except Exception as e:
print(f"get_blocks(): {e}")
# 方法3尝试获取所有图层
try:
if hasattr(image, 'get_layers'):
layers = image.get_layers()
print(f"get_layers(): {type(layers).__name__} (长度: {len(layers) if hasattr(layers, '__len__') else 'N/A'})")
except Exception as e:
print(f"get_layers(): {e}")
# 方法4尝试遍历
try:
if hasattr(image, '__iter__'):
print("图像对象可迭代,尝试遍历...")
count = 0
for item in image:
print(f" 项目 {count}: {type(item).__name__}")
count += 1
if count >= 5: # 只显示前5个
break
print(f"总共找到 {count} 个项目")
except Exception as e:
print(f"遍历图像对象失败: {e}")
except Exception as e:
print(f"✗ 调试失败: {e}")
import traceback
traceback.print_exc()
def main():
"""主函数"""
print_separator("DWG文件结构调试工具")
print("此工具将详细分析DWG文件的内部结构")
print()
# 查找DWG文件
dwg_files = list(Path('.').glob('*.dwg'))
if not dwg_files:
print("✗ 当前目录下未找到DWG文件")
print("请确保DWG文件在当前目录中")
return
print(f"找到 {len(dwg_files)} 个DWG文件:")
for i, dwg_file in enumerate(dwg_files, 1):
print(f" {i}. {dwg_file}")
# 使用第一个DWG文件进行调试
test_file = str(dwg_files[0])
print(f"\n使用文件进行调试: {test_file}")
# 调试文件结构
debug_dwg_structure(test_file)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n用户中断了程序执行")
except Exception as e:
print(f"\n\n程序执行出错: {e}")
import traceback
traceback.print_exc()