Error baking rigid bodies before rendering I'm using the following function to render my scene:

    def render_scene(self, file_name):
        bpy.data.scenes[0].render.filepath = os.path.join(self.output_path, file_name)
        bpy.ops.object.select_by_type(type='MESH')
        bpy.ops.rigidbody.bake_to_keyframes()
        bpy.ops.render.render(animation=True)


but I get the following error in bpy.ops.rigidbody.bake_to_keyframes:

  File "/snap/blender/33/2.80/scripts/modules/bpy/ops.py", line 201, in __call__
    ret = op_call(self.idname_py(), None, kw)
RuntimeError: Error: Traceback (most recent call last):
  File "/snap/blender/33/2.80/scripts/startup/bl_operators/rigidbody.py", line 174, in execute
    bpy.ops.anim.keyframe_insert(type='BUILTIN_KSI_LocRot', confirm_success=False)
  File "/snap/blender/33/2.80/scripts/modules/bpy/ops.py", line 201, in __call__
    ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.anim.keyframe_insert.poll() failed, context is incorrect


How can I solve this problem?
Another way you could do it is:

def render_scene(self, file_name):
    bpy.data.scenes[0].render.filepath = os.path.join(self.output_path, file_name)
    bpy.ops.ptcache.bake_all()
    bpy.ops.render.render(animation=True)