Sunday, August 15, 2010

Basic Python in Maya

Lets cover some Python fundamentals to get us started.

Since, out of the box, Python was not developed for Maya it does not understand how to interact with any of your scene's nodes.  Therefore, although you can always write pure Python code with no problem, whenever Python needs to interact with your scene you will need to import a module Maya provides to append all its MEL functions. 
import maya.cmds
maya.cmds.polySphere()
This will first execute the module maya.cmds from the current Python session.  This will import all of Maya's Python wrappers for its MEL commands.  To execute the Maya command you must write the module name followed by the command name.  To reduce the need to type maya.cmds for every command it is most common to assign the module to a namespace.
import maya.cmds as cmds    #mc is also a frequently assigned namespace
cmds.polySphere()
Another method is to bring all the maya.cmds objects into the current main module:
from maya.cmds import *
polySphere()
This requires no namespaces.  However, standard Python functions may be overridden. Alternatively, since everything in Python are objects you can copy the function call to an object in the current module.
import maya.cmds as cmds
polySphere=cmds.polySphere()
polySphere()

 -----

Most commands return feedback after a successful call.
  • All commands in create mode return the name of the node created. 
  • Query commands return the attribute(s) designated.  
  • Edit commands will return either 0 or 1.  
Again, always have the docs open while programming to check available flags.
mySphere=cmds.polySphere() #stored the created nodes in mySphere
print mySphere
>>[u'pSphere1', u'polySphere1']
These are some of the most simple, essential commands that even non programmers should know. You will return to these time and time again.
  • ls
  • select
  • delete
  • listAttr
  • setAttr
  • listConnections
  • listRelatives
  • nodeType
  • undo

Example:
import maya.cmds as cmds
stepTransforms=[]     #a python array
for i in xrange(50):     #loop this code block 50 times
    currentStep=cmds.polyCube(width=6, height=.2, depth=1, name="step%s" %i)
    cmds.xform(currentStep, translation=[0,float(i)/5,0], rotation=[0,i*10,0])

    stepTransform, stepMesh=currentStep     #unpack the polyCube result into transforms and meshes
    stepTransforms.append(stepTransform)
cmds.group(stepTransforms, name="stairs")
Writing Python procedures for Maya doesn't get much more complicated than that.  Play around with different commands, and remember the docs have examples on nearly everything.