stolik
stolik

Reputation: 11

Dynamically load custom modules

I have simple app in python to visual fx (pygame). I want load my custom modules in this app. Each module have custom vfx.

struct of app:

app:
|
-main.py
-config.py
-modules
  |
  -01
    |
    -module.py
    -assets
  -02
    |
    -module.py
    -assets
  -XX
    |
    -module.py
    -assets

in module.py i have:

    #import libs

def loadModules():
    dir = []
    list = os.listdir("modules")
    for d in list:
        path = os.path.abspath("modules") + os.sep + d
        if os.path.isdir(path) and os.path.exists(path + os.sep + "module.py"):
            dir.append(path + os.sep + "module.py")
    return dir
#init pygame & create scene
i = 0
while true
    #scene()
    sys.path.append(loadModules()[0])
    mod = importlib.import_module("module", __name__)
    mod.draw(scene)
    #print(plugin)
    sys.path.remove(plugin)

    if(i > 10):
         sys.path.append(loadPlugins()[1])
         mod = importlib.import_module("module", __name__)
         mod.draw(scene)
         #print(plugin)
         sys.path.remove(plugin)

    i += 1

Each module.py in modules i have method

draw()

to create visualisations

How can i load dynamic few module witch standard same name method draw() ? In this solution the first module is loaded only, next module, in next dir 02 is not loaded.

Upvotes: 1

Views: 66

Answers (2)

stolik
stolik

Reputation: 11

Ok, but now load only one module, not all. What am I doing wrong? Check this -> screen

edit:

I found a deprecated solution:

for dir in loadModules():
    print(dir)
    imp.load_source('module', dir)
    import module
    module.draw()

Upvotes: 0

match
match

Reputation: 11070

loadModules()[0] will always return the first item of the dir which will always be 01.

Rather than doing while True instead loop over all the entries in loadModules():

for dir in loadModules():
    sys.path.append(dir)
    mod = importlib.import_module("module", __name__)
    mod.draw(scene)
    sys.path.remove(dir)

Upvotes: 1

Related Questions