|
我正在运行以下程序.重要的是,假设这些程序所在的目录中有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中,因此不会在其他地方进行搜索. (编辑:安卓应用网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|