1

我需要制作一个脚本来调用特定目录中的每个 .py 文件。这些是主程序的插件。每个插件脚本必须能够从调用脚本访问类和方法。

所以我有这样的事情:

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()

我希望能够在callee.py

myMain.callMe()

仅使用是import行不通的,因为mainfile.py必须是正在运行的程序,callee.py可以删除并mainfile自行运行。

4

1 回答 1

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()

使用此代码,您应该能够调用callMe当前目录中任何 python 文件的函数。并且该函数将可以访问MainClass,因为我们将它作为参数传递给callMe

注意:如果你在 callee.py's中调用callMeof ,会产生无限递归,你会得到MainClasscallMe

RuntimeError: maximum recursion depth exceeded

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

于 2013-10-21T03:40:37.767 回答