# Bake script works individually, but crashes in loop

I am trying to write a script to bake all of my physics in the correct order. The commands work if I issue them to each cache individually, but if I try to bake them all in a loop, I get a Error: EXCEPTION_ACCESS_VIOLATION

The script is as follows: import

 bpy
from bpy import data as D, context as C

for objName in ('StickManDefender', 'Blood1', 'Blood2'):
obj = D.objects[objName]
print(obj.name)
for mod in obj.modifiers:
if mod.type == 'DYNAMIC_PAINT':
ctx = C.copy()
for surf in mod.canvas_settings.canvas_surfaces:
print(surf.surface_format)
if surf.surface_format == 'IMAGE':
ctx['object'] = obj
bpy.ops.dpaint.bake(ctx)
break
elif surf.surface_format == 'VERTEX':
ctx['active_object'] = obj
ctx['object'] = obj
ctx['point_cache'] = surf.point_cache
print('Free Bake')
bpy.ops.ptcache.free_bake(ctx)
print('Bake')
bpy.ops.ptcache.bake(ctx, bake=True)


The output is:

StickManDefender
IMAGE
Blood1
VERTEX
Free Bake
Bake
DynamicPaint: Preparing UV surface of 256x256 pixels and 16576 tris.
Error: EXCEPTION_ACCESS_VIOLATION


If I limit the run of the script to only 1 of the objects, no problems. As soon as I try to bake multiple in a loop, crash. I've tried using concurrent.futures.ThreadPoolExecutor to run each iteration on a separate thread and wait for the result before continuing the loop and I've tried running the whole thing on another thread, but no dice. I've also tried calling C.scene.update() between iterations, but that doesn't help either. Is there something else I need to do to make this work?

• As an aside, I've worked around this by putting a numeric property on an object as an iteration counter and running the script multiple times. I'd prefer a single run. Oct 28 '19 at 23:50