加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:34:35 所属栏目:Python 来源:网络整理
导读:我正在运行以下程序.重要的是,假设这些程序所在的目录中有mymodule.py文件. 首先: exec('''import sysimport osos.chdir('/') sys.path = []import mymodule''',{}) 第二: import mymoduleexec('''import sysimport osos.chdir('/') sys.path = []import m
我正在运行以下程序.重要的是,假设这些程序所在的目录中有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中,因此不会在其他地方进行搜索.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读