Posts Tagged ‘quick-tip’

Python in Maya

I´ve finally started python inside Maya and It has been great! I´d share a few ideas in this post.

MEL is definitely a great starting point and everyone love it but it is a bit “legacy” nowadays since python makes life much easier, suitable and powerfull in terms of programming for CG. The bindings for all of the native Maya commands are in the maya.cmds module, wich can be called as following:

import maya.cmds

selection = maya.cmds.ls(sl=True)
# import using shorter namespace ie. cmds, cmd, mc
import maya.cmds as mc

selection = mc.ls(sl=1)
print 'selected nodes are %s \n' % selection

A top-level namespace that imports all the modules/methods directly:

import sys
from maya.cmds import *

selection = ls(sl=1)
selShape = []

for sel in selection:
    selShape.append(listRelatives(sel, s=1))

sys.__stdout__.write('selected= ' + str(selection) + 'shape= ' + str(selShape) + '\n')

You should read this Autodesk help link and also this article before coding in that way.

The cool new pythonic OOP based system integrated with 2011 and 2012 versions is called Pymel, wich wrap classes and basically attaches attributes exposing their properties:

import pymel.core as pymelCore

# note the inheritance of methods
lastSelected = pymelCore.ls(sl=1)[-1]
longNames = pymelCore.listAttr(lastSelected.longName())

print 'node= %s attrs= %s' % (lastSelected, longNames)

Here´s a another example, it adds a shelfButton into the Custom shelf menu:

# tested under Maya 2012

import pymel.core as pmc

pmc.uitypes.ShelfButton( p = (pmc.uitypes.ShelfLayout('Custom')),
                                   en = 1,
                                   ebg = 1,
                                   vis = 1,
                                   po = 1,
                                   pma = 1,
                                   m = 1,
                                   ann = "right click to view pop-up menus",
                                   label = "Test",
                                   imageOverlayLabel = "TEST",
                                   st = "iconAndTextHorizontal",
                                   menuItem = [ ("LOG", " python(\"import logging; logging.info('log')\") "),
                                           ("JOINTS", " python(\"import maya.cmds as cmds; cmds.ls(type='joints')\") ")
                                           ]

Check out this video tutorial from CG Bootcamp aswell.

Last but not least, it is a good idea to configure one IDE to speed up the workflow. I personally use Eclipse as Maya IDE. Check out Jason Parks Power Python for Maya (Plus) LIVE lecture recorded by Rigging Dojo to learn more about that.

That´s all folks, cheers :)

Filed under: resources — Tags: , , , — renatopolimeno @