Script throws error only when run from command line

I have a script that copies an animation from one armature to another. I found it on StackOverflow (https://blender.stackexchange.com/a/75450/114821). This script runs perfectly in GUI mode. It is not particular about the state of the interface; that is, it selects the correct objects and modes so that the operators have the correct context.

However, when I run this script in headless mode it fails:

Traceback (most recent call last):
  File "D:\Synthetic Hand\3D hand 7.blend\makeclip.py", line 67, in <module>
  File "<string>", line 71, in apply_mocap
  File "<string>", line 46, in apply_animation
  File "C:\Program Files\Blender Foundation\Blender 2.91\2.91\scripts\modules\bpy\ops.py", line 132, in __call__
    ret = _op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.anim.keyframe_insert_menu.poll() failed, context is incorrect

The function that throws the error is below. The line that throws the error is the last in this function.

def apply_animation():
    global source, target, frame_from, frame_to
    #set keying set to whole character
    #we have all bones selected
    scene = bpy.context.scene
    for frame in range(frame_from, frame_to ):
        scene.frame_current = frame
        scene.frame_set(scene.frame_current)
        # apply visual transfrom to pose Ctrl+A
        bpy.ops.pose.visual_transform_apply()
        # insert all keyframes -> press I
        bpy.ops.anim.keyframe_insert_menu(type='__ACTIVE__', confirm_success=True)

I realize the call to keyframe_insert_menu refers to a GUI control, which is not available in the headless mode. What’s another away to accomplish the same thing?

I managed to solve the problem by iterating through the bones and calling their keyframe_insert method. The previous approach was to pre-select all bones and then call a function that’s equivalent to hitting I on the keyboard, which would add keyframes for all selected bones.

        ob = bpy.data.objects[source]
        for bone in ob.pose.bones:
            bone.keyframe_insert(data_path = 'location')
            if bone.rotation_mode == "QUATERNION":
                bone.keyframe_insert(data_path = 'rotation_quaternion')
            else:
                bone.keyframe_insert(data_path = 'rotation_euler')
            bone.keyframe_insert(data_path = 'scale')