首先:
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 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中,因此不会在其他地方进行搜索.