Posts Tagged ‘ commands.py

How does Maya populate its maya.cmds package?

From over on my Mel Wiki:

When using Python in Maya, to access the bulk of the mel commands via Python, you import the mel.cmds package, usually into a namespace, like so:

import maya.cmds as mc
print mc.ls()

But if you browse to that package on disk, you’ll find it empty, only containing an __init__.py file (required for package creation):

C:\Program Files\Autodesk\Maya<VERSION>\Python\Lib\site-packages\maya\cmds

So how are all the ‘mel commands’ added to that package for execution in Python?

There is a Maya startup Python module living here, that works the magic of populating that package:

C:\Program Files\Autodesk\Maya<VERSION>\Python\Lib\site-packages\maya\app\commands.py

It inspects a file called commandList (no extension, but it’s text) living here:

C:\Program Files\Autodesk\Maya<VERSION>\bin\commandList

You can open that file in a text editor, and what you’ll find are two columns: One with a ‘mel’ command name, and one with a .dll where that command ‘lives’. Those .dll’s live in the same dir as the commandList file. Here’s a sample:

TanimLayer AnimSlice.dll
about Shared.dll
addAttr Shared.dll
addDynamic DynSlice.dll
addPP DynSlice.dll
affectedNet Shared.dll
affects Shared.dll
agFormatIn Translators.dll
agFormatOut Translators.dll
aimConstraint AnimSlice.dll
air DynSlice.dll
aliasAttr Shared.dll
align Shared.dll

What commands.py does is parse the commandList file and append each command (via a Python command wrapper function) to maya.cmd‘s ‘__dict__‘ attribute (maya.cmds.__dict__), which is the lookup table users access when calling their favorite mel command via Python (like maya.cmds.ls())  It also passes the name of the .dll to the command wrapper function, so when the user executes the given command, it first loads the parental .dll.

Crack open commands.py for the nitty-gritty details.

If you want to see the end result of all this hard work, you can run this code in Maya. But it prints a *lot* of stuff:

import maya.cmds as mc

for k in sorted(mc.__dict__.keys()):
    print k, mc.__dict__[k]