Running Python scripts outside a Maya session

You can run Python scripts that use Maya Python modules from standalone Python interpreters such as mayapy. However, when you run a Python script from outside a Maya session using either mayapy or another external interpreter, you will need to import and initialize the Maya Python libraries before you can use the Maya Python modules and APIs. This will load the libraries, check out licenses, and initialize graph states.

import maya.standalone 
maya.standalone.initialize()

Before your script exits, call maya.standalone.uninitialize(). This will return licenses, unload the Maya libraries, and close the Maya session.

For example:

import maya.standalone
maya.standalone.initialize()

import maya.cmds

# script body

maya.standalone.uninitialize()
Note:

Calling initialize() and uninitialize() from within a Maya process, whether through the script editor or a batch process, will generate an error because the Maya Python libraries are automatically loaded and initialized within a Maya process. If your Python script will be called either from within Maya or from within an external interpreter, you will need to enclose the calls to initialize() and uninitialize() within try blocks:

try:
  import maya.standalone
  maya.standalone.initialize()
except:
  pass

try:
  maya.standalone.uninitialize()
except:
  pass