Is there any way to export the last frame of a physics simulation from command line? I have a basic rigid body physics sim, but I want to export the last frame of the simulation. So far I have tried setting the "current frame to the last frame of the simulation and exporting it that way, but that doesn't work.

#Select all objects other than the suitcase
bpy.ops.object.select_all(action='SELECT')
bpy.data.objects['Suitcase'].select = False

# store the location of current 3d cursor
saved_location = bpy.context.scene.cursor_location.copy()  # returns a copy of the vector

# give 3dcursor new coordinates
bpy.context.scene.cursor_location = (0.0,0.0,0.0)

# set the origin on the current object to the 3dcursor location
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_VOLUME')

# Randomly place objects in the air    
bpy.ops.object.randomize_transform(random_seed= randint(1,9000), use_delta=False, use_loc=True, loc=(12.0, 8.0, 0.0), use_rot=True, rot=(360.0, 360.0, 360.0), use_scale=False, scale_even=False, scale=(1.0, 1.0, 1.0))
bpy.ops.object.select_all(action='SELECT')

#Runs physics simulation
bpy.context.scene.frame_set(1)
bpy.context.scene.frame_current += 1
bpy.context.scene.update()
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.visual_transform_apply()

# Define Directory
dir = bpy.path.abspath('//stlexport/')

# Create Directory (If Necessary)
if not os.path.exists(dir): os.makedirs(dir)

# Export STLs
bpy.ops.export_mesh.stl(filepath = dir, batch_mode = 'OBJECT')
Bake the point cache

Using same method as with particles here CLI How to render last frame of hair dynamics sym?

Replace "runs physics simulation" with a bake operator below. Not sure if playing, or frame setting, and baking happen in bg mode as they do when using GUI.

rbw.py

import bpy
context = bpy.context

scene = context.scene
rbw = scene.rigidbody_world
pc = rbw.point_cache

# match bake to animation
print(pc.frame_start, pc.frame_end)


bpy.ops.ptcache.bake({"point_cache": pc}, bake=True)

scene.frame_set(250)
bpy.ops.export_scene.obj(filepath="test.obj")


Testing in CLI with

blender -b xxx.blend -P rbw.py


can confirm  test.obj is a result of simple physics sim at 250.