1

Here's a simple code that works fine as far as the .blend file with the object I'm modifying is already open.

obj = bpy.data.objects['obj']
obj = C.scene.objects.active
obj.select = True
bpy.ops.rigidbody.object_add()
obj.rigid_body.type = 'PASSIVE'

However, if I add a line at the beginning of my code to open the file using python,

bpy.ops.wm.open_mainfile(filepath=task_path+ str(x) +".blend")

I get the following error: RuntimeError: Operator bpy.ops.rigidbody.object_add.poll() failed, context is incorrect

I'm sorry to ask the same (or similar) question twice, but believe me, I've been working on this problem for weeks, read everything online about the "context is incorrect" error and unsuccessfully tried multiple things to solve it. Nothing works and the problem seems to be related to opening the file using python (bpy.ops.wm.open_mainfile). Any clue about what's happening? Thanks a lot for your help!!

ANB
  • 21
  • 3
  • 1
    Related https://blender.stackexchange.com/questions/42956/python-operator-context-is-incorrect and https://blender.stackexchange.com/questions/14948/opening-a-blender-file-during-python-script-execution-without-changing-context and https://blender.stackexchange.com/questions/95072/execute-script-with-gui-context-object-has-no-attribute-active-object – batFINGER Jul 15 '19 at 15:43
  • Thanks @batFINGER I understand the problem now, I think. I'm trying to use a persistent handler but I'm not quite sure how. Any help appreciated. Thanks – ANB Jul 15 '19 at 18:54

1 Answers1

1

Just in case this is useful for somebody in the future, here's what seems to work for me:

import bpy
from bpy.app.handlers import persistent  

@persistent
def load_handler(dummy):
  obj = bpy.data.objects['obj']
  obj = C.scene.objects.active
  obj.select = True
  bpy.ops.rigidbody.object_add()
  obj.rigid_body.type = 'PASSIVE'

bpy.app.handlers.load_post.append(load_handler)
bpy.ops.wm.open_mainfile(filepath=task_path+ str(x) +".blend")
ANB
  • 21
  • 3