Maya Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Python

Maya Python commands


Commands in Python all have a similar structure, a function that takes a number of named and unamed
arguments. To start using Python, make sure you are in the Python tab, and then load the commands:
import maya.cmds as cmds
Most commands are named the same as their equivalent MEL command. The biggest difference is that
some are not included in Python. This includes a number of mathematical and geometrical functions, as
well as functions like rand. Some of these have replacements in standard Python libraries, and some do
not.
Node creation:
cmds.sphere( n='earth' )
Finding nodes in a scene of a particular type:
cmds.ls( type='nurbsSurface' )
Finding selected nodes:
cmds.ls( selection=True )
Finding attributes on a given node:
cmds.getAttr('earth.translate')
cmds.getAttr('earth.translateX')
Setting attributes:
cmds.setAttr('earth.translateX', 5.0)

Using Variables
Variables are storage places for values. There are two main types of variables that we will use in this
class: strings and numbers. The programmer chooses the name for the variable, and there are a few
important rules to follow:

Choose names that make sense


Use letters, numbers, and the underscore _
Don't begin a variable name with a number
Don't use the names of functions or other Python reserved words

In Python, there is a distinction between different types of variables. Unlike MEL, the type can change
throughout the program, and this will affect how a variable can be used.
Variables have three parts: a name, a value, and a type. Here is an example of creating a variable that is
a number, with the name position and a value of the translateX of an object called "earth":
position = cmds.getAttr('earth.translateX')
Once the variable is created with a value, we can use it to manipulate the values of objects in Maya:
position = position + 5
cmds.setAttr('earth.translateX', position)

The assignment operator - the = - will store the value on the right-hand side into the variable on the left
hand side.

Conditional Statements
Conditional statements allow you to choose an action to take based on the value of some variable in the
program. In Python, conditionals are expressed with the if ... elif ... else structure.
The simplest example of a conditional is a check to see if a value is within a certain range:
if position > 5:
The conditional will return True if the condition is met - in this case, if the variable position is greater
than 5. If there is not, it will return False.
Whitespace is very important in Python. Whitespace consists of all of the characters that you cannot see
in text, but affect the way that it is aligned: spaces, tab characters, newlines and carriage returns.
Inside of an if statement, all of the associated commands must be one visual TAB over from the left
side. In the Script Editor, just press the tab key.
if position < 5:
cmds.setAttr('earth.translateX', 0)
All of the lines in your program that are one TAB over will be executed if the statement is True. If it is
False, they will be skipped.
To continue on with the program after the conditional, you just need to go back to the left justification
of the original if. These lines will continue as the program normally would, running independent of the
if statement.
When you use an if, Python will execute the associated statements if the condition is True, and do
nothing if it is False. You can also specify an alternative by use an else:
if position < 5:
cmds.setAttr('earth.translateX', position + 5)
else:
cmds.setAttr('earth.translateX', 5)
Comparison in conditionals
< - less than
<= - less than or equal to
> - greater than
>= - greater than or equal to
== - equal to
not - added for negation
and - combine two conditions, both must be true

or - combine two conditions, one must be true


You can also use a third clause in a conditional called an elif. This lets you choose multiple situations:
if cmds.getAttr('pSphere2.translateX') == 0:
cmds.setAttr('pSphere2.translateX', 10)
if cmds.getAttr('pSphere2.translateX') == 0:
cmds.setAttr('pSphere2.translateX', 10)
elif cmds.getAttr('pSphere2.translateX') >= 10:
cmds.setAttr('pSphere2.translateX', 15)

Object creation
These are some very simple commands that you can use in Maya to create objects:
cmds.nurbsPlane( ...)
cmds.polyPlane( ...)
cmds.sphere( ...)
cmds.polySphere( ...)
cmds.nurbsCube( ...)
cmds.polyCube( ...)

Properties of Transform nodes


translate - translateX, translateY, translateZ
rotate - rotateX, rotateY, rotateZ
scale - scaleX, scaleY, scaleZ

Storing the name of an object when you create it


transform, shape = cmds.polySphere()
The variable transform will contain the transform information, and the variable shape will have the
shape information.
In order to access one of these properties, you can use string concatenation with the name of the object
and the property you are trying to change:
cmds.setAttr(shape + '.radius', 5)

Loops
Loops are used to repeat a certain lines of code. The most common loop in Python is a for loop. A for
loop repeats all of the statements that are associated with it. Those statements are tabbed over one level
from the for, and statements that are lined up with the justification of the for will be run when the loop
is completed.

For loops are useful for repeating a task. For instance, if you know that you need to create a certain
number of objects, you can use a for loop to repeat the task:
for num in range(10):
cmds.sphere()
This will create ten spheres. You can also take advantage of the variable num to perform some action
inside of the loop.
for num in range(1, 11):
cmds.sphere( radius= num)
One other way that a for loop can be used to iterate through a list. Many of the commands that find
nodes in Maya return a list - this is anything between the square brackets. Most commonly, these
commands will return a list of strings.
For instance, you can use the ls command to find nodes in a scene that are selected:
for node in cmds.ls( selection=True ):
print node
If you have a list of things, you can use a for loop to go through all of them and perform some task.
for node in cmds.ls( selection=True ):
print cmds.getAttr(node + '.translateX')

Finding the Shape node


If you have the transform node name, you can find the related shape node using the listRelatives
command:
cmds.listRelatives('nurbsSphere1')
From here, you can adjust the properties of the shape:
for sphere in cmds.ls ('nurbsSphere*', type='transform'):
posX = cmds.getAttr(sphere + '.translateX')
shape = cmds.listRelatives()[0]
radius = cmds.sphere(shape, query=True, radius=True)
cmds.sphere(shape, edit=True, radius=radius+1)

Deletion
There are several different ways to delete objects in the scene. You can delete all of the selected
objects:
cmds.delete()
You can delete by name:
cmds.delete( 'surfaceShape1', 'surface1', 'paramCurve1' )
And you can delete a list of items that are returned from another command:
cmds.delete( cmds.ls( geometry=True ) )

Changing attributes
Once you have access to the nodes that you want, you can also change attributes:
for asset in cmds.ls('sphere*', type='transform'):
print cmds.setAttr(asset + '.translateX', 0)

Lists
Lists are a type of variable in Python. They can hold multiple elements, including elements of different
types. To create a list, you use the [ ]
spheres = ["sphere1", "sphere2", "sphere5", "sphere10"]
Each element has an index value, starting with 0 on the left-hand side. They also have addresses that
start on the right-hand side, starting with -1:
0
-4
spheres "sphere1"

-3
-2
"sphere2" "sphere5"

3
-1
"sphere10"

You can also refer to a slice of a list, which is a part of the list. To get a slice of the first two spheres:
print spheres[0:2]
The first number can be omitted if the slice starts at the beginning, or the last one if it goes until the end
of the list:
print spheres[:2]
print spheres[1:2]
print spheres[2:]
You can also use a step:
print spheres[0:4:2]
To find the length:
print len(spheres)
How many of a particular item:
print spheres.count(sphere1)
Is the item in the list?
if sphere1 in spheres:

Adding a new element to a list can be done using append:


spheres.append(sphere6)
To append multiple items, perhaps while making a decision about them, you can use this pattern:
spheres = []
for object in cmds.ls(sl=True):
if 'Sphere' in object:
spheres.append(object)
print spheres
Additional operators for lists and strings (from the Python documenation):
Operation
s[i] = x
s[i:j] = t
del s[i:j]
s[i:j:k] = t
del s[i:j:k]
s.count(x)
s.insert(i, x)
s.pop([i])
s.remove(x)
s.reverse()
s.sort()
s.sort(reverse=True)

Result
item i of s is replaced by x
slice of s from i to j is replaced by the contents of the iterable t
same as s[i:j] = []
the elements of s[i:j:k] are replaced by those of t
removes the elements of s[i:j:k] from the list
return number of is for which s[i] == x
same as s[i:i] = [x]
same as x = s[i]; del s[i]; return x
same as del s[s.index(x)]
reverses the items of s in place
sort the items of s in place
reverse sort the items of s in place

Tuples
A tuple is very similar to a list, but it does not share all of its properties. The most important difference
is that a tuple is not mutable the individual elements cannot be changed.
That means that you cannot do this with a tuple:
spheres = ("sphere1", "sphere2", "sphere5", "sphere10")
spheres[0] = sphere3

Because the () are special character in Python, there are also some oddities. For instance, to create a
single item tuple:
spheres = ("sphere1",)

Why are tuples important? They maintain the integrity of an entire sequence. Also, many functions
return them in fact, that is what a function returns by default when it returns multiple elements.
What if you have a tuple and want to convert it to a list?
spheres = ("sphere1", "sphere2")
spheres = list(spheres)
Or vice versa:
spheres = tuple(spheres)

Sets
A set is a group of items like a list or a tuple. The main difference is that is unordered instead of the
items staying in the order that you put them in, a set organizes the items in the way that makes the most
sense for searching through them.
Sets share some of the functions that are a part of other containers, such as: len(s), x in s, x not in s.
However, they do not support indexing or slicing, since their is no fundamental order to the items. Here
are the methods that are unique to sets:
Operation
s.add(x)
s.remove(x)
s.discard(x)
s.discard(x)
s.clear()
s.issubset(t)
s.issuperset(t)
s.union(t)
s.intersection(t)
s.difference(t)
s.symmetric_difference(t)

Result
add element x to set s
remove x from set s; raises KeyError if not present
removes x from set s if present
remove and return an arbitrary element from s; raises
KeyError if empty
remove all elements from set s
test whether every element in s is in t
test whether every element in t is in s
new set with elements from both s and t
new set with elements common to s and t
new set with elements in s but not in t
new set with elements in either s or t but not both

In addition to being useful for working with these ideas, you can also make a unique list by:
spheres = list(set(list))

Dictionaries
A dictionary is also referred to as a map or a hash. It allows you to associate a key with a value.
Creating a dictionary:
spheres = {'sphere1': 1, 'sphere2':10, 'sphere3':20}
Just like with a list, you can create an empty dictionary and iterate through some items to add them:
spheres = {}
for object in cmds.ls(sl=True):
spheres[object] = cmds.getAttr( object + '.translate')
There are also two useful constructor forms that can take either lists (one with the keys and one with
the values) or tuple pairs:
objects = ['sphere1', 'sphere2', 'sphere3']
colors = ['red', 'green', 'blue']
shadedObjects = dict(zip(objects, colors))
shadedObjects = dict( [('sphere1','red'), ('sphere2', 'green'),
('sphere3', 'blue')] )

Operation
len(d)
d[key]
d[key] = value
key in d
get(key[, default])
del d[key]

Result
Return the number of items in the dictionary d.
Return the item of d with key key. Raises a KeyError if key is
not in the map
Set d[key] to value.
key in d
Return the value for key if key is in the dictionary, else default
Remove d[key] from d

There are several ways that dictionaries can be used in for loops. On is to iterate through the keys, and
then access the values using bracket notation:
for sphere in spheres:
print sphere
print spheres[sphere]

You can also use the function iteritems to give key-value pairs:

for key, value in spheres.iteritems():


print key, value

Functions
Functions are small blocks of code that can be executed repeatedly. The two most important variations
in functions occur in their arguments and return values.
This is a simple definition of a Python function. It doesn't take any arguments, and it returns a value of
None by default.
def createSpheres():
for i in range(4):
cmds.polySphere()
There is one way to call the function:
createSpheres()
Arguments can be added to send information into a function. They have names, but they do not have a
specified type:
def createSpheres(num):
for i in range(num):
cmds.polySphere()
createSpheres(2)
Default arguments can be created that have a value. With a default argument, you can still specify and
argument but if you do not, the value of the default will be used:
def createSpheres(num=4):
for i in range(num):
cmds.polySphere()
There are two ways to call this function, either with an argument or without one:
createSpheres()
createSpheres(6)
Arguments can also be called using their name. This is the main way that Maya Python calls use
arguments. It can be especially useful if the arguments all have defaults, because then you can choose
between the arguments you would like to use:
def createSpheres(num=4, size=0.5):
for i in range(num):
cmds.polySphere()
To use the named argument:

createSpheres(size=1)
In some functions, you may want to send an arbitrary number of arguments. This can be specified using
the *:
def createSpheres(*names):
for name in names:
cmds.polySphere(n=name)
createSpheres('earth', 'venus', 'mars')

Range
There are several ways to use the builtin function range(). It constructs a list based on the arguments
that your provide.
range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(1, 11)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(10, -1, -1)

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

range(2, 11, 2)

[2, 4, 6, 8, 10]

You might also like