PyAssimp加载模型报错:'_GeneratorContextManager'无meshes等属性
解决PyAssimp 5.2.5中
AttributeError: '_GeneratorContextManager' object has no attribute 'meshes'的问题 问题根源
pyassimp 5.x版本中,pyassimp.load接口的实现发生了变化:它不再直接返回Scene对象,而是返回一个上下文管理器(_GeneratorContextManager)。直接将该返回值赋值给scene并尝试访问meshes等属性,自然会触发AttributeError。
解决方案
使用Python的with语句来管理Scene对象的生命周期,这是pyassimp 5.x推荐的用法,既能保证正确获取Scene实例,又能自动释放资源,无需手动调用pyassimp.release()。
修正后的代码
import pyassimp import pyassimp.postprocess def main(filename=None): with pyassimp.load(filename, processing=pyassimp.postprocess.aiProcess_Triangulate) as scene: print("Meshes:" + str(len(scene.meshes)))
手动资源管理(不推荐)
如果因特殊需求必须手动控制资源,可以通过上下文管理器的__enter__()方法获取Scene实例,最后通过__exit__()或pyassimp.release()释放资源:
import pyassimp import pyassimp.postprocess def main(filename=None): scene_ctx = pyassimp.load(filename, processing=pyassimp.postprocess.aiProcess_Triangulate) scene = scene_ctx.__enter__() try: print("Meshes:" + str(len(scene.meshes))) finally: scene_ctx.__exit__(None, None, None) # 等价于 pyassimp.release(scene)
验证结果
修改代码后,加载你提供的立方体OBJ模型,会正常输出Meshes:1(单个网格的立方体模型),同时可以正常访问scene.materials、scene.textures等属性。
内容的提问来源于stack exchange,提问作者rbaleksandar
相关产品推荐
相关产品推荐

