I'm new to Maya plug-in development and have a question regarding UI cleanup. I'm writing a plug-in that creates a new shelf (with various shelfButtons attached to external scripts). When the plug-in loads and unloads, I want to add or remove this shelf from the Maya UI. This is working without any issue. However, I also want to clear my plug-in shelf when Maya exits (if the plug-in is set to Auto-Load it will simply load again on restart...if Auto-Load is not set, I don't want the shelf to appear when Maya starts).
This should be possible by registering a callback (OpenMaya.MSceneMessage.kMayaExiting) during the 'initializePlugin' method. The following code works without any issues if I attach the callback to a different scene message (such as kAfterSave), but when I use kMayaExiting it doesn't remove the shelf. Strangely, if I do a quick print statement (on exit) to test if the shelf has been removed it appears to have removed it...but when I restart Maya the shelf appears once again (without loading the plugin). I'm not completely sure about the print statement either because the output flies by pretty quickly when Maya exits (is it possible to log the ScriptEditor text to a file when exiting?). Thanks for any help! I've been banging my head against this issue all day. 
import maya
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
fMayaExitingCB = None
# Remove the UI when Maya exits
def removeUI(clientData):
maya.cmds.setParent(maya.mel.eval("global string $gShelfTopLevel;$temp = $gShelfTopLevel"))
if maya.cmds.layout("TestPluginShelf", exists=True):
maya.cmds.deleteUI("TestPluginShelf", layout=True)
# Initialize the script plug-in
def initializePlugin(mobject):
mplugin = OpenMayaMPx.MFnPlugin(mobject, "TestPlugin", "1.0", "Any")
# Create shelf and buttons
maya.cmds.setParent(maya.mel.eval("global string $gShelfTopLevel;$temp = $gShelfTopLevel"))
if maya.cmds.layout("TestPluginShelf", exists=True) == False:
maya.cmds.shelfLayout("TestPluginShelf", style="textOnly")
maya.cmds.shelfButton(image1="scriptIcon.png",
label="script", annotation="externalScript",
command="import ExternalScript\nreload(ExternalScript)", sourceType="python")
# Add callback to clean up UI when Maya exits
global fMayaExitingCB
fMayaExitingCB = OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kMayaExiting, removeUI)
# Uninitialize the script plug-in
def uninitializePlugin(mobject):
mplugin = OpenMayaMPx.MFnPlugin(mobject)
# Cleanup the UI and remove the callback when plug-in is unloaded
maya.cmds.setParent(maya.mel.eval("global string $gShelfTopLevel;$temp = $gShelfTopLevel"))
if maya.cmds.layout("TestPluginShelf", exists=True):
maya.cmds.deleteUI("TestPluginShelf", layout=True)
global fMayaExitingCB
if (fMayaExitingCB != None):
OpenMaya.MSceneMessage.removeCallback(fMayaExitingCB)
Cheers,
Josiah