Search code examples
pythonpython-2.7mayamel

How can you check if a frame is a keyframe in Maya with Python?


I need to cycle through every frame of an animation in Maya and create two arrays, one of the values of a given attribute at every single frame, and one of those values only at the keyframes. Problem is, I can't figure out how to make maya ask the question "is the current frame a keyframe for this attribute" in python. I figured it out in MEL, though, so maybe somebody could help me convert it.

Here's the loop in MEL:

global proc int keyExistsAtFrame(   int $frameNum,
                    string $object,
                    string $attribute)
{
    int $value;
    selectKey -clear;
    $value = `selectKey -add -k -t $frameNum ($object + "." + $attribute)`;

    if($value)
        return 1;
    else
        return 0;
}

for( $i=1; $i<120; ++$i )
{
    currentTime -edit $i;
    if (keyExistsAtFrame($i, "DD_headRoll_ctrl", "rotateZ"))
    {
        print "key exists at ";
        print $i;
        print "\n";
    }
}

How could I implement this into my python script? Here's my current draft in python:

import maya.cmds as cmd

for i in range(int(cmd.playbackOptions(q=1, minTime = True)), int(cmd.playbackOptions(q=1, maxTime = True))):
    cmd.currentTime(i, e=1)
    iskey = cmd.selectKey(add = True, k = True, t = (i, i), attribute = "DD_headRoll_ctrl.rotateZ")
    #print iskey
    if iskey:
        print i

Solution

  • It's actually a lot simpler than that to find out if a plug has keys:

    object = "pSphere1"
    attr = "tx"
    
    cmds.keyframe(object + "." + attr, q=True)
    
    # Result: [5.0, 28.0, 46.0, 79.0] #
    

    cmds.keyframe will return a list of frames every key is on.