Help! Python doesnt work for me

Hi guys

I'm new to Python in Maya, however i know some Max and Mel script so...not a complete noob

anyways lately i have decided to learn python for my job as a rigger and td. I am following a tutorial called Building UI's with python by Jeremy Ernst.

I have followed his script word by word to make sure there isn't any typos or unnecessary white spaces. i save the script in documents/maya/scripts file. when i open Maya i toggle from Mel to Maya and try to use an import cmds script in the python tab of the script editor, I then hit execute

Nothing! in the video a UI is supposed to pop up in the view port??

So i figure the tutorial is using an older version of Maya to me, so i download the older 2011 Maya trial, follow the steps again

still nothing? i try to find any thing that should be turned on in the plugin editor? then i check to make sure i am loading the python shell grabbing the latest 3.3 version. i have goggled all over to see if the issue can be resolved?

That's pretty much the situation at the present, any body having same problem or knows how i can resolve this?
please don't hesitate to reply.

cheers.
Joe

___________________________________________________________________________________________________________________
THE CODE

import maya.cmds as cmds

def UI():

    #check to see if your window exists
    if cmds.window("exampleUI", exists = True):
        cmds.deleteUI("exampleUI")

        #create our window
        window = cmds.window("exampleUI", title = "Example UI", w = 300, h = 300, mnb = False, mxb = False, sizeable = False)

        #show window
        cmds.showWindow(window)

SCRIPT EDITOR MAYA

import exampleUI
reload(exampleUI)

exampleUI.UI()

check your line 'if cmds.window("exampleUI", exists=True)' it's expecting the window to already exist, therefore it will never run the window build statements. Change it to 'exists=False' and it will work fine.

Also, whenever you run into something like this, I would copy the function and throw it into the script editor, and instead of running 'exampleUI.UI()' just run 'UI()'. Especially when you begin to learn Python in maya, the path's, aliases, sourcing and reloading of scripts can be quite confusing, since it's all happening in the background. Whenever you're unsure if something's loaded, type help(insertFunctionNameHere).

Good luck man, Python surely has been the most rewarding thing I've ever learnt in Maya. 

tokyopancake ,oh dude thank you so much
it worked!
Yippie!
you are awesome, also i have been to tokyo and so are the pancakes :smiley:

Joe

Cheers mate, let me know if you need any more help!

actually im trying to create a character tab UI following the next tutorial of Jeremy Ernst's series

heres the code

__________________________________________________________________________________________

import maya.cmds as cmds

widgets = {}

def UI():

    if cmds.window("tabTest", exists = True):
        cmds.deleteUI("tabTest")

    widgets["window"] = cmds.window("tabTest", title = "Character Tabs Test", w = 400, h = 600, mxb = False, mnb = False)
    mainLayout = cmds.columnLayout(w = 400, h = 600)
    widgets["tablayout"] = cmds.tabLayout(imw = 5, imh = 5)

    #find all the character namespaces in the scene create UI for each
    findNameSpaces()

    cmds.showWindow(widgets["window"])

def findNameSpaces():

    import maya.cmds as cmds

    cmds.namespace(setNamespace = ":")

    namespaces = cmds.namespaceInfo(listOnlyNamespaces = True)

    for namespace in namespaces:
        if cmds.objExists(namespace + ":*"):

            #create a tab
            widgets[(namespace + "_tab")] = cmds.columnLayout(w = 400, h = 600, parent = widgets["tabLayout"])

            #edit the tab name
            cmds.tabLayout(widgets["tabLayout"], edit = True, tabLabel = (widgets[(namespace + "_tab")], namespace))
________________________________________________________________________________________________________________

what is happening is it isnt displaying the names spaces i have created
its just a grey box with nothing inside it :frowning:

thank you Tokyopancake
"also if there is any really imformative UI python building tutorials you know of please send me a link"
cheers.
Joe

this is what it is suppose to look like,

i have also noticed the code namespaces next to print the tag changes to green in the script editor
______________________________________________________________________________
import maya.cmds as cmds

cmds.namespace(setNamespace = ":")

namespaces = cmds.nameSpacesInfo(listOnlyNamespaces = True)

for namespace in namespaces:
    if cmds.objExists(namespace + ":*):
        print namespace
______________________________________________________________________________
perhaps this is because its a newer version?
im using maya 2014

First off, in order for these tabs to appear you'll need a namespaced object in your scene, if there's no namespaced objects, you'll get no tabs, but I bet you knew this already.

However, I did find an error in your script, it's the spelling of 'tabLayout' as a dictionary key for your widget dictionary. You initialize it as 'tablayout' and then call for it later as 'tabLayout'. If you have a namespaced object in your scene you'll see an error come up.

I always do Rubber Duck Debugging, it's the best way to find errors, also it's really hip and happening to talk to rubber ducks these days!
http://en.wikipedia.org/wiki/Rubber\_duck\_debugging 

ok its a little odd but i have noticed that when Jeremy types his namespace tag his stays white text in the script editor, however in my version it is green, so could this be it be it??

The tab still doesnt work after making those suggested changes, learning alot through trial and error though :wink:
Cheers again for the help

Jeremy's screen is different in the script editor

Nah, when it turns Blue, it means maya found it to be a maya command, I can see in Jeremy's one first off it turns blue, and second time around it stays white... honestly this shouldn't be a problem for your script. However I do see that when Jeremy runs his script it prints the three Namespaces found: as far as I can tell Bob, Jack and Jane, however in your scripteditor it doesn't print back anything, which means there are no namespaces found, this would be the reason your tabs don't show up.

About the coloring of your variables however, I always revert to specifically naming my variables not to conflict with maya, although this shouldn't be a biggie, it's still a safe thing. I generally tag stuff like 'object' as 'myObject' and when I go into a for loop I call stuff 'thisObject' as in..

for thisObject in myObjectList:
    print thisObject.

P.S. the difference in colouring could be a maya version thing. 

thanks once again Tokyopancake. and good explanation :slight_smile:

there are namespaces i made with the namespace editor called bob,jack and jame. also nulls named the same with null at the end so "Bobnull" Jeremy uses them as hypothetical rig names. 
i will try the change of the variable. hopefully this fixes it. 
will keep you posted. cheers again 

yeah I would rewrite your script like:

import maya.cmds as mc
 
mc.namespace(setNamespace = ':')
 
allNamespaces = mc.namespaceInfo(listOnlyNamespaces=True)
 
for myNamespace in allNamespaces:
	if mc.objExists(myNamespace + ':*'):
		print myNamespace

Also while we're at it, I would advise to learn about string formatting in python. in MEL, you concaternate strings with the + operator. as in 'myObjectName' + '.' + 'myAttribute'. This also works in Python, but you can get a lot cleaner and readable code by learning the string formatting way.
The same example would be like this: '%s.%s' % (myObjectName, myAttribute), or if you only are formatting 1 variable into the string '%s' % myObjectName. Basically what it's doing is replacing the %s with the variables you provide. So in the example in your script, I would change:
    myNamespace + ':*'
into
    '%s:*' % myNamespace

I know this can be a bit confusing at first, but I wish I learned this when I started out with Python, so I tell you now :slight_smile:

If it's still not working, maybe post a screenshot of your outliner where the namespace objects are visible. 

Hey Tokyopancake "mmmmm"
thanks again for the feedback

Yeah i just tried that, used the code you gave me, "no worky :(" , i use mc sometimes instead of cmds but maya commands i am doing because the tutorial is using that tag.
also the print isnt printing the name spaces :frowning:

not sure perhaps it this version, does it work on your end? can you test on your version?

cheers
Joe

heres the screen shot you requested :slight_smile:

What seems to be going wrong is you've created your namespaces Bob, Jack and Jane. These namespaces now 'live' in your scene, apparently. But your script is asking wether there's an object associated with the namespace. I haven't used the namespace editor much, since I only use namespaces on Importing and Referencing, but you can assign objects to a namespace by clicking 'Bob' in your namespaceEditor, then selecting your null in your viewport, and you click 'Add Selected' in the namespaceEditor.

As far as I can tell from the screenshot your nulls are named Bobnull, Jacknull,... but if they had the namespace assigned, they should be called Bob:Bobnull, Jack:Jacknull. When I try it this way, it works on my end, and it should for you!

Hope it works now mate :slight_smile: 

It did thank you so much, Tokyopancake you are the man
but anyways it works time to do the rest of these tutorials :slight_smile:

wow i was wrapped once i got it working, but yet again another road block.
It worked and soon as i added variables for translate,rotate and scale??

thanks i have almost got through this first video haha
anyways heres the code
_________________________________________________________________
import maya.cmds as cmds

widgets = {}

def UI():

    if cmds.window("tabTest", exists = True):
        cmds.deleteUI("tabTest")

    widgets["window"] = cmds.window("tabTest", title = "Character Tabs Test", w = 400, h = 600, mxb = False, mnb = False)
    mainLayout = cmds.columnLayout(w = 400, h = 600)

    widgets["tabLayout"] = cmds.tabLayout(imw = 5, imh = 5)

    #find all the character namespaces in the scene create UI for each
    findNameSpaces()

    cmds.showWindow(widgets["window"])

def findNameSpaces():

    cmds.namespace(setNamespace = ":")
    namespaces = cmds.namespaceInfo(listOnlyNamespaces = True)

    for namespace in namespaces:
        if cmds.objExists(namespace + ":*"):

            #create a tab
            widgets[(namespace + "_tab")] = cmds.columnLayout(w = 400, h = 600, parent = widgets["tabLayout"])

            #create attr field grps for translate rotate and scale
            cmds.separator(h = 10, style = "none")

            widgets[(namespace + "_attrFG_T")] = cmds.attrFieldGrp(attribute = (namespace + ":null.translate"))
            widgets[(namespace + "_attrFG_R")] = cmds.attrFieldGrp(attribute = (namespace + ":null.rotate"))
            widgets[(namespace + "_attrFG_S")] = cmds.attrFieldGrp(attribute = (namespace + ":null.scale"))

            #edit the tab name
            cmds.tabLayout(widgets["tabLayout"], edit = True, tabLabel = (widgets[(namespace + "_tab")], namespace))
_____________________________________________________________________________________________________
error from script editor

 Error: Could not find vector attribute named Bob:null.translate.
# Traceback (most recent call last):
#   File "", line 3, in
#   File "C:/Users/Jason/Documents/maya/scripts\tabTest.py", line 18, in UI
#     findNameSpaces()
#   File "C:/Users/Jason/Documents/maya/scripts\tabTest.py", line 39, in findNameSpaces
#     widgets[(namespace + "_attrFG_T")] = cmds.attrFieldGrp(attribute = (namespace + ":null.translate"))
# RuntimeError: Could not find vector attribute named Bob:null.translate. #

_____________________________________________________________________________________________________
Cheers
Joe

the nulls have changed to Bob:Bobnull
                                          Jack:Jacknull
                                          Jane:Janenull

could this be it?

i already tried running a partition to see if i could only count after the ":."

cheers Tokyopancake

im really enjoying python, after this tutorial im going to concider doing a crash course in python :slight_smile:

Best.
Jason

Yeah that's it. Your script is calling for Bob:null.translate, but there's no object in your scene called null, only Bobnull and Jacknull.

try this:

if mc.objExists('Bob:null'):
	print 'awesome, your script was fine'
else:
	print '\n\n\n\n', 'jason needs to do some rubber ducky debugging'.upper()

 let me know what it says :stuck_out_tongue:

Thankyou Tokyopancake

the thing im finding is the code needs to find all the namespaces, not specific names like Bob:Bobnull, is there away to say select with the name null after the Bob: part the way i was trying. was using a list [(":":null"[1])] using cmds.partition.

what i would like to aim for is to be able to create new name spaces and for the script to automatically update and add a tab list for the name space.

"https://vimeo.com/43948657" this is what im following :slight_smile:

about rubber ducky, what is it, how can i get started?
i want to learn :wink:

Cheers.
Joe

Yeah from what I understand though, you would want a tab to be created for every namespace in your scene that has an object attached.. But you need to create a new attribute field for every object inside that namespace..

Personally finding all the namespaces etc, I would do without too many maya commands, since the ':' is a protected string character specifically assigned for namespaces in Maya, you could use simple string queries. Have a look in the example below, I'm going through all the dagnodes in the scene, and splitting their stringName with the .split() method...

allNodes = mc.ls(dag=True)
 
namespaceDict = {}
 
for item in allNodes:
    # see if object has a namespace
    if ':' in item:
        # split found namespaced-object into a namespace and an object name.
        thisNamespace, thisObject = item.split(':')
 
        # make sure that namespace is a key in the namespaceDictionary
        if thisNamespace not in namespaceDict:
            namespaceDict[thisNamespace] = []
 
        # check if this object has a parent, if NOT, it means it's parented to the world
        # and we are good to go.
        thisParent = mc.listConnections(item, p=True)
        if thisParent==None:
            # add this world object to the dictionary.
            namespaceDict[thisNamespace].append(thisObject)
 
 
 
allNamespaces = namespaceDict.keys() # see all the keys (namespaces in this case in the dictionary
for thisNamespace in allNamespaces:
    objsInNamespace = namespaceDict[thisNamespace]
    for thisObject in objsInNamespace:
        print 'this object is:', '%s:%s' % (thisNamespace, thisObject)

I would then use the dictionary to first off create the tabs in your interface, by querying the .keys(), and then create attrFieldT, R, S, for every single item in that dictionaryKey > objectList = thisDict[thisKey]

Thanks for the video, I'll have a look into it, I should brush up on my interface stuff :slight_smile:
Rubber Ducky Debugging is the act of explaining what you are trying to code to a rubber ducky, if you can explain it to a rubber ducky you can figure out if it's actually making sense... You can also do this by commenting your scripts in a lot of psuedo code, like the example above, the moment your comments start to become unclear and like an acid trip, is the moment you know problems start to arrise :slight_smile: