简体   繁体   English

如何动态导入模块?

[英]How to dynamically import modules?

I am trying to import modules dynamically in Python.我正在尝试在 Python 中动态导入模块。 Right now, I have a directory called 'modules' with two files inside;现在,我有一个名为“modules”的目录,里面有两个文件; they are mod1.py and mod2.py.它们是 mod1.py 和 mod2.py。 They are simple test functions to return time (ie. mod1.what_time('now') returns the current time).它们是返回时间的简单测试函数(即mod1.what_time('now')返回当前时间)。

From my main application, I can import as follows :从我的主应用程序,我可以导入如下:

sys.path.append('/Users/dxg/import_test/modules')
import mod1

Then execute :然后执行:

mod1.what_time('now') 

and it works.它有效。

I am not always going to know what modules are available in the dirctory.我并不总是会知道目录中有哪些模块可用。 I wanted to import as follows :我想import如下:

tree = []
tree = os.listdir('modules')

sys.path.append('/Users/dxg/import_test/modules')

for i in tree:
  import i

However I get the error :但是我收到错误:

ImportError: No module named i

What am I missing?我错过了什么?

The import instruction does not work with variable contents (as strings) (see extended explanation here ), but with file names. import指令不适用于变量内容(作为字符串)(请参阅此处的扩展说明),但适用于文件名。 If you want to import dynamically, you can use the importlib.import_module method:如果要动态导入,可以使用importlib.import_module方法:

import importlib
tree = os.listdir('modules')

...

for i in tree:
    importlib.import_module(i)

Note:笔记:

  • You can not import from a directory where the modules are not included under Lib or the current directory like that (adding the directory to the path won't help, see previous link for why).您不能从模块未包含在Lib或当前目录下的目录导入(将目录添加到路径无济于事,请参阅上一个链接了解原因)。 The simplest solution would be to make this directory (modules) a package (just drop an empty __init__.py file there), and call importlib.import_module('..' + i, 'modules.subpkg') or use the __import__ method.最简单的解决方案是将此目录(模块)作为一个包(只需在其中放置一个空的__init__.py文件),然后调用importlib.import_module('..' + i, 'modules.subpkg')或使用__import__方法.

  • You might also review this question .您也可以查看此问题 It discusses a similar situation.它讨论了类似的情况。

You can achieve something like what you are proposing, but it will involve some un-pythonic code.您可以实现类似于您所提议的东西,但它会涉及一些非 Python 代码。 I do not recommend doing this:我不建议这样做:

dynamic_imports = dict()
for filename in tree:
    name = filename.replace('.py', '')
    dynamic_imports[name] = __import__(name)

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

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