0

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?

Casual
  • 71
  • 1
  • 8

2 Answers2

1

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'.

Code GUI
  • 21
  • 2
0
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()
Rex
  • 3
  • 4
  • Gives error. ` module.main()` `AttributeError: module 'arp' has no attribute 'main'` arp.py `def main(): print('arp')` – Casual Nov 10 '20 at 06:44