一半君的总结纸

听话只听一半君

#78 如何得到当前正在运行的script的路径; 比如你想读取同一目录下的另一个文件的时候?

如果你的script里有 global procedures 那你可以用 whatIs command.

string $result = `whatIs myGlobalProc`;

不幸的是这返回结果的是下面的可读格式(human-readable form):

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

使用一个简单的 tokenize 就能得到结果了:

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

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

输出是:

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

注意: 如果你的路径或者文件名中包含空格,你就得自己把tokenize返回的array里的从第4个元素开始,一直拼接所有字符串直到最后,这样才能得到想要的路径.

你还得知道你得到的这个路径确实是一个 MEL script ,如果你whatIs一个 internal command,返回结果就不是路径了,例如:

whatIs sphere;
// Result: Command //

假设有下面的 script:

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

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

还有这个 whereIs MEL command:

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

    if ( `exists $procedure` )
    {
        // 使用 whatIs command 来找到位置.
        string $result = eval( "whatIs " + $procedure );

        // 解析可读形式的字符串.
        string $tokens[];
        int $numTokens = `tokenize $result " " $tokens`;

        // 确信这是一个 MEL script 而不是 internal command.
        if ( $tokens[0] == "Mel" )
        {
            // 如果有空格,就从第4个元素开始连接字符串.
            for ( $i = 4; $i < $numTokens; $i++ )
            {
                $where = $where + $tokens[$i];

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

    return $where;
}

使用举例:

source myScript;
Script being sourced is: D:/AW/Bryan/scripts/myScript.mel

myScript;
Procedure is running in script: D:/AW/Bryan/scripts/myScript.mel

加强版:

如果是python的话,当前运行的script的文件名在sys.argv[0]里,或者用__file__ 也可以

Related How-To’s

05 January 2002

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: