简体   繁体   English

在Python3.0中动态导入模块?

[英]Dynamically importing modules in Python3.0?

I want to dynamically import a list of modules. 我想动态导入模块列表。 I'm having a problem doing this. 我在执行此操作时遇到问题。 Python always yells out an ImportError and tells me my module doesn't exist. Python总是大声ImportError并告诉我我的模块不存在。

First I get the list of module filenames and chop off the ".py" suffixes, like so: 首先,我获得模块文件名列表,并截掉".py"后缀,如下所示:

viable_plugins = filter(is_plugin, os.listdir(plugin_dir))
viable_plugins = map(lambda name: name[:-3], viable_plugins)

Then I os.chdir to the plugins directory and map __import__ the entire thing, like so: 然后我os.chdir到plugins目录并map __import__整个内容,就像这样:

active_plugins = map(__import__, viable_plugins)

However, when I turn active_plugins into a list and try to access the modules within, Python will throw out an error, saying it cannot import the modules since they don't appear to be there. 但是,当我将active_plugins转换为列表并尝试访问其中的模块时,Python会抛出一个错误,称它无法导入模块,因为它们似乎不存在。

What am I doing wrong? 我究竟做错了什么?


Edit: By simply using the interactive interpreter, doing os.chdir and __import__(modulefilename) produces exactly what I need. 编辑:通过简单地使用交互式解释器,做os.chdir__import__(modulefilename)产生我所需要的。 Why isn't the above approach working, then? 那么,上述方法为什么不起作用? Am I doing something wrong with Python's more functional parts? 我对Python的更多功能部分做错了吗?

It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path. 它说它做不到,因为即使您将目录更改为模块所在的位置,该目录也不在导入路径上。

What you need to do, instead of changing to the directory where the modules are located, is to insert that directory into sys.path . 您需要做的是将目录插入sys.path ,而不是切换到模块所在的目录。

import sys
sys.path.insert(0, directory_of_modules)
# do imports here.

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

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