How do I export animation data stored in actions using the Python API?

I am writing an exporter for a custom format, and I would like it to export each action as a separate animation. Based on what I've learned so far, I think the exporter would have to look something like this:

export_rest_pose(armature_object.data.bones)
for action in bpy.data.actions:
# TODO: set 'action' as the current action, somehow
frame_begin, frame_end = [int(x) for x in action.frame_range]
for frame in range(frame_begin, frame_end):
bpy.context.scene.frame_set(frame)
export_pose(armature_object.pose.bones)


First, does this look about right, or is there a better way of doing it? In particular, is there a way to get the pose of an armature at a specific frame without changing the whole scene to that frame?

Second, assuming that is the correct way to do it, how do I set the current action?

You can set an object's action like:

object.animation_data.action = action


But note that you should check first, that animation_data is not None (which is the case for objects with zero keyframes set).

frame_set() is not a bad choice. You could also evaluate the F-Curves one by one and avoid the frame changes, but it's easier to set the frame and get the transformations ready to use (e.g. as 4x4 Matrix). It's also ensured that all modifiers, drivers and such are applied.

Quick F-Curve example:

bpy.context.object.animation_data.action.fcurves[0].evaluate(5)
#~ -3.2612

bpy.context.object.animation_data.action.fcurves[0].keyframe_points[0].co
#~ Vector((1.0, -3.2612))

bpy.context.object.animation_data.action.fcurves[0].keyframe_points[0].interpolation
#~ 'BEZIER'