MEL How-To #78

Back · Previous · Next Maya

How do I determine the path for a script while it is executing; for example, to load another file in the same folder?

If you have any global procedures in the script you can track it with the whatIs command.

string $result = `whatIs myGlobalProc`;

Unfortunately this returns the human-readable form of:

Mel procedure found in: C:/AW/Maya4.0/scripts/others/myScript.mel

But a simple tokenize will yield the result:

string $tokens[];
tokenize $result " " $tokens;

print ( "My location is: " + $tokens[4] + "\n" );

The output:

My location is: C:/AW/Maya4.0/scripts/others/myScript.mel

Note: If your path or filename contain spaces you'll have to concatenate elements 4+ to get the complete path description.

You have to be careful that what you have found is in fact a MEL script and not an internal command. For example:

whatIs sphere;
// Result: Command //

Consider the following script:

global proc myScript()
{
    print ( "Procedure is running in script: " + whereIs( "myScript" ) + "\n" );
}

print ( "Script being sourced is: " + whereIs( "myScript" ) + "\n" );

And the whereIs MEL command:

global proc string whereIs( string $procedure )
{
    string $where = "";

    if ( `exists $procedure` )
    {
        // Use the whatIs command to determine the location.
        string $result = eval( "whatIs " + $procedure );

        // Parse the human-readable form.
        string $tokens[];
        int $numTokens = `tokenize $result " " $tokens`;

        // Make sure this is a MEL script and not an internal command.
        if ( $tokens[0] == "Mel" )
        {
            // Concatenate path if it contains spaces.
            for ( $i = 4; $i < $numTokens; $i++ )
            {
                $where = $where + $tokens[$i];

                if ( $i < $numTokens )
                {
                    $where = $where + " ";
                }
            }
        }
    }

    return $where;
}

Put them together:

source myScript;
Script being sourced is: D:/AW/Bryan/scripts/myScript.mel
myScript;
Procedure is running in script: D:/AW/Bryan/scripts/myScript.mel

Related How-To's

05 January 2002