Python:从文件夹导入每个模块? [英] Python: import every module from a folder?

查看:419
本文介绍了Python:从文件夹导入每个模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What would be the best (read: cleanest) way to tell Python to import all modules from some folder?

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

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,而是东西)

I also don't want an extra scope added to the imported stuff (not "myfolder.mymodule.something", but "something")

推荐答案

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

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 __ - 而mpmport语句需要对模块名称进行硬编码,它允许您在导入之前检查文件的其他内容 - 可能是大小,还是导入某些必需的模块。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆