Using bpy.ops.wm.open_mainfile when running scripts in background

Hi, all.

I’m trying to write a script that will open blend file, cut out some faces and save it as different blend file, in a loop several times. Basically I need to break my model into several pieces and save them all in different files. However I’m seeing a weird behavior when using bpy.ops.wm.open_mainfile.

def cutFaces(ppath, pfile, fields):

    for id in fields:
        faces = fields[id]
        # Open file
        bpy.ops.wm.open_mainfile(filepath = ppath + '\\' + pfile)
        obj =[0]
        # Switch to edit mode
        bpy.ops.object.mode_set(mode = 'EDIT')
        # Select all the faces except for faces in the list
        mesh = bmesh.from_edit_mesh(
        for face in mesh.faces:
   = face.index in faces
        del mesh

        bpy.ops.wm.save_mainfile(filepath = ppath + 'fields' + id + '.blend')

I then create a .py file with following code to call the function

import bpy
import finalization
finalization.cutFaces(r'D:\Work', 'data.blend', {1: [1,2,3,4,5,6,7,8]})

Then I run blender in background and executing the script

c:\Program Files\Blender Foundation\Blender>blender.exe -b -P "D:\Work\"

And getting this:

  File "c:\Program Files\Blender Foundation\Blender\2.76\scripts\modules\bpy\", line 189, in __call__
    ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.object.mode_set.poll() failed, context is incorrect

Now when I remove bpy.ops.wm.open_mainfile from the script and open the file in blender via command line, it works fine.

c:\Program Files\Blender Foundation\Blender>blender.exe "D:\work\data.blend" -b -P "D:\Work\"

What am I missing?

Thanks in advance.


I was running it foreground to see if it’s working, and it seems when you run it in foreground, context is getting None after a call to bpy.ops.wm.open_mainfile. Surprisingly, when running in background, this works perfectly.

Not sure what’s the difference, and it kinda solves my problem, but still interesting why it doesn’t work in foreground, is it a bug?

Sorry to bump this thread, but how do you run bpy.ops.wm.open_mainfile in the background? I do not see any background flag for it?

The different could be that when run in background the script might wait it to finish loading the scene which is what I am trying to get at here.

I run entire blender in background. Not sure how it is now, the version of blender I ran way old, but I did it by running blender.exe [.blend file] -b -p [script file]. This command opens your blender file and runs the script and -b flag does it in background.

1 Like