Search code examples
pythonmayapymel

maya.cmds Dialog to end script


I would like to end an entire script once an attribute has not been found. Currently, I have the following code. I display a dialog and use sys.exit() to end the script but I m wondering if there is a cmds dialog that does this automatically for you without sys.exit(),

def check_attr(attr):
    if not cmds.select(cmds.ls(attr)):
         cmds.confirmDialog(title= 'Attribute not found   ', message = attr+' attribute was not found', button =['OK'])
         sys.exit()

My question: Does a cmds...Dialog that stops a script exist?


Solution

  • Since you're using a function the easiest way would be to use return in your if condition so that it never continues the rest of the function:

    def check_attr(attr):
        if not cmds.select(cmds.ls(attr)):
             cmds.confirmDialog(title= 'Attribute not found   ', message = attr+' attribute was not found', button =['OK'])
             return
    
        print "Continuing script"
    
    
    check_attr("someAttr")
    

    You can also use OpenMaya.MGlobal.displayError to display it in Maya's taskbar:

    import maya.OpenMaya as OpenMaya
    
    
    def check_attr(attr):
        if not cmds.select(cmds.ls(attr)):
             OpenMaya.MGlobal.displayError(attr + ' attribute was not found')
             return
    
        print "Continuing script"
    
    
    check_attr("attr")
    

    Though be careful since OpenMaya.MGlobal.displayError simply displays an error, it doesn't stop execution like cmds.error. You could use cmds.error too, but I find that the error it spits out in the taskbar is a lot less readable.