在Python中,是否可以从文件夹/包获取模块列表并导入它们?
我想从类内的函数中执行此操作,以便整个类都可以访问它们(可能从__init__
方法完成)。
非常感谢您的帮助。
请参见模块文档。
是的,您可以通过对目录中的文件进行目录列表并手动导入它们的方法来实现此操作。但是,没有内置语法来满足您的要求。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. 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:__all__ = ["echo", "surround", "reverse"]
This would mean that from sound.effects import * would import the three named submodules of the sound package.
import module
dir (module)
from module import function
dir(foo)
пјҲе…¶дёӯfoo
жҳҜдёҖдёӘеҢ…пјүж—¶пјҢжҲ‘еҫ—еҲ°дәҶ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
пјҢе®ғ并дёҚеҢ…еҗ«иҜҘеҢ…дёӯжЁЎеқ—зҡ„еҲ—иЎЁгҖӮ - Eric Wilson>>> type(dir(sys)) <type 'list'>
- Griffindistribute
模块提供了一个机制来完成大部分工作。首先,你可以使用 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'])
然后您可以在循环中导入每个模块:
modules = {}
for module in module_names:
modules[module] = __import__('.'.join('sqlalchemy', module))
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
,没有提到package
中的模块。如果明确导入模块,则dir
会显示模块,但这会败坏问题的目的。 - Eric Wilson__init__.py
文件?即使是空的,这会告诉Python将文件夹视为一个模块。 - Hannele__init__.py
文件。但我没有@MarkHildreth提供的帮助性参考:在__init__.py
中添加了一行代码__all__ = ['bar','baz']
。 - Eric Wilson