[英]Iterating over python files in a given directory and importing them?
I'm working on a little pet project in python, and I want to be able to write external modules and dynamically import them. 我正在使用python开发一个小型宠物项目,并且希望能够编写外部模块并动态导入它们。 So far, I've got something like this:
到目前为止,我有这样的事情:
def getModules(self):
os.chdir(moduleDir)
for module in os.listdir():
#code goes here to import
#also append to a list for use later on
I'd use import module
, but that just gives a Syntax Error. 我会使用
import module
,但这只会给出一个语法错误。
You can use importlib.import_module()
like this: 您可以像这样使用
importlib.import_module()
:
import importlib
my_modules = []
def getModules(self):
os.chdir(moduleDir)
for module in os.listdir():
my_module = importlib.import_module(module[:-3]) # Or: module.split('.')[0]
my_modules.append(my_module)
Example: 例:
Let's say we have a module a
that contains the following function: 比方说,我们有一个模块
a
,包含以下功能:
def fn():
print("Hello World")
The following is the result: 结果如下:
>>> import importlib
>>>
>>> my_module = importlib.import_module('a') # Note: 'a' without '.py'
>>>
>>> my_module.fn()
Hello World
You should use the __import__
function. 您应该使用
__import__
函数。 Something like this will help, 这样的事情会有所帮助,
def getModules(self):
modules = []
os.chdir(moduleDir)
for module in os.listdir('.'):
m = __import__(module.split('.')[0]) # Assuming your listdir() gives .py files
modules.append(m)
A still better choice would be importlib.import_module()
which is a wrapper around __import__
. 更好的选择是
importlib.import_module()
,它是__import__
的包装。 It's got a similar syntax to __import__
. 它具有与
__import__
相似的语法。 Of course, you need to import importlib
. 当然,您需要
import importlib
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.