Thursday, September 20, 2012

Using MEL to call multiple parameter Python function

Here are some tips I wrote for using mel's python command to call a multiple parameter python function, it may come in handy for things like using a mel based user interface but then calling a python function on a button click. Hope the ideas are helpful.


//and to use in mel, source test.mel, something like
mel_foo("Great Day",{"It","Compiled","Okay"});

mel_foo("Great Day",{"It","Compiled","Okay"});
Great Day
['It', 'Compiled', 'Okay']
import maya.cmds as cmds

def foo( arg1 = '', arg2 = [] ):
    print arg1
    print arg2

//with something like these three MEL utilities
//return string, pad(string) this changes a string--  a to  'a'
global proc string pad(string $arg)
 return ("'"+$arg+"'");
//return string[], padArray(string[]) this changes a string[]--  {a} to  {'a'}
global proc string[] padArray(string $arg[])
 string $result[] = {};
 for($i = 0; $i < size($arg); $i++ ){ $result[size($result)] = pad($arg[$i]); }
 return $result;
//return string, arrayToPyList(string[]) this changes a string []--  {"a","b"}  to "['a', 'b']"
global proc string arrayToPyList(string $arg[])
 return "["+stringArrayToString($arg,",")+"]";

//we can have something like
global proc mel_foo (string $a, string $array[] )
 string $pyModule = "testPy";
 //this is the python function we want to call
 string $def = "foo";

 //call a python command from mel
 //It helps us find the def foo .. see below
 string $importCmd = "from "+$pyModule+" "+"import "+$def;
 python $importCmd;

 //making arguments in a form that python can use
 string $aPadded = pad($a);
 string $arrayPadded[] = padArray($array);

 //there are quite a few pluses here 
 //but the pluses are just gluing the string together
 //to get something like
 //foo( 'a', ['b1','b2',…] )
 string $pyCmd = $def+" "+"("+

 python $pyCmd;