how to automate bpy.ops.action.snap(FLATTEN_HANDLES)

If this is not the best forum for this, please let me know, I’m a newby here.

I’ve copied a basic run animation from a BVH file to a human model created in MakeHuman. The VBH file had no data for hands and fingers so I modeled a fist for each hand in the first keyframe and created a Python script that copied the “rotation_quaternion” W, X, Y, and Z values for each bone in each hand in the first keyframe into the same bones in all subsequent keyframes. This worked well enough except that the fCurves for each bone looked like a row of arches over the in-between frames and the hands opened for the in-betweens and closed for the keyframes. Weird. I found that selecting each bone in each hand in Pose mode and executing key-> snap->Flatten Handles in the UI’s Graph Editor fixed the problem.

Now I’d like to add something like

bpy.ops.action.select_linked()
bpy.ops.action.snap(type='NEAREST_MARKER')

to my script for each bone after changing the rotations in each fCurve so I don’t have to do it manually. Unfortunately, I’m not familiar with bpy.ops operations yet and all I’m getting is:

RuntimeError: Operator bpy.ops.action.select_linked.poll() failed, context is incorrect.

I’ve read enough in the Blender 2.6 docs to know that bpy.ops represents operations so you can use Python to automate UI tasks but I haven’t gotten the hang of it yet.

So, If anyone could point me towards tutorials, examples, docs, or any reasonable related instructional materials I’d really appreciate it. A little example here would be great but I don’t mind digging things out myself until the time spent becomes as aggravating as it has here.

Also, I used “Flatten Handles” in the UI but didn’t find it in the enum definition in the 2.6 Python doc. I hope ‘NEAREST_MARKER’ provides the same fix but would rather do in Python what I’ve done in the UI. Is that possible in this case? Finally, I don’t know if “bpy.ops.action.select_linked”, which is causing the current problem, is correct or even necessary. Any comments on this would be great.

Thanks in advance for any assistance anyone can provide.

This works if you got the right object and the handles selected:

import bpy
a=bpy.context.area.type
bpy.context.area.type = 'GRAPH_EDITOR'
bpy.ops.graph.snap(type='HORIZONTAL')
bpy.context.area.type = a