Friday, 27 January 2012

Maya standalone python

I've just had an email from an ex student asking about automating the export process from maya as at present they load each scene by hand and then use a particular plugin to export in a new format.

My suggestion was to use the standalone maya python interpretor and try to semi automate the process, to do this I wrote a simple proof of concept as follows.

The following script scans the current directory for any maya ASCII files, opens the file and selects all. Then exports this as an obj file.

First we need to enable the maya standalone system

import maya.standalone
import maya.cmds as cmds
import os

maya.standalone.initialize(name='python')

The line above imports the maya.standalone module, next we need to initialise this and tell it which interpretor we are using with the name='python' command. We now have an empty maya environment which should have read our Maya.env so all the paths etc are setup. However none of our default auto-loaded plugins are loaded. In this case I wish to use the obj export plugin so need to load it. As this is a simple proof of concept I don't do any checking to make sure it is loaded etc.

cmds.loadPlugin("objExport")

The next batch of code scans the current directory and checks for .ma files then does the export
files = os.listdir(".")
for mayafile in files :
  if mayafile.endswith(".ma") :
    cmds.file(mayafile,o=True)
    cmds.select(all=True)
    newFile="%s.obj" %(mayafile)
    cmds.file(newFile,type="OBJexport",pr=True,es=True)

The rest of the code uses the standard maya.cmds module to first open the file then select all elements.

Next I create a new filename by adding ".obj" to the end of the file loaded and export with the file command.

To run the script we need to use the mayapy command. This should be in the same directory as the rest of the maya executables. On my mac this is /Applications/Autodesk/maya2011/Maya.app/Contents/bin/mayapy but you will need to add it to your path

To run I've saved the file as export.py and run mayapy export.py

No comments:

Post a comment