Casual
Casual

Reputation: 71

Import all modules from folder, execute function from all of them with known name

Well, I have pretty hard task and I'm completely stucked, like in any direction.

What program should do:

  1. Import all modules (names are random) from folder
  MainScript.py
  modules/
      mod1.py
      mod2.py
      mod3.py
      ...
  1. Execute specific (known name, and everywhere it's same) function.

mod1.main()
mod2.main()
mod3.main() ...

As I understand it, I should list all files in folder , then make list with them and for each [x] in list import module and execute script. I've found that modules[0].main() works only if modules[0] no string, so, it should be modules[0]=main not modules[0]='main'. So and there I need somehow deal with it... but for import I don't know...

I've already googled about it, only found https://stackoverflow.com/a/1057534/10289135 And I guess it will not work for me (I also don't understand how it works and script didn't work for me)

Any ideas?

Upvotes: 0

Views: 184

Answers (2)

Rex
Rex

Reputation: 3

import os 
import sys
import importlib
modules = []
for i in os.listdir("C:\\Windows\\path\\to\\your\\modules\\"):
    mod = i
    modules.append(mod)
sys.path.append("C:\\Windows\\path\\to\\your\\modules\\")
for i in modules:
    i = i[:i.find(".")]
    module = importlib.import_module(f"{i}")
    module.main()

Upvotes: 0

Code GUI
Code GUI

Reputation: 21

You can use the following syntax:

from filename(remove the .py) import *

This is a wild card import it imports every thing from a module literally everything .By doing this you dont need to do the work like 'filename.blabla' ,but simply you can do 'blabla'.

Upvotes: 1

Related Questions