python – 导入模块时exec行为的区别

前端之家收集整理的这篇文章主要介绍了python – 导入模块时exec行为的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在运行以下程序.重要的是,假设这些程序所在的目录中有mymodule.py文件.

首先:

exec('''import sys
import os
os.chdir('/') 
sys.path = []
import mymodule''',{})

第二:

import mymodule
exec('''import sys
import os
os.chdir('/') 
sys.path = []
import mymodule''',{})

第一个片段按预期引发ImportError(毕竟,mymodule所在的目录不在路径中).然而,第二个片段没有,即使mymodule也不在它的路径中,我给它的环境是空的.

我的问题是为什么

解决方法

根据 The import system – The module cache,

The first place checked during import search is 07001. This
mapping serves as a cache of all modules that have been prevIoUsly
imported,including the intermediate paths. So if foo.bar.baz was
prevIoUsly imported
,sys.modules will contain entries for foo,
foo.bar,and foo.bar.baz. Each key will have as its value the
corresponding module object.

During import,the module name is looked up in 07001 and if
present,the associated value is the module satisfying the import,and
the process completes.
However,if the value is None,then a
ModuleNotFoundError is raised. If the module name is missing,Python
will continue searching for the module.

第二个片段成功导入mymodule;它被缓存在sys.modules中,因此不会在其他地方进行搜索.

原文链接:https://www.f2er.com/python/185770.html

猜你在找的Python相关文章