A blog for brain droppings and tech stuff

Maya Python API

For the past few years I have been working with Maya’s Python API, aka OpenMaya 2.0. I find that it does a fairly good job of bridging Maya’s C++ API with a more “Pythonic” wrapper than OpenMaya. Less syntax is required since we can pass Python data types such as floats and lists. The only downside I have a found is lack of documentation. In some cases we can pass a list of floats and in others we need to specifically use a Maya container such as MDoubleArray in order to find the correct signature if a function is overloaded.

Here is a simple example of rotating a cube using the API.

"""
@Author Neil Berard
MAYA PYTHON API EXAMPLE
Create a cube and modify its Transform.
"""
import maya.api.OpenMaya as om2
import maya.cmds as cmds
# CREATE CUBE
# Create a simple cube and edit it with Maya API
cubeStr = cmds.polyCube()[0]

# GET THE API CUBE NODE
selectionList = om2.MGlobal.getSelectionListByName(cubeStr)

# DAG PATH (actual transform node)
# 0 parameter means the first entry of the list.
dag = selectionList.getDagPath(0)
# TRANSFORM
# Function Class similar to cmds.xform, we can now modify transform attributes such as rotation or
# setting the matrix value of an object.
xform = om2.MFnTransform(dag)
# ROTATE 45 DEGREES IN X
# Need to convert to radians.
x = om2.MAngle(45.0, om2.MAngle.kDegrees)
rot = om2.MEulerRotation(x.asRadians(), 0, 0)
xform.setRotation(rot, om2.MSpace.kTransform)