Code Snippets: Maya Py

Updated: Feb 9

select a node and get a list of currently selected nodes

# method 1
cmds.select('nodeName')
selection = cmds.ls(sl=True)

# method 2
node_list = cmds.ls('nodeName*')

use wildcards (*, ?) to select multiple nodes at once


add to a selection

cmds.select('nodeName', add=True)

clear a selection

cmds.select(cl=True)
 

working with nodes

# create and delete
cmds.createNode('nodeType', n='nodeName')
    # adding 'Shape' to the end when creating a shape node
    properly names the transform node as well
cmds.delete('nodeName')

# group nodes
cmds.group(n='groupName', em=True)
cmds.parent('nodeName', 'groupName')

# get node type
type = cmds.nodeType('nodeName')

check if a node exists

if cmds.objExists('nodeName') == 1:
    # the node exists

add or remove a node from a set

cmds.sets('node_name', add='set_name') # add
cmds.sets('node_name, remove='set_name') # remove
 

working with attributes

# set an attribute
cmds.setAttr('node.attr', 'example', type='string')

# get an attribute's value
value = cmds.getAttr('node.attr')

# get a list of all attributes of a node
attr_list = cmds.listAttr('node')

# add an attribute
cmds.addAttr(at='float', dv=0, max=1, min=-1, nn='Attr Name', ln='attrName')
 

get the shape node from the transform node

cmds.listRelatives('trans_node', typ='shape', c=True)[0]

get the transform node from the shape node

cmds.listRelatives('shape_node', typ='transform', p=True)[0]
 

center pivot

cmds.xform('nodeName', cp=True)

freeze transforms

cmds.select('nodeName')
cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)

delete history

# all construction history
cmds.delete(all=True, ch=True)

# only selected nodes
cmds.select('nodeName')
cmds.delete(ch=True)
 

create and assign a shader

cmds.shadingNode('shaderType', n='shaderName', asShader=True)
cmds.sets(n='shaderGroupName', em=True, r=True, nss=True)
cmds.connectAtttr('shaderName.outColor', 'shaderGroupName.surfaceShader')

cmds.select('geoName')
cmds.hyperShade(assign='shaderName')
 

create a keyframe

value = 1
frame_num = 10
cmds.setKeyframe('nodeName', v=value, at='attrName', t=frame_num)

create an expression

cmds.expression(a='node.attribute', s='expression')
 

get current viewed camera

for viewport in cmds.getPanel(type='modelPanel'):
    current_cam = cmds.modelEditor(viewport, q=1, av=1, cam=1)

create a camera and image plane

cmds.camera(n='cameraName', fl=50)
cmds.setAttr('cameraName.renderable', 1)

cmds.imagePlane('n='imagePlaneName', c='cameraName')
cmds.setAttr('imagePlaneName.depth', 1000)
    # turn image plane off
cmds.setAttr('imagePlaneName.displayMode', 0)
    # turn image plane on
cmds.setAttr('imagePlaneName.displayMode', 3)

cmds.lookThru('cameraName')

fit image plane to resolution gate

import maya.mel as mel

mel.eval("source AEimagePlaneTemplate.mel")
mel_command = "AEinvokeFitRezGate %s->%s.sizeX %s->%s.sizeY" % (cam, img_plane, cam, img_plane)
mel.eval(mel_command)
 

get current file name and path

import maya.cmds as cmds
import os.path

file_path = cmds.file(q=True, sn=True)
file_name = os.path.basename(file_path)

set project and open a file

import maya.cmds as cmds
import maya.mel as mel

mel.eval('setProject \"' + 'full/project/path' + '\"')
cmds.file('fileName', o=True, f=True)

save a file under a new name

import maya.cmds as cmds

cmds.file(rename='new_name')
cmds.file(force=True, save=True, type='mayaBinary')
 

create a reference

cmds.file('full/path/to/file', r=True, mnc=False, nc='namespace', op="v=0;")

get a list of all references

references = cmds.ls(type='reference')

get a reference file path

path = cmds.referenceQuery('referenceName', f=True, shn=True)

replace a reference

cmds.file('path/to/new/reference/file', loadReference='refName')

delete a selected reference

selection = cmds.ls(sl=True)
for obj in selection:
    ref = cmds.referenceQuery(obj, f=True)
    cmds.file(ref, rr=True)
 

export selected geometry

import maya.cmds as cmds
import os.path

# select desired geometry prior to export

fileName = 'exportedGeo.mb'
dirPath = 'full/path/to/desired/directory'
type = 'mayaBinary'

filePath = os.path.join(dirPath, fileName)
cmds.file(filePath, op='v=0;', typ=type, pr=Falsale, es=True)
 

check if a node name already exists, and add numbers if it does

node_name = 'test_geo'
if cmds.objExists(node_name)
    count = 0
    node_list = cmds.ls(node_name + '_*')
    for node in node_list:
        name_parts = node.split('_')
        total = len(name_parts)
        num = int(name_parts[total]) - 1
        if num > count:
            count = num
    count += 1
    result_name = '%s_%02d' % (node_name, count)
else:
    result_name = node_name
 

print a result on the Maya command line

import sys
sys.stdout.write('# Result: message #')

raise an error

cmds.error('Error message')
 

basic ui start

import maya.cmds as cmds

def ui():
    # define ui
    uiName = 'uiName'
    uiTitle = 'ui title'
    width, height = [200, 200]
    
    # check if window exists
    if cmds.window(uiName, ex=True):
        cmds.deleteUI(uiName)
    
    # create window
    window = cmds.window(uiName, t=uiTitle, wh=(width, height), s=False, mxb=False, rtf=False)
    
        # add elements to ui
    cmds.columnLayout(cal='left')
    cmds.text('example')
    cmds.setParent('..')

    # show window
    cmds.showWindow(window)

ui()

more information


some ui layouts and controls

cmds.columnLayout()
cmds.rowLayout()
cmds.tabLayout()

cmds.separator()

cmds.button()
cmds.text()
cmds.textFieldGrp()
cmds.checkBox()
cmds.floatFieldGrp()

cmds.optionMenu()
cmds.menuItemtem()

working with controls

# edit a control
cmds.controlCmd('controlName', e=True, attrFlag=newValue)

# query a control
cmds.controlCmd('controlName', q=True, attrFlag=True)

# disable or enable a control
cmds.disable('controlName', v=True)

replace a control

def replaceControl(*args):
    cmds.deleteUI('controlName')
    cmds.controlCmd('ctrlName', flags=values, p='parentLayout')
    
def changeMenuItems(*args):
    cmds.deleteUI('controlName')
    cmds.optionMenu('ctrlName', flags=values, p='parentLayout')
    cmds.menuItem('new item 1')
    cmds.menuItem('new item 2')
    cmds.setParent('..')
190 views