Tuesday, August 19, 2014

Tip using Python Try Except for Maya scripts

Happy Tuesday,

One reason Python is extremely helpful for Maya hot key script writing is the ability to use try and except statements to avoid needing to write lots of error checking code.

Here's an example that sets some rotation channels in channel editor that should work whether or not channels are locked.  If this was written in MEL it would take more lines of code to get the tool to not bug out with locked channels.

Hope you find this helpful.

#author: Nathaniel Anozie (ogbonnawork at gmail dot com)
#
#modify at own risk

# updated 08-18-2014 nate ----- initial commit

import maya.cmds as cmds

def na_zeroRotate():
    """
    set rxyz to 0 for all selected
    """
    sel = []
    sel = cmds.ls(sl=True)

    #does what it can
    for arg in sel:
        try:
            cmds.setAttr( (arg+".rotateX"),0)
        except RuntimeError:
            pass
        try:
            cmds.setAttr( (arg+".rotateY"),0)
        except RuntimeError:
            pass
        try:
            cmds.setAttr( (arg+".rotateZ"),0)
        except RuntimeError:
            pass
cheers,
Nate