I'm new on Blender and I'm struggling with Blender's import operator for STL files. In my code, I try to load a file from the browser and then make some actions on the loaded object. I can get the file I want but the code continues to run before the STL file is loaded, so I get the error: KeyError: 'bpy_prop_collection[key]: key "file_name" not found'
Here's my code:
import bpy
from bpy_extras.io_utils import ImportHelper
from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator
#clearing previous objects
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
#stl file loading
bpy.ops.import_test.some_data('INVOKE_DEFAULT')
#some action with the file
x_dimension = bpy.data.objects["file_object"].dimensions[0]
Using :
class ImportSomeData(Operator, ImportHelper):
"""This appears in the tooltip of the operator and in the generated docs"""
bl_idname = "import_test.some_data"
bl_label = "Import Some Stl File"
bl_options = {'REGISTER', 'UNDO'}
# ImportHelper mixin class uses this
filename_ext = ".stl"
filter_glob: bpy.props.StringProperty(
default="*.stl",
options={'HIDDEN'})
def execute(self, context):
if self.filepath:
bpy.ops.import_mesh.stl(filepath=self.filepath)
# Print the imported object reference
print ("Imported object:", context.object)
# Create a material
mat = bpy.data.materials.new(name="STLMaterial")
# Append the material to the last slot
context.object.data.materials.append(mat)
return {'FINISHED'}
# Only needed if you want to add into a dynamic menu
def menu_func_import(self, context):
self.layout.operator(ImportSomeData.bl_idname, text="Text Import Operator")
def register():
bpy.utils.register_class(ImportSomeData)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
def unregister():
bpy.utils.unregister_class(ImportSomeData)
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
if __name__ == "__main__":
register()
Found on How to import a STL file using the file browser?.
Is there a way to stop the code until the STL file has loaded?
Thanks!