Python Notes
Last edited March 5, 2009
More by Daxx »
Tutorials

Qt Designer  http://www.cs.usfca.edu/~afedosov/qttut/

pyuic form1.ui > form1.py  
Modules

CTYPES
 http://python.net/crew/theller/ctypes/
is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. In Python 2.5 it is already included.
WxPython
http://www.wxpython.org/
 a good module to create standard interface with the style of the system where running

Labels: Python Modules
PyOpenGL
http://pyopengl.sourceforge.net/
 The Python OpenGL® Binding
Labels: Python Modules
pyGame
http://www.pygame.org/news.html
 a game interface for python
Labels: Python Modules
python CGKIT
http://cgkit.sourceforge.net/
this module give the access to Renderman , SL , CGshaders and more on CG
Labels: Python Modules
MySqlDb
http://sourceforge.net/projects/mysql-python
 THE module to interface python with mySQL
Labels: Python Modules
Python 3D Software links
www.vrplumber.com/py3d.py#PyOpenGL
 
 This is a section to put notes about python modules
Labels: Python Modules
Notes

Useful links

http://www.python.org - The Python home page

http://diveintopython.org - A really good programmers' guide to Python

http://it.diveintopython.org/toc/index.html (italian doc)

http://docs.python.org/ref/ref.html - Python Reference Manual

http://docs.python.org/lib/lib.html - Python Library Reference

http://www.penzilla.net/tutorials/python/

http://www.effbot.org/librarybook (the eff-bot guide to) The Standard Python Library

http://docs.python.it  (italian doc) e - zona Python

http://aspn.activestate.com/ASPN/Cookbook/Python (en doc)

http://www.pycode.com/

iwiwdsmi.blogspot.com  Sofeng's Blog

This is a section to put useful links to python docs

Labels: Python Notes
Maya Python Code Examples

 #----------------------------------DIGITAL TUTORS NOTES
#------------------------------ variables sample
import maya.cmds as mc
cubeToBevel = mc.polyCube(w=1, h=1, d=1, sx=1, sy=1, sz=1, ax=(0,1,0), cuv=1, ch=1)
mc.scale(4,4,4, r=True)
mc.polyBevel(cubeToBevel, offset=0.5, offsetAsFraction=1, autoFit=1, segments=1, worldSpace=1, fillNgons=1, mergeVertices=1, mergeVertexTolerance=0.0001, smoothingAngle=30, miteringAngle=180, angleTolerance=180, ch=1)

#------------------------------- variables types
original = "rosco"
copycat = original

# ----------------------------------------concatenating strings
print copycat
print copycat + " is the value of the string named copycat"

# -------------------------------------concatenating string+int or float or hex
intLife = 42
fPI = 3.14
hexColor = 0xFFCC00
print "The value of IntLife is ... %d" % intLife
print "The value of fPI is ... %f" % fPI
print "The value of hexColor is ... %x" % hexColor

print "My values are %d and %f" % (intLife,fPI)

# ------------------------------- selections
myFirstList = [ ] # array
myFirstList = [ "red", 21.00, 1 ] # you can create a multidimensional array  ( string, float, int)
listKeys = mc.ls(sl=True) # ls -sl

#----------------------------------------- for loop
listKeys = mc.ls(sl=True)
selSize = len(listKeys)
for i in range(0,selSize,1) :     # for i in range(start,end,increment)
    rescaler = (i+1)*0.1
    mc.scale(rescaler,rescaler,rescaler, listKeys[i], r=true)
print "done"

#--------------------------------------------------- Tutorial  - procedural Cog

import maya.cmds as mc

pdStatus= mc.promptDialog(message="Please imput number of teeth", button="OK")
if pdStatus == "OK": # double equal to compare
    numTeeth = mc.promptDialog(query=True, text=True)
    numTeeth = int(numTeeth) # this is a function to change a string type into an int type

pdStatus2= mc.promptDialog(message="Please imput radius", button="OK")
if pdStatus2 == "OK": # double equal to compare
    numRad = mc.promptDialog(query=True, text=True)
    numRad = float(numRad)
    gear = mc.polyPipe(subdivisionsAxis=numTeeth*2,radius=numRad, h=0.5)
    # Set tbe value of intSA to be the pipe's subdivision axis
    intSA = mc.getAttr(gear[1]+".subdivisionsAxis")
    # Use formula to derive the start and end outer faces
    intStartFace = (intSA * 2)
    intEndFace = (intSA * 3) - 1
    mc.select(clear=1)
    ### Deselect all in use for loop to select every other face
    for i in range (intStartFace, intEndFace, 2):
        mc.select(gear[0]+".f[%d]" % i,add=True)
    mc.polyExtrudeFacet(ltz=0.5)
    mc.polySmooth(gear[0],continuity=0.5)
   
#  ----------------------------------------Tutorial - disperser

import maya.cmds as mc
import random as rnd     # help(random) to know what's inside random module

selList = mc.ls(selection=True)
for obj in selList:
    rangeX = rnd.randint (-10, 10)
    rangeZ = rnd.randint (-10, 10)
    mc.setAttr(obj + ".translateX", rangeX)
    mc.setAttr(obj + ".translateZ", rangeZ)
   
#----------------------------------------------  Disperser GUI

 if mc.window("dWin", q=True, ex=True):
    mc.deleteUI("dWin")
dWin=mc.window(title="Disperser",wh = (256,256))
mc.columnLayout()
mc.separator(h=10)
mc.text(label=" Set X Y Z Range Values for Translation")
rangeTField = mc.floatFieldGrp(numberOfFields=3)
mc.separator(h=10)
mc.text(label=" Set X Y Z Range Values for Rotation")
rangeRField = mc.floatFieldGrp(numberOfFields=3)
mc.separator(h=30)
mc.button(label="Disperser Selected",command="disperse()")
mc.showWindow(dWin)


def disperse():
    import maya.cmds as mc
    import random as rnd     # help(random) to know what's inside random module
    selList = mc.ls(selection=True)
    rangeTX = mc.floatFieldGrp(rangeTField, query=True, value1=True)
    rangeTY = mc.floatFieldGrp(rangeTField, query=True, value2=True)
    rangeTZ = mc.floatFieldGrp(rangeTField, query=True, value3=True)
    rangeRX = mc.floatFieldGrp(rangeRField, query=True, value1=True)
    rangeRY = mc.floatFieldGrp(rangeRField, query=True, value2=True)
    rangeRZ = mc.floatFieldGrp(rangeRField, query=True, value3=True)
    for obj in selList:
        randomTX = rnd.randint (-rangeTX, rangeTX)
        randomTY = rnd.randint (-rangeTY, rangeTY)
        randomTZ = rnd.randint (-rangeTZ, rangeTZ)
        randomRX = rnd.randint (-rangeRX, rangeRX)
        randomRY = rnd.randint (-rangeRY, rangeRY)
        randomRZ = rnd.randint (-rangeRZ, rangeRZ)
        mc.setAttr(obj + ".translateX", randomTX)
        mc.setAttr(obj + ".translateY", randomTY)
        mc.setAttr(obj + ".translateZ", randomTZ)
        mc.setAttr(obj + ".rotateX", randomRX)
        mc.setAttr(obj + ".rotateY", randomRY)
        mc.setAttr(obj + ".rotateZ", randomRZ)
       
#---------- While loop
import maya.cmds as mc

startFrame = mc.playbackOptions(query=True, minTime=True)
endFrame = mc.playbackOptions(query=True, maxTime=True)
currentFrame = startFrame
while (currentFrame < endFrame) :
    print " The frame is currently at %d" % currentFrame
    currentFrame += 1
    #break # use break to make sure to not brake maya
# out of loop

#------------- bake animation to another obj
import maya.cmds as mc

startFrame = mc.playbackOptions(query=True, minTime=True)
endFrame = mc.playbackOptions(query=True, maxTime=True)
currentFrame = startFrame

goal = "pSphere1"
follower = "pSphere2"


while (currentFrame < endFrame) :
    print " The frame is currently at %d" % currentFrame
    goalTrans = mc.getAttr(goal + ".translate")
    #mc.setAttr(follower+".translate",goalTrans[0][0],goalTrans[0][1],goalTrans[0][2])
    mc.setKeyframe(follower, at="translateX", v=goalTrans[0][0])
    mc.setKeyframe(follower, at="translateY", v=goalTrans[0][1])
    mc.setKeyframe(follower, at="translateZ", v=goalTrans[0][2])
    mc.currentTime(currentFrame)
    currentFrame += 1
   
# ------------------------ motion trail sowrds
# python expression
import maya.cmds as mc

def lag(frame,goal,follower,lagAmount):
    goalTrans = mc.getAttr(goal + ".translate",t=frame-lagAmount)
    goalRot = mc.getAttr(goal + ".rotate",t=frame-lagAmount)
    mc.setAttr(follower+".translate",goalTrans[0][0],goalTrans[0][1],goalTrans[0][2])
    mc.setAttr(follower+".rotate",goalRot[0][0],goalRot[0][1],goalRot[0][2])
#mel command
#python("lag(" + frame +", 'swordGoal','sword1',1)");

#--------------------------------------- MAYAPI.EXE

Python 2.4.3 (#69, Jul 13 2006, 15:36:15) [MSC v.1400 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print " the number is 32"
 the number is 32
>>> import maya.standalone
>>> maya.standalone.initialize()
>>> import maya.cmds as mc
>>> mc.polyCube()
[u'pCube1', u'polyCube1']
>>> mc.file(rename="C:\\cube.ma")
u'C:\\cube.ma'
>>> mc.file(rename="C:\cube.ma")
u'C:\\cube.ma'
>>> mc.file(rename="C:/cube.ma")
u'C:/cube.ma'
>>> mc.file(save=True)
u'C:/cube.ma'
>>>
   
 override standard methods with maya cmds
 
class bone:
def __init__(self,bone):
self.bone=cmd.joint(n=bone)
cmd.select(cl=True)
return


def __radd__(self,other):

                '''
                    override the + add function
                '''
cmd.parent(self.bone,other.bone)
return other.bone



def setName(self,newName):
'''
set bone name
'''
self.bone=newName
return cmd.rename(self.bone,newName)


def getName(self):
'''
get bone name
'''
return self.bone


def setPos(self,pos):
'''
set local space position
'''
return cmd.xform(self.bone,ws=False,t=pos)


def getPos(self):
'''
get local space position
'''
return cmd.xform(self.bone,q=True,ws=False)


def setWPos(self,pos):
'''
set world space position
'''
return cmd.xform(self.bone,ws=True,t=pos)


def getWPos(self):
'''
get world space position
'''
return cmd.xform(self.bone,q=True,ws=True)

b1=bone("osso0")
b2=bone("osso1")

b1+b2
http://www.koders.com/                  a nice bank of open sources c++ / python files  
import maya.cmds as cmds
class testW:
butts=["uno","due","tre","quattro","cinque","sei"]
def gui(self):
w=cmds.window("testwin")
c=cmds.columnLayout(adj=True)
self.doButtons(c)
cmds.showWindow(w)

def doButtons(self,parentC):
def runCbut(arg1):
return lambda x: self.bCommand(arg1)

for b in self.butts:
cmds.button(b,c=runCbut(b),parent=parentC)

def bCommand(self,txt):
oldName=txt+"_firstTime"
newName=txt+"_renamed"
if cmds.objExists(oldName):
cmds.rename(oldName,newName)
else:
cmds.sphere(n=oldName)

ww=testW()
ww.gui()
 
 
this is a simple example that show how to use python to build maya interfaces
with lambda (to defer the evaluation)
Labels: Python Source Codes
import maya.cmds as mc

def mainScriptMethod():
    #Check to see if the window exists
    if mc.window("mainScriptMethodWindow", q=True, ex=True):
    mc.deleteUI("mainScriptMethodWindow")

Note that in MEL, this is much more direct and clear:

if (`window -q -ex mainScriptMethodWindow`) {
// Do something
}
 

In Python: selectedObjects = mc.ls(sl=True)
In MEL: string $selectedObjects[] = `ls -sl`;
to import module from  sub folder just put a __init__.py file into the folder
example:

----------------------------------
mainScript.py

folder
       |
    __init__.py
    themodule.py
----------------------------------

into the script use this syntax to import the module
import folder.themodule.py
Labels: Python Notes
Maya Python API

/opt/aw/maya8.5.1/devkit/plug-ins/scripted
 location of all the Python scripted plugins for Maya
Labels: Python Source Codes
Books

Python Essential Reference - Google Book
books.google.co.uk/books?id=kQom0WiUbZQC
The content on this page is provided by a Google Notebook user, and Google assumes no responsibility for this content.