当模块名称在变量中时导入模块 [英] importing a module when the module name is in a variable
问题描述
可能的重复:
Python 中的动态模块导入
我正在编写一个小脚本,它从目录中获取文件名并将其传递给另一个模块,然后该模块导入该文件.
I am writing a small script that gets the name of a file from a directory and passes this to another module which then imports the file.
所以流程就像1)获取模块名称(将其存储在变量中)2) 将此变量名称传递给模块3)导入名字存放在变量名中的模块
so the flow is like 1) get module name ( store it in a variable) 2) pass this variable name to a module 3) import the module whose name is stored in the variable name
我的代码就像
data_files = [x[2] for x in os.walk(os.path.dirname(sys.argv[0]))]
hello = data_files[0]
modulename = hello[0].split(".")[0]
import modulename
问题是当它到达 import 语句时,它读取 modulename 作为一个真正的模块名称,而不是存储在这个变量中的值.我不确定这在 python 中是如何工作的,解决这个问题的任何帮助都会很棒
the problem is when it reaches the import statement, it reads modulename as a real module name and not the value stored in this variable. I am unsure about how this works in python, any help on solving this problem would be great
推荐答案
您想要内置的 __import__
函数
You want the built in __import__
function
new_module = __import__(modulename)
这篇关于当模块名称在变量中时导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!