简体   繁体   中英

Python - Plugins to Main Program

I need to make a script that calls every .py file in a specific directory. These are plugins to the main program. Each plugin script must be able to access classes and methods from the calling script.

So I have something like this:

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

And I want to be able to do the following in callee.py

myMain.callMe()

Just using import will not work because mainfile.py must be the program that is running, callee.py can be removed and mainfile will run on its own.

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

With this code you should be able to call callMe function of any python file in the current directory. And that function will have access to MainClass , as we are passing it as a parameter to callMe .

Note: If you call callMe of MainClass inside callee.py's callMe , that will create infinite recursion and you will get

RuntimeError: maximum recursion depth exceeded

So, I hope you know what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM