2013-10-21 25 views
1

我需要調用特定目錄中的所有.py文件的腳本。這些是主程序的插件。每個插件腳本必須能夠從調用腳本訪問類和方法。Python的 - 插件主程序

所以我有這樣的事情:

mainfile.py

class MainClass: 
    def __init__(self): 
     self.myVar = "a variable" 

     for f in os.listdir(path): 
      if f.endswith(".py"): 
       execfile(path+f) 

    def callMe(self): 
     print self.myVar 

myMain = MainClass() 
myMain.callMe() 

而且我希望能夠做的只是使用import不會起作用,因爲在callee.py

myMain.callMe() 

以下mainfile.py必須是正在運行的程序,callee.py可以被刪除並且mainfile將自行運行。

+0

那麼'callee.py中的'mainfile import MainClass'怎麼樣? – yakiang

+0

@yakiang - 該代碼永遠不會執行,因爲'callee.py'不是主程序。 – functorial

+0

@ user2529202:你如何打開插件.py源文件?當使用標準的'import'模塊被執行,然後@yakiang解決方案是確定... – mguijarr

回答

1
import os 
class MainClass: 
    def __init__(self): 
     self.myVar = "a variable" 
     self.listOfLoadedModules = [] 

     for f in os.listdir("."): 
      fileName, extension = os.path.splitext(f) 
      if extension == ".py": 
       self.listOfLoadedModules.append(__import__(fileName)) 

    def callMe(self): 
     for currentModule in self.listOfLoadedModules: 
      currentModule.__dict__.get("callMe")(self) 

myMain = MainClass() 
myMain.callMe() 

有了這個代碼,你應該能夠調用任何Python文件的callMe功能在當前目錄。並且該函數將有權訪問MainClass,因爲我們將它作爲參數傳遞給callMe

注:如果你調用MainClasscallMe內callee.py的callMe,將創造無限循環,你會得到

RuntimeError: maximum recursion depth exceeded 

所以,我希望你知道你在做什麼。

+0

每當我嘗試做這樣的事情時,基本上每當我調用'__import__'時,它都會再次執行我的主腳本。我甚至做過'if extension ==「.py」和fileName!=「mainfile」'。 **編輯**沒關係,那是因爲我把'進口mainfile'在'callee.py' – functorial

+0

我們不需要導入它,因爲我們把它當作一個參數。 – thefourtheye