gpt4 book ai didi

python - 动态获取模块

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:12 24 4
gpt4 key购买 nike

我有一些像这样的模块:

    Drivers/
a.py
b.py
c.py

现在我想根据一个变量值来调用它们。让我们考虑驱动程序是我将从中获取变量名称的变量。

    if driver=='a':
#then call the driver a and execute.
a.somefunction()
if driver=='b':
#then call the driver b and execute

我知道我们在 if 语句中从驱动程序中获取的值是一个字符串类型的值,并且在 if 语句中我们必须调用一个模块。有什么办法可以转换吗??

最佳答案

如果你的“Drivers/”目录在python的搜索路径中,只需导入模块并调用函数:

import importlib
module = importlib.import_module(driver)
module.some_function()

关于python - 动态获取模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24720403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com