[英]Import folder of modules in Python
Is it possible in python to get a list of modules from a folder/package and import them? 在python中是否可以从文件夹/包中获取模块列表并将其导入?
I would like to be able to do this from a function inside a class, so that the entire class has access to them (possibly done from the __init__
method). 我希望能够通过类内部的函数来执行此操作,以便整个类都可以访问它们(可能是通过
__init__
方法完成的)。
Any help would be greatly appreciated. 任何帮助将不胜感激。
See the modules document . 请参阅模块文档 。
The only solution is for the package author to provide an explicit index of the package.
唯一的解决方案是让程序包作者提供程序包的显式索引。 The import statement uses the following convention: if a package's
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported when from package import * is encountered.import语句使用以下约定:如果程序包的
__init__.py
代码定义了名为__all__
的列表,则将其视为遇到从包import *时应导入的模块名称的列表。 It is up to the package author to keep this list up-to-date when a new version of the package is released.发行新版本的软件包时,软件包作者有责任使此列表保持最新。 Package authors may also decide not to support it, if they don't see a use for importing * from their package.
如果软件包作者没有看到从软件包中导入*的用途,他们可能还会决定不支持它。 For example, the file sounds/effects/
__init__.py
could contain the following code:例如,文件sounds / effects /
__init__.py
可能包含以下代码:__all__ = ["echo", "surround", "reverse"]
This would mean that from sound.effects import * would import the three named submodules of the sound package.
这意味着从sound.effects import *将导入声音包的三个命名子模块。
Yes, you could find a way to do this by doing a directory listing for the files in the directory and import them manually. 是的,您可以找到一种方法来执行此操作,方法是为目录中的文件列出目录并手动将其导入。 But there isn't built-in syntax for what you're asking.
但是您要的内容没有内置语法。
You can know the list of the modules with the dir function 您可以使用dir功能了解模块列表
import module
dir (module)
Later in a program, you can import a single function : 在程序的后面,您可以导入一个函数:
from module import function
The distribute
module provides a mechanism that does much of this. distribute
模块提供了执行此操作的机制。 First, you might start by listing the python files in a package using pkg_resources.resource_listdir
: 首先,您可以先使用
pkg_resources.resource_listdir
在软件包中列出python文件:
>>> module_names = set(os.path.splitext(r)[0]
... for r
... in pkg_resources.resource_listdir("sqlalchemy", "/")
... if os.path.splitext(r)[1] in ('.py', '.pyc', '.pyo', '')
... ) - set(('__init__',))
>>> module_names
set(['engine', 'util', 'exc', 'pool', 'processors', 'interfaces',
'databases', 'ext', 'topological', 'queue', 'test', 'connectors',
'orm', 'log', 'dialects', 'sql', 'types', 'schema'])
You could then import each module in a loop: 然后,您可以循环导入每个模块:
modules = {}
for module in module_names:
modules[module] = __import__('.'.join('sqlalchemy', module))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.