简体   繁体   English

Function 从列表中导入模块

[英]Function to import modules from a list

My goal is to have a function with a list of strings as input and import those modules I want for my code.我的目标是拥有一个带有字符串列表的 function 作为输入,并导入我的代码所需的那些模块。

Example:例子:

list_of_modules = ['module1', 'module2']

def importer(list_of_modules):
    for module in list_of_modules:
        if module == 'module1':
            from package.package2.module1 import function1
        if module == 'module2':
            from package.package2.module2 import function1
        if module == 'module3':
            from package.package2.module3 import function1

I have tried this solution and it seems like the modules are not imported.我已经尝试过这个解决方案,但似乎没有导入模块。 I have also tried using import builtin function, but nothing.我也尝试过使用import builtin function,但没有。

My real example was:我的真实例子是:

def importer(modules):
    for value in modules:
        if value == "ble_connection":
            from top_app.module.connection.test_connectivity import connection1
        if value == "switch_connection":
            from top_app.module.connection.test_connectivity import connection2

I have to add that I am using pytest for running the tests from the general conftest file and this one calls this importer function during the pytest_configure hook which is right after the discovery hook.我必须补充一点,我正在使用 pytest 从通用 conftest 文件运行测试,这个在发现挂钩之后的 pytest_configure 挂钩期间调用这个导入器 function。

Do you have any solution for this?你对此有什么解决办法吗?

thanks谢谢

I would use exec for this purpose:为此,我会使用exec

list_of_modules = ['module1', 'module2']
for module in list_of_modules:
    exec('package.package2.{} import function1'.format(module))

but as someone commented on your OP, function1 will be overwritten doing this.但正如有人对您的 OP 发表的评论, function1将被覆盖这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM