调用动态导入模块的函数

use*_*465 4 python import

我有这个模块(称为 module1.py):

import os
def main():
    command=os.system("dir")
    return command,"str"
Run Code Online (Sandbox Code Playgroud)

我已经动态导入它了:

mod = __import__("modules."module1)
Run Code Online (Sandbox Code Playgroud)

效果很好。但现在我想调用 module1 的函数“main”。

mod.main()不起作用。为什么??如何调用 module1 模块的 main() 函数?

非常感谢

sbe*_*rry 5

我更喜欢使用fromlist论证。

mod = __import__("modules.%s" % (module1), fromlist=["main"])
mod.main()
Run Code Online (Sandbox Code Playgroud)

根据您的用例,您可能还需要指定局部变量和全局变量。

mod = __import__("modules.%s" % (module1), locals(), globals(), ["main"])
Run Code Online (Sandbox Code Playgroud)