Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list all submodules imported from module

My code starts with the following:

from module import *

How can I get a list of all submodules imported from this module.

For example module has:

module.submodule
module.submodule2
module.anothersubmodule

I want to get after from module import *:

[submodule, submodule2, anothersubmodule]

(not strings with name of submodules, but a list with all submodules themselves)

UPD: I understood that I asked about XY problem. So here's what i'm trying to achieve: I have a folder called modules that will have a bunch of scripts following the same pattern. They will all have a function like main(). In my main script i want to import them all and iterate like that:

for i in modules:
    i.main(*some_args)
like image 628
dacefa Avatar asked Dec 19 '22 00:12

dacefa


1 Answers

Use the pkgutil module. For example:

import pkgutil
import module

modualList = []
for importer, modname, ispkg in pkgutil.iter_modules(module.__path__):
    modualList.append(modname)
like image 69
Jon Avatar answered Dec 27 '22 02:12

Jon