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

402 lines
15 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 -*-
"""
Aspose.CAD 真正问题调试脚本
功能深入分析Aspose.CAD无法提取线条的真正原因
作者AI Assistant
日期2024
"""
import os
import sys
import traceback
from pathlib import Path
def print_separator(title=""):
"""打印分隔线"""
print("=" * 60)
if title:
print(f" {title} ")
print("=" * 60)
def debug_image_object():
"""深入调试Image对象"""
print_separator("深入调试Image对象")
try:
import aspose.cad as cad
# 查找DWG文件
dwg_files = list(Path('.').glob('*.dwg'))
if not dwg_files:
print("✗ 未找到DWG文件")
return
test_file = str(dwg_files[0])
print(f"使用文件: {test_file}")
# 加载DWG文件
with cad.Image.load(test_file) as image:
print(f"成功加载DWG文件")
print(f"图像类型: {type(image).__name__}")
print(f"图像尺寸: {image.width} x {image.height}")
# 检查Image对象的所有属性
print(f"\nImage对象的所有属性:")
all_attrs = [attr for attr in dir(image) if not attr.startswith('_')]
for attr in all_attrs:
try:
value = getattr(image, attr)
if callable(value):
print(f" 方法: {attr}()")
else:
print(f" 属性: {attr} = {value}")
except Exception as e:
print(f" 属性: {attr} (访问失败: {e})")
# 尝试不同的访问方式
print(f"\n尝试不同的访问方式:")
# 方法1检查是否有CAD特定的属性
cad_attrs = ['cad_image', 'cad_drawing', 'drawing', 'model', 'layout']
for attr in cad_attrs:
try:
if hasattr(image, attr):
value = getattr(image, attr)
print(f"{attr}: {type(value).__name__}")
if hasattr(value, '__len__'):
print(f" 长度: {len(value)}")
else:
print(f"{attr}: 不存在")
except Exception as e:
print(f"{attr}: 访问失败 - {e}")
# 方法2尝试转换为其他类型
print(f"\n尝试类型转换:")
try:
# 检查是否有as_cad_image方法
if hasattr(image, 'as_cad_image'):
cad_image = image.as_cad_image()
print(f" ✓ as_cad_image(): {type(cad_image).__name__}")
else:
print(f" ✗ as_cad_image(): 不存在")
except Exception as e:
print(f" ✗ as_cad_image(): 失败 - {e}")
# 方法3检查是否有get_entities方法
try:
if hasattr(image, 'get_entities'):
entities = image.get_entities()
print(f" ✓ get_entities(): {type(entities).__name__}")
if hasattr(entities, '__len__'):
print(f" 实体数量: {len(entities)}")
else:
print(f" ✗ get_entities(): 不存在")
except Exception as e:
print(f" ✗ get_entities(): 失败 - {e}")
# 方法4检查是否有get_blocks方法
try:
if hasattr(image, 'get_blocks'):
blocks = image.get_blocks()
print(f" ✓ get_blocks(): {type(blocks).__name__}")
if hasattr(blocks, '__len__'):
print(f" 块数量: {len(blocks)}")
else:
print(f" ✗ get_blocks(): 不存在")
except Exception as e:
print(f" ✗ get_blocks(): 失败 - {e}")
# 方法5检查是否有get_layers方法
try:
if hasattr(image, 'get_layers'):
layers = image.get_layers()
print(f" ✓ get_layers(): {type(layers).__name__}")
if hasattr(layers, '__len__'):
print(f" 图层数量: {len(layers)}")
else:
print(f" ✗ get_layers(): 不存在")
except Exception as e:
print(f" ✗ get_layers(): 失败 - {e}")
# 方法6尝试遍历图像对象
try:
if hasattr(image, '__iter__'):
print(f" ✓ 图像对象可迭代")
count = 0
for item in image:
print(f" 项目 {count}: {type(item).__name__}")
count += 1
if count >= 5:
break
print(f" 总共找到 {count} 个项目")
else:
print(f" ✗ 图像对象不可迭代")
except Exception as e:
print(f" ✗ 遍历图像对象失败: {e}")
except Exception as e:
print(f"✗ 调试Image对象失败: {e}")
traceback.print_exc()
def check_cad_specific_classes():
"""检查CAD特定类"""
print_separator("检查CAD特定类")
try:
import aspose.cad as cad
# 尝试导入CAD特定的类
cad_classes = [
'CadImage',
'CadDrawing',
'CadDocument',
'CadFile',
'CadEntity',
'CadLine',
'CadPolyline',
'CadBlock',
'CadLayer'
]
for class_name in cad_classes:
try:
# 尝试从不同模块导入
modules_to_try = [
'aspose.cad',
'aspose.cad.fileformats',
'aspose.cad.fileformats.cad',
'aspose.cad.fileformats.cad.cadobjects',
'aspose.cad.fileformats.cad.cadobjects.cadentities'
]
imported = False
for module_name in modules_to_try:
try:
module = __import__(module_name, fromlist=[class_name])
if hasattr(module, class_name):
cls = getattr(module, class_name)
print(f"{class_name}: 从 {module_name} 导入成功")
print(f" 类型: {type(cls).__name__}")
imported = True
break
except ImportError:
continue
except Exception as e:
print(f" ✗ 导入失败: {e}")
continue
if not imported:
print(f"{class_name}: 无法导入")
except Exception as e:
print(f"{class_name}: 检查失败 - {e}")
except Exception as e:
print(f"✗ 检查CAD特定类失败: {e}")
def test_direct_cad_loading():
"""测试直接加载CAD文件"""
print_separator("测试直接加载CAD文件")
try:
# 查找DWG文件
dwg_files = list(Path('.').glob('*.dwg'))
if not dwg_files:
print("✗ 未找到DWG文件")
return
test_file = str(dwg_files[0])
print(f"使用文件: {test_file}")
# 方法1尝试使用CadImage.load
try:
from aspose.cad.fileformats.cad import CadImage
print("✓ 成功导入CadImage")
cad_image = CadImage.load(test_file)
print(f"✓ 成功使用CadImage.load加载文件")
print(f" 类型: {type(cad_image).__name__}")
# 检查CadImage的属性
print(f"\nCadImage对象属性:")
cad_attrs = [attr for attr in dir(cad_image) if not attr.startswith('_')]
for attr in cad_attrs[:10]: # 只显示前10个
try:
value = getattr(cad_image, attr)
if callable(value):
print(f" 方法: {attr}()")
else:
print(f" 属性: {attr} = {value}")
except Exception as e:
print(f" 属性: {attr} (访问失败: {e})")
# 尝试获取实体
if hasattr(cad_image, 'entities'):
entities = cad_image.entities
print(f"\n✓ 找到entities: {type(entities).__name__}")
if hasattr(entities, '__len__'):
print(f" 实体数量: {len(entities)}")
# 显示前几个实体
for i, entity in enumerate(entities[:5]):
print(f" 实体 {i}: {type(entity).__name__}")
if hasattr(entity, 'entity_type'):
print(f" 类型: {entity.entity_type}")
# 尝试获取块
if hasattr(cad_image, 'blocks'):
blocks = cad_image.blocks
print(f"\n✓ 找到blocks: {type(blocks).__name__}")
if hasattr(blocks, '__len__'):
print(f" 块数量: {len(blocks)}")
# 显示前几个块
for i, block in enumerate(blocks[:3]):
print(f"{i}: {type(block).__name__}")
if hasattr(block, 'entities'):
block_entities = block.entities
if hasattr(block_entities, '__len__'):
print(f" 块中实体数量: {len(block_entities)}")
# 尝试获取图层
if hasattr(cad_image, 'layers'):
layers = cad_image.layers
print(f"\n✓ 找到layers: {type(layers).__name__}")
if hasattr(layers, '__len__'):
print(f" 图层数量: {len(layers)}")
# 显示前几个图层
for i, layer in enumerate(layers[:3]):
print(f" 图层 {i}: {type(layer).__name__}")
if hasattr(layer, 'name'):
print(f" 名称: {layer.name}")
if hasattr(layer, 'entities'):
layer_entities = layer.entities
if hasattr(layer_entities, '__len__'):
print(f" 图层中实体数量: {len(layer_entities)}")
except ImportError as e:
print(f"✗ 无法导入CadImage: {e}")
except Exception as e:
print(f"✗ 使用CadImage.load失败: {e}")
traceback.print_exc()
# 方法2尝试使用其他加载方式
try:
import aspose.cad as cad
# 尝试使用Image.load然后转换
with cad.Image.load(test_file) as image:
print(f"\n✓ 使用Image.load加载成功")
print(f" 类型: {type(image).__name__}")
# 检查是否有转换方法
convert_methods = ['to_cad_image', 'as_cad_image', 'get_cad_image']
for method in convert_methods:
if hasattr(image, method):
try:
cad_image = getattr(image, method)()
print(f"{method}(): {type(cad_image).__name__}")
except Exception as e:
print(f"{method}(): 失败 - {e}")
else:
print(f"{method}(): 不存在")
except Exception as e:
print(f"✗ 使用Image.load失败: {e}")
except Exception as e:
print(f"✗ 测试直接加载CAD文件失败: {e}")
def check_file_format():
"""检查文件格式"""
print_separator("检查文件格式")
try:
import aspose.cad as cad
# 查找DWG文件
dwg_files = list(Path('.').glob('*.dwg'))
if not dwg_files:
print("✗ 未找到DWG文件")
return
test_file = str(dwg_files[0])
print(f"使用文件: {test_file}")
# 检查文件格式
try:
file_format = cad.Image.get_file_format(test_file)
print(f"✓ 文件格式: {file_format}")
except Exception as e:
print(f"✗ 获取文件格式失败: {e}")
# 检查文件是否可以被加载
try:
can_load = cad.Image.can_load(test_file)
print(f"✓ 可以加载: {can_load}")
except Exception as e:
print(f"✗ 检查是否可以加载失败: {e}")
# 检查文件大小和内容
file_size = os.path.getsize(test_file)
print(f"✓ 文件大小: {file_size:,} 字节 ({file_size/1024/1024:.2f} MB)")
# 读取文件头部信息
try:
with open(test_file, 'rb') as f:
header = f.read(16)
print(f"✓ 文件头部: {header.hex()}")
# 检查DWG文件签名
if header.startswith(b'AC10') or header.startswith(b'AC10'):
print(f"✓ 检测到DWG文件签名")
else:
print(f"⚠ 未检测到标准DWG文件签名")
except Exception as e:
print(f"✗ 读取文件头部失败: {e}")
except Exception as e:
print(f"检查文件格式失败: {e}")
def main():
"""主函数"""
print_separator("Aspose.CAD 真正问题调试工具")
print("深入分析Aspose.CAD无法提取线条的真正原因")
print()
# 检查文件格式
check_file_format()
# 深入调试Image对象
debug_image_object()
# 检查CAD特定类
check_cad_specific_classes()
# 测试直接加载CAD文件
test_direct_cad_loading()
# 总结
print_separator("调试总结")
print("基于以上调试结果,可能的原因包括:")
print("1. 文件格式问题 - DWG文件可能损坏或格式不标准")
print("2. API使用方式问题 - 需要使用正确的CAD特定API")
print("3. 文件内容问题 - DWG文件可能不包含线条实体")
print("4. 版本兼容性问题 - Aspose.CAD版本与文件版本不兼容")
print("\n建议:")
print("- 尝试使用其他DWG文件进行测试")
print("- 使用AutoCAD等软件验证DWG文件内容")
print("- 尝试将DWG文件转换为DXF格式")
print("- 联系Aspose技术支持获取帮助")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n用户中断了程序执行")
except Exception as e:
print(f"\n\n程序执行出错: {e}")
traceback.print_exc()