Python:从文件夹中导入每个模块? [英] Python: import every module from a folder?
问题描述
告诉 Python 从某个文件夹导入所有模块的最佳(阅读:最干净)方法是什么?
What would be the best (read: cleanest) way to tell Python to import all modules from some folder?
我想让人们将他们的模组"(模块)放在我的应用程序的一个文件夹中,我的代码应该在每次启动时检查该文件夹并导入放置在那里的任何模块.
I want to allow people to put their "mods" (modules) in a folder in my app which my code should check on each startup and import any module put there.
我也不希望在导入的内容中添加额外的范围(不是myfolder.mymodule.something",而是something")
I also don't want an extra scope added to the imported stuff (not "myfolder.mymodule.something", but "something")
推荐答案
如果在模块中转换文件夹本身,通过使用 __init__.py
文件并使用 from <文件夹名称>import *
适合你,你可以遍历文件夹内容使用os.listdir"或glob.glob",并使用 __import__
内置函数导入每个以.py"结尾的文件:
If transforming the folder itself in a module, through the use of a __init__.py
file and using from <foldername> import *
suits you, you can iterate over the folder contents
with "os.listdir" or "glob.glob", and import each file ending in ".py" with the __import__
built-in function:
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 语句需要对模块名称进行硬编码,并且它允许您检查有关文件 - 可能是大小,或者是否在导入之前导入了某些必需的模块.
The benefit of this approach is: it allows you to dynamically pass the module names to __import__
- while the ìmport statement needs the module names to be hardcoded, and it allows you to check other things about the files - maybe size, or if they import certain required modules, before importing them.
这篇关于Python:从文件夹中导入每个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!