Search code examples
pythonmaya

Get texture filename from Maya python script?


I'm writing a python script to output a scene to a simple, readable file.

I've successfully outputted the position, rotation, scale and mesh name, but how do I get the filename of the texture that is applied to a mesh?

import maya.cmds as cmds
meshesWithoutShape = []
meshes = cmds.ls("mesh_*")
for mesh in meshes:
    if("Shape" not in mesh):
        meshesWithoutShape.append(mesh)

shapesInSel = cmds.ls(dag=1,o=1,s=1)
shadingGrps = cmds.listConnections(shapesInSel,type='shadingEngine')
shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1)
fileNode = cmds.listConnections('%s.color' % (shaders[0]), type='file')
currentFile = cmds.getAttr("%s.fileTextureName" % fileNode[0])

for mesh in meshesWithoutShape:
    print("\n" + mesh.rstrip('1234567890'))

    print round(cmds.getAttr("%s.translateX" % mesh), 2), round(cmds.getAttr("%s.translateY" % mesh), 2), round(cmds.getAttr("%s.translateZ" % mesh), 2)

    print cmds.getAttr("%s.rotateX" % mesh), cmds.getAttr("%s.rotateY" % mesh), cmds.getAttr("%s.rotateZ" % mesh)

    print cmds.getAttr("%s.scaleX" % mesh), cmds.getAttr("%s.scaleY" % mesh), cmds.getAttr("%s.scaleZ" % mesh)

    fileNode = cmds.listConnections('%s.color' % (shaders[0]), type='file')
    currentFile = cmds.getAttr("%s.fileTextureName" % fileNode[0])
    print currentFile

Solution

  • You can use ls to list all file nodes and get texture path ?

    allFileNodes = cmds.ls(et="file")
    for eachFile in allFileNodes:
        currentFile = cmds.getAttr("%s.fileTextureName" % eachFile)
    

    If you want to get if from selection or specific mesh

    shapesInSel = cmds.ls(dag=1,o=1,s=1,sl=1)
    shadingGrps = cmds.listConnections(shapesInSel,type='shadingEngine')
    shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1)
    fileNode = cmds.listConnections('%s.color' % (shaders[0]), type='file')
    currentFile = cmds.getAttr("%s.fileTextureName" % fileNode[0])
    

    Update

    Here is the code you want to work with your needs

    import maya.cmds as cmds
    meshesWithoutShape = []
    meshes = cmds.ls("mesh_*", tr = True)
    
    for mesh in meshes:
        print("\n" + mesh.rstrip('1234567890'))
    
        print round(cmds.getAttr("%s.translateX" % mesh), 2), round(cmds.getAttr("%s.translateY" % mesh), 2), round(cmds.getAttr("%s.translateZ" % mesh), 2)
    
        print cmds.getAttr("%s.rotateX" % mesh), cmds.getAttr("%s.rotateY" % mesh), cmds.getAttr("%s.rotateZ" % mesh)
    
        print cmds.getAttr("%s.scaleX" % mesh), cmds.getAttr("%s.scaleY" % mesh), cmds.getAttr("%s.scaleZ" % mesh)
        shadingGrps = cmds.listConnections(mesh,type='shadingEngine')
        shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1)
        fileNode = cmds.listConnections('%s.color' % (shaders[0]), type='file')
        currentFile = cmds.getAttr("%s.fileTextureName" % fileNode[0])
        print currentFile