在Pymel中导入Python

0 投票
2 回答
607 浏览
提问于 2025-04-17 17:57

我在做我的自动绑定脚本的时候,发现代码越来越长,读起来很费劲,难以专注于某一部分。我想把一个Python文件导入进来,然后调用里面的函数。但是我找不到导入这个文件的方法,有人能帮我吗?

2 个回答

0

把你想放进模块里的函数写成一个 Python 文件。(小提示:文件名不要以数字开头哦。)

在我的例子中,myModule.py 文件里包含了:

def myFunc1():
    print 'myFunc1 is called'
    pass

def myFunc2():    
    print 'myFunc2 is called'
    return

现在把这个文件保存在一个文件夹里。我的例子中,Python 文件的路径是:

d:\projects\python\myModule.py

接下来,在你的 Maya 会话脚本编辑器里输入:

import sys
import os

modulePath = os.path.realpath(r'd:\projects\python\myModule.py')
moduleName = 'myModule'

if modulePath not in sys.path:
    sys.path.append(modulePath)

try:
    reload(moduleName)
except:
    exec('import %s' % moduleName)

这样你的模块就应该被导入了。

现在从 myModule 调用 myFunc1()

myModule.myFunc1()

这会输出:

myFunc1 is called

接下来我们从 myModule 调用 myFunc2()

myModule.myFunc2()

这会输出:

myFunc2 is called

如果我们现在在 myModule.py 中添加一个新函数:

def myFunc3():    
        print 'myFunc3 is called'
        return

我们只需要运行上面的代码,就能重新加载更新后的模块。

现在我们可以尝试这个语句:

myModule.myFunc3()

... 然后会得到这个输出:

myFunc3 is called

1

我建议你把你的Python文件放到一个Python模块里,然后在MEL文件中这样引用:

python "import my_python_module";

string $pycommand = "my_python_module.my_function(param1, "+ $mel_string_param1 +",\"" + $mel_string_param2 + "\")";

string $result= `python $pycommand`;

撰写回答