模块名称在变量中时导入模块[重复]

时间:2022-08-22 08:54:02

Possible Duplicate:
Dynamic module import in Python

可能重复: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 .

我正在编写一个小脚本,从目录中获取文件的名称,并将其传递给另一个模块,然后导入该文件。

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

所以流程就像1)获取模块名称(将其存储在变量中)2)将此变量名称传递给模块3)导入名称存储在变量名称中的模块

my code is like

我的代码就像

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

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 on how this works in python , any help on solving this problem would be great

问题是当它到达import语句时,它将modulename作为实际模块名称而不是存储在此变量中的值。我不确定它在python中是如何工作的,任何解决这个问题的帮助都会很棒

2 个解决方案

#1


34  

You want the built in __import__ function

你想要内置的__import__函数

new_module = __import__(modulename)

#2


19  

importlib is probably the way to go. The documentation on it is here. It's generally preferred over __import__ for most uses.

importlib可能是要走的路。它的文档在这里。对于大多数用途,它通常优于__import__。

In your case, you would use:

在您的情况下,您将使用:

import importlib
module = importlib.import_module(module_name, package=None)

#1


34  

You want the built in __import__ function

你想要内置的__import__函数

new_module = __import__(modulename)

#2


19  

importlib is probably the way to go. The documentation on it is here. It's generally preferred over __import__ for most uses.

importlib可能是要走的路。它的文档在这里。对于大多数用途,它通常优于__import__。

In your case, you would use:

在您的情况下,您将使用:

import importlib
module = importlib.import_module(module_name, package=None)