Is it generally bad practice to load a blender file within a script? I'm running into lots of trouble when doing so. For example here I want to create fresh file, then import a fbx and then save it:
def create_empty_scene():
bpy.ops.wm.open_mainfile(filepath=r"D:\empty.blend")
def import_fbx_and_save_as_blend(fbx_filepath):
create_empty_scene()
bpy.ops.import_scene.fbx(filepath=fbx_filepath, )
This gives me an error wihin the fbx import:
File "C:\Program Files\Blender Foundation\Blender 3.1\3.1\scripts\addons\io_scene_fbx\import_fbx.py", line 2849, in _
root_helper.build_hierarchy(fbx_tmpl, settings, scene, view_layer)
File "C:\Program Files\Blender Foundation\Blender 3.1\3.1\scripts\addons\io_scene_fbx\import_fbx.py", line 2284, in build_hierarchy
child.build_hierarchy(fbx_tmpl, settings, scene, view_layer)
File "C:\Program Files\Blender Foundation\Blender 3.1\3.1\scripts\addons\io_scene_fbx\import_fbx.py", line 2244, in build_hierarchy
bpy.ops.object.mode_set(mode='EDIT')
File "C:\Program Files\Blender Foundation\Blender 3.1\3.1\scripts\modules\bpy\ops.py", line 132, in __call__
ret = _op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.object.mode_set.poll() Context missing active object
Something even simpler does also not work:
bpy.ops.wm.open_mainfile(filepath=r"D:\cube.blend")
cube = bpy.context.scene.objects["Cube"]
cube.select_set(True)
print(bpy.context.selected_objects)
This results in an error regarding the context:
AttributeError: 'Context' object has no attribute 'selected_objects'
all these scripts work completely fine when no scene is loaded before. I have the same happening when running this code via an operator or not.
In pipeline scripts I'm used to just load a file or refresh a scene etc. Is this a no-go in Blender or am I maybe missing something? I have noticed that appending files is working.
I'm fairly new to Blender scripting so excuse this trivial question.
bpy.opsare for interactive use through the UI and should be avoided in scripts because they depend on context. Using them through scripts may yield unexpected results at best, or fail entirely at worst. Manipulate data directly frombpy.datainstead. – Duarte Farrajota Ramos Jun 01 '22 at 10:01open_mainfileresults in a fresh start, so your call toimport_scene.fbxwill never be invoked. – Marty Fouts Jun 01 '22 at 15:15