`sys.meta_path` 和 `sys.path_hooks` 导入器对象有什么区别?
What is the difference between `sys.meta_path` and `sys.path_hooks` importer objects?
使用importlib
,"Meta Path Finder"(遍历sys.meta_path找到)和Path Entry Finder”(遍历sys.path_hooks找到)有什么区别?
第一种类型在导入开始时调用,但第二种类型何时使用? return 都是规范对象吗?
我想实现自定义导入,其中可以从 *.py 或 *.pyc 以外的源导入模块,例如来自流。如何做到这一点?
sys.path_hooks returns a finder factory.
Path hooks are called as part of sys.path (or package.__path__
) processing
正如我们在 PEP 302 relevant part 中读到的那样,您应该阅读它来做您想做的事。
说到,我们在我的代码中使用了 custom hook 但我不建议您逐字复制它(我真的不确定我们对 init 文件所做的骗局)
但是这个过程有点像那里 - find_module
方法 returns self 或 None 取决于你想接受什么作为模块和 load_module
方法通过编译代码并将其分配到 sys.modules
中来加载它。通过更换这些部件,您几乎可以加载任何您想要的东西。
相关:
- Package-specific import hooks in Python
- Python sys.path_hooks Examples
当要导入模块时,解释器首先遍历 sys.meta_path
中的对象列表,在每个对象上调用 find_spec()
或(自 3.4 起弃用)find_module()
方法. )该接口记录在 importlib.abc.MetaPathFinder 抽象基础 class 中。)这些在任何其他进口商(包括冻结和 built-in)被检查之前被查询,因此可以覆盖任何其他进口处理。
sys.meta_path
中的 PathFinder
对象是使用 sys.path
和 sys.path_hooks
的对象。 (除了 Python < 3.4,其中 PathFinder
功能内置于解释器中,当 sys.meta_path
中没有任何内容可以加载模块时使用。)
PathFinder
遍历 sys.path
中的路径列表。对于每条路径,如果 finder 尚未在 sys.path_importer_cache
中为该路径缓存,它会遍历 sys.path_hooks
中的可调用项列表,使用路径调用每个可调用项以查看它是否会生成一个发现者;它缓存在 sys.path.importer_cache_
.
中找到的第一个
一旦找到查找器,它就会通过 find_spec()
或已弃用的 find_module()
方法查询它是否可以找到该模块。如果是这样,它可以继续导入它,否则它会从 sys.path
.
上的下一个路径开始上面的步骤
这最初是在 PEP 302, but PEP 451 is pretty much the modern behaviour; the importlib 文档中描述的,似乎是当前规范。
我的 personal notes.
中总结了相当多的细节(带有更多链接)
使用importlib
,"Meta Path Finder"(遍历sys.meta_path找到)和Path Entry Finder”(遍历sys.path_hooks找到)有什么区别?
第一种类型在导入开始时调用,但第二种类型何时使用? return 都是规范对象吗?
我想实现自定义导入,其中可以从 *.py 或 *.pyc 以外的源导入模块,例如来自流。如何做到这一点?
sys.path_hooks returns a finder factory.
Path hooks are called as part of sys.path (or
package.__path__
) processing
正如我们在 PEP 302 relevant part 中读到的那样,您应该阅读它来做您想做的事。
说到,我们在我的代码中使用了 custom hook 但我不建议您逐字复制它(我真的不确定我们对 init 文件所做的骗局)
但是这个过程有点像那里 - find_module
方法 returns self 或 None 取决于你想接受什么作为模块和 load_module
方法通过编译代码并将其分配到 sys.modules
中来加载它。通过更换这些部件,您几乎可以加载任何您想要的东西。
相关:
- Package-specific import hooks in Python
- Python sys.path_hooks Examples
当要导入模块时,解释器首先遍历 sys.meta_path
中的对象列表,在每个对象上调用 find_spec()
或(自 3.4 起弃用)find_module()
方法. )该接口记录在 importlib.abc.MetaPathFinder 抽象基础 class 中。)这些在任何其他进口商(包括冻结和 built-in)被检查之前被查询,因此可以覆盖任何其他进口处理。
sys.meta_path
中的 PathFinder
对象是使用 sys.path
和 sys.path_hooks
的对象。 (除了 Python < 3.4,其中 PathFinder
功能内置于解释器中,当 sys.meta_path
中没有任何内容可以加载模块时使用。)
PathFinder
遍历 sys.path
中的路径列表。对于每条路径,如果 finder 尚未在 sys.path_importer_cache
中为该路径缓存,它会遍历 sys.path_hooks
中的可调用项列表,使用路径调用每个可调用项以查看它是否会生成一个发现者;它缓存在 sys.path.importer_cache_
.
一旦找到查找器,它就会通过 find_spec()
或已弃用的 find_module()
方法查询它是否可以找到该模块。如果是这样,它可以继续导入它,否则它会从 sys.path
.
这最初是在 PEP 302, but PEP 451 is pretty much the modern behaviour; the importlib 文档中描述的,似乎是当前规范。
我的 personal notes.
中总结了相当多的细节(带有更多链接)