5
$\begingroup$

I have a script that tries to derive several blend files from the same source file. However after a while I realised that the delete() operator apparently doesn't work after reverting the file. I could nail it down to this, that can be run with the default startup scene.

import bpy

# if this line is removed, delete() behaves as expected.
bpy.ops.wm.revert_mainfile()

bpy.context.scene.objects['Cube'].select=True
bpy.ops.object.delete()

Expected result: Cube should be deleted.

Actual result: Cube is selected, but not deleted

Feature? Bug? Something I don't understand about how scripts operate when loading/reverting files?

This can be tested by copying the script in a text window and hitting 'Run Script'

EDIT: It's been suggested that I should refresh the UI to see the result. This is irrelevant to the problem. (As I did) you can confirm that nothing was deleted programmatically.

$\endgroup$
4
$\begingroup$

It is basically a timing issue: your code below revert_mainfile() is called before the scene is ready, it's simply too early.

A load_post handler alone doesn't help either, the argument passed to this callback is None.

If you register a persistent load_post handler, which sets up a scene_update_pre handler, the execution will be delayed until the scene is ready:

import bpy
from bpy.app.handlers import persistent

def scene_update_callback(scene):

    # self-removal, only run once
    bpy.app.handlers.scene_update_pre.remove(scene_update_callback)

    ob = scene.objects.get("Cube")

    if ob is not None:
        bpy.ops.object.mode_set(mode='OBJECT')
        bpy.ops.object.select_all(action='DESELECT')
        ob.select = True
        bpy.ops.object.delete()


@persistent
def load_post_callback(dummy):

    # self-removal, so it isn't called again
    bpy.app.handlers.load_post.remove(load_post_callback)

    # use a scene update handler to delay execution of code
    bpy.app.handlers.scene_update_pre.append(scene_update_callback)


if __name__ == '__main__':
    bpy.app.handlers.load_post.append(load_post_callback)
    bpy.ops.wm.revert_mainfile()
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy