Python中导入模块文件夹

3

在Python中,是否可以从文件夹/包获取模块列表并导入它们?

我想从类内的函数中执行此操作,以便整个类都可以访问它们(可能从__init__方法完成)。

非常感谢您的帮助。


“from package import *”和“dir(package)”不够用吗?请注意,dir是Python命令,也是命令行命令。 - Hannele
@Hannele 这对你真的有效吗?我得到的是['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'],没有提到package中的模块。如果明确导入模块,则dir会显示模块,但这会败坏问题的目的。 - Eric Wilson
我可能需要重新检查一下如何使用文件夹 - 这个文件夹中是否有__init__.py文件?即使是空的,这会告诉Python将文件夹视为一个模块。 - Hannele
是的,我有一个__init__.py文件。但我没有@MarkHildreth提供的帮助性参考:在__init__.py中添加了一行代码__all__ = ['bar','baz'] - Eric Wilson
3个回答

4

请参见模块文档

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.

是的,您可以通过对目录中的文件进行目录列表并手动导入它们的方法来实现此操作。但是,没有内置语法来满足您的要求。

0
你可以使用dir函数查看模块列表。
import module
dir (module)

程序相关内容翻译:在程序的后续部分,您可以导入单个函数:

from module import function

еҪ“жҲ‘е°қиҜ•дҪҝз”Ёdir(foo)пјҲе…¶дёӯfooжҳҜдёҖдёӘеҢ…пјүж—¶пјҢжҲ‘еҫ—еҲ°дәҶ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']пјҢе®ғ并дёҚеҢ…еҗ«иҜҘеҢ…дёӯжЁЎеқ—зҡ„еҲ—иЎЁгҖӮ - Eric Wilson
@EricWilson >>> type(dir(sys)) <type 'list'> - Griffin
2
这样做并不能获取模块列表,而只会获取该包(在其目录下定义的__init__.py文件中)的属性列表。仅在__all__变量中明确声明时,该包的模块才会包含在此列表中。 - Mark Hildreth

0

distribute 模块提供了一个机制来完成大部分工作。首先,你可以使用 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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接