gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:03:15 24 4
gpt4 key购买 nike

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

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

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

最佳答案

如果在模块中转换文件夹本身,通过使用 __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 语句需要对模块名称进行硬编码,但它允许您在导入文件之前检查有关文件的其他信息 - 可能是大小,或者它们是否导入了某些必需的模块。

关于Python:从文件夹导入每个模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10043485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com