2013-03-05 69 views
0

我正在使用我的Auto-Rig腳本,並注意到代碼越來越長,難以閱讀並專注於一部分。我正在考慮導入一個python文件並調用導入的python文件中的函數。似乎無法找到一種方法來導入文件可以有人幫助我。將python導入pymel

+1

寫thefile.py,然後在你的腳本'進口thefile'。使用函數調用'thefile.afunction()' – joaquin 2013-03-05 07:52:05

+0

最好的方法是花一些時間閱讀關於[繼承,私有變量和類本地引用] [1]的Python文檔,它的基本理解是任何「對象」 oop語言應該有一個數據和行爲, [1]:https://docs.python.org/2/tutorial/classes.html – 2016-09-11 21:08:14

回答

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`; 
0

寫你希望你的模塊作爲一個Python文件中所包含的功能。 (提示:不要用數字啓動你的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) 

你的模塊就可以進口。

現在叫myFunc1()myModule

myModule.myFunc1()

這會給輸出:

myFunc1 is called

現在我們調用myFunc2()myModule

myModule.myFunc2()

這會給輸出:

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

我們只需要運行上面相同的代碼來重新加載更新:

myFunc2 is called

如果我們現在有一個新的功能更新我們的myModule.py模塊。

現在,我們可以嘗試聲明:

myModule.myFunc3()

...並得到如下的輸出:

myFunc3 is called