【问题标题】:Python: import every module from a folder?Python:从文件夹中导入每个模块?
【发布时间】:2012-04-20 01:43:01
【问题描述】:

告诉 Python 从某个文件夹导入所有模块的最佳(阅读:最干净)方法是什么?

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

我也不希望在导入的内容中添加额外的范围(不是“myfolder.mymodule.something”,而是“something”)

【问题讨论】:

标签: python import directory


【解决方案1】:

如果在模块中转换文件夹本身,通过使用__init__.py 文件和使用from <foldername> import * 适合您,您可以迭代文件夹内容 使用“os.listdir”或“glob.glob”,并使用__import__内置函数导入每个以“.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__ - 而ìmport 语句需要对模块名称进行硬编码,它允许您检查文件的其他内容 - 可能是大小,或者如果他们导入某些必需的模块,则在导入它们之前。

【讨论】:

  • 这在Python3.6中仍然有效,但最后一行改为:import importlib; importlib.import_module("plugins" + "." + module)
  • 谢谢 - 他们已弃用 __import__ 中的文件名。该功能仍然有效,只需使用“。”那里而不是os.path.join
【解决方案2】:

创建一个名为

的文件
 __init__.py

在文件夹里面,像这样导入文件夹名称:

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

【讨论】:

  • 那么按照链接的答案中的建议在 os.path 列表中添加文件夹并导入您需要的内容。
【解决方案3】:

您可能想尝试该项目:https://gitlab.com/aurelien-lourot/importdir

有了这个模块,你只需要写两行来从你的目录中导入所有插件,你不需要额外的__init__.py(或任何其他额外的文件):

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

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多