Initializing and uninitializing in Python

Before using Maya Python from within mayapy or another external Python interpreter, you will need to load and initialize the Maya libraries in the interpreter.

Use import maya.standalone to load the libraries in the interpreter, and initialize() to initialize them:

import maya.standalone 
maya.standalone.initialize()
You will not need to call initialize() if you are running a script from within the Maya script editor. This is because the Maya libraries are automatically loaded and initialized in the script editor. Calling initialize() from within the script editor will generate an error. If you are writing a script that may be called from within the Maya script editor or from within an external interpreter, you will need to enclose the call to initialize() within a try block.
try: 			
    import maya.standalone 			
    maya.standalone.initialize() 		
except: 			
    pass

This will safely catch the error generated from calling initialize() from within the script editor.

Your script should call maya.standalone.uninitialize() before it exits. This will terminate the script's connection to Maya cleanly. The call to uninitialize() will also fail in the script editor. It should also be enclosed in a try block.
try: 			
    maya.standalone.uninitialize() 		
except: 			
    pass