Tuesday, September 2, 2008

Finally: Python can talk to Maya

I work in the the software package Maya, by Autodesk. As of version 'Maya 2008', they put Python scripting in Maya, to augment it's built-in scripting language, MEL. This is great, but Maya's 'Script Editor' leaves a LOT to be desired when it comes to authoring Python code. I've been using an external IDE called 'Wing Professional' to do my Python coding. And I knew that Wing had the ability to ouput what one was executing to a network socket. And I knew that Maya could open a socket. Problem was, the socket that Maya's mel command 'commandPort' open expects MEL commands, not Python commands. You could jump through some wrapper hoops to get them to talk, but I didn't care for it.
Enter Python's 'exec' command: It allows you to execute a module on disk as if it was interactively entered. So I came up with a plan:
  • In Wing, I have a script bound to a hot-key: It takes what the user has highlighted, and saves it off to a temp text file on disk. It then (through a socket) pings Maya, and tells it to evaluate that code.
  • When Maya launches it opens up a socket. Then when it gets the call from Python to do work, it finds the temp file, and runs 'exec' on it, and also prints the contents for the user.
This worked great, but one problem: Any variables defined during the execution were local to the execution. After execution was over, they were out of the scope of any other code. I tracked down that 'exec' had args that let you pass in a dictionary defining a certain variable scope. By passing in Python's base '__main__.__dict__' , I was able to add all the declared variables into that root scope, making them visible to all other interactive coding sessions.
FINALLY, Python can talk to Maya ;) I documented the whole thing (with code) on my Mel Wiki HERE.

No comments: