如何在Python中动态导入时调用__import__函数。

huangapple go评论60阅读模式
英文:

How do I call __import__ when dynamically importing in python

问题

I am just playing around with the dynamically importing a module example as they do in 16.15 of dive into python.

我只是在玩弄动态导入模块的示例,就像《Python深入浅出》中的第16.15章节所示。

I am doing something like

我正在做类似的事情:

modulenames = ['my_module']
modules = list(map(import, modulenames))
modules[0].process()

模块名称 = ['my_module']
模块列表 = list(map(import, 模块名称))
模块列表[0].process()

However my model is in a subdirectory (called 'modules') so instead of

但是我的模块位于一个子目录中(名为'modules'),所以不是

import my_module

我会这样做

我会这样做:

from modules import my_module

从 modules 导入 my_module

The import dunder accepts a fromlist where I (presumably?) can pass the subdirectory but I cant quite figure out the syntax to add it inside the map() call

导入双下划线(dunder)接受一个 fromlist 参数,我(大概?)可以传递子目录,但我无法弄清楚如何在 map() 调用内添加它的语法。

英文:

I am just playing around with the dynamically importing a module example as they do in 16.15 of dive into python.

I am doing something like

modulenames = ['my_module']
modules = list(map(__import__, modulenames))
modules[0].process()

However my model is in a subdirectory (called 'modules') so instead of

import my_module

I would do

from modules import my_module

The import dunder accepts a fromlist where I (presumably?) can pass the subdirectory but I cant quite figure out the syntax to add it inside the map() call

答案1

得分: 1

根据我理解的文档,您只需执行以下操作:

modules = __import__("modules", fromlist=["my_module"])

然后可以使用 modules.my_module 访问它。

英文:

From what I understand in the documentation, you can just do :

modules = __import__("modules", fromlist=["my_module"])

and then acces it with modules.my_module

答案2

得分: 1

Here is the translation:

另一种方式:

from importlib import import_module

module_list = ('package.a', 'package.b')
modules = [import_module(module) for module in module_list]
modules[0].process()
英文:

Another way:

from importlib import import_module

module_list = ('package.a', 'package.b')
modules = [import_module(module) for module in module_list]
modules[0].process()

huangapple
  • 本文由 发表于 2023年5月10日 22:01:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定