Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call functions of a dynamically imported module

Tags:

python

import

I have this module (called module1.py):

import os
def main():
    command=os.system("dir")
    return command,"str"

I have dynamically imported it with this:

mod = __import__("modules."module1)

It works great. But now I want to call the function "main" of module1.

mod.main() does not work. Why?? How may I call the main() function of the module1 module?

Thank you very much

like image 478
user1618465 Avatar asked Sep 19 '25 12:09

user1618465


1 Answers

I prefer using the fromlist argument.

mod = __import__("modules.%s" % (module1), fromlist=["main"])
mod.main()

Depending on your use case you may also want to specify locals and globals.

mod = __import__("modules.%s" % (module1), locals(), globals(), ["main"])
like image 53
sberry Avatar answered Sep 22 '25 02:09

sberry