Reputation: 687
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.
Upvotes: 1
Views: 137
Reputation: 239443
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.
Upvotes: 1