Cmds not defined when imported and used a function, but works inside Maya


I recently started studying Python for Maya, and today found this website while looking for help,
it’s my first post and I couldn’t find any similar topic or if I did they did not help me find a solution, I apologize if it is an easy problem to fix and I could have found the solution somewhere I didn’t check

Following a tutorial I’m making a simple object renamed,
when i run it like this in Maya, it works perfectly:
def Rename () :

selection = = True)

if len(selection) == 0:

    selection = = True, long = True)


selection.sort(key=len, reverse = True)

for obj in selection:

    shortName =(obj.split("|")[-1])

    children = maya.cmds.listRelatives(obj, children=True, fullPath=True) or []


    if len(children)== 1:

        child = children[0]

        objType = maya.cmds.objectType(child)


        objType = maya.cmds.objectType(obj)


    if objType == "mesh" :

        suffix = "geo"

    elif objType == "joint" :

        suffix = "jnt"

    elif objType == "nurbsCurve" :

        suffix = "nCurve"

    elif objType == "locator" :

        suffix = "lcr"

    elif objType == "camera" :

        suffix = "Skipping Camera"



        suffix = "grp"


    newName = shortName + "_" + suffix


    maya.cmds.rename(obj, newName)

but when i try to import it and run the rename function I get the error “… cmds not defined”

I tried adding “import maya.cmds as cmds” at the beginning of my py file, or in maya before importing, but the issue stays, any idea why?

thanks for the help

Here I was just about to type a reply asking for your code, and you edited just as I started typing. Good call! Also, welcome!

Luckily, this one’s pretty easy. You’re using the “word” maya.cmds in your function.
But doing import maya.cmds as cmds only defines the word cmds

So, you could either define maya.cmds by using the import line import maya.cmds at the top of your file.
You could change all of the places where it says maya.cmds in your file to just cmds and use the import line import maya.cmds as cmds at the top of your file

I would personally do the second one, because that’s just kind of the standard.

[EDIT] Also, you should definitely make sure that your equivalent of History → Show Stack Trace is checked in your script editor. It tells maya to show all the parts of an error, and it really helps with fixing bugs.


it worked! I used the second solution as you recommended, I didn’t expect to receive an answer so fast, thanks a lot for the help, I also activated stack trace for any other time I’ll ask for help.

thank you for the warm welcome