Python: 从文件夹导入每个模块?

2024-04-25 19:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

告诉Python从某个文件夹导入所有模块的最佳方法是什么?

我想允许人们把他们的“mods”(模块)放在我的应用程序中的一个文件夹中,我的代码应该在每次启动时检查这个文件夹,并导入放在那里的任何模块。

我也不想在导入的东西中添加额外的作用域(不是“myfolder.mymodule.something”,而是“something”)


Tags: 模块方法代码文件夹mods应用程序作用域something
3条回答

创建名为

 __init__.py

在文件夹中导入文件夹名,如下所示:

>>> from <folder_name> import * #Try to avoid importing everything when you can
>>> from <folder_name> import module1,module2,module3 #And so on

你可能想试试那个项目:https://gitlab.com/aurelien-lourot/importdir

使用此模块,只需编写两行代码即可从目录中导入所有插件,而不需要额外的__init__.py(或任何其他额外文件):

import importdir
importdir.do("plugins/", globals())

如果在模块中转换文件夹本身,通过使用__init__.py文件并使用from <foldername> import *适合您,则可以遍历文件夹内容 使用“os.listdir”或“glob.glob”,并使用内置函数导入以“.py”结尾的每个文件:

import os
for name in os.listdir("plugins"):
    if name.endswith(".py"):
          #strip the extension
         module = name[:-3]
         # set the module name in the current global name space:
         globals()[module] = __import__(os.path.join("plugins", name)

这种方法的好处是:它允许您动态地将模块名传递给__import__,而“import”语句需要对模块名进行硬编码,并且它允许您在导入文件之前检查有关文件的其他内容(可能是文件大小,或者如果它们导入了某些必需的模块)。

相关问题 更多 >