您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:23:12 python 字数 1809 阅读 557 来源 www.jb51.cc/python

我正在运行以下程序.重要的是,假设这些程序所在的目录中有mymodule.py文件. 首先: exec('''import sys import os os.chdir('/') sys.path = [] import mymodule''', {}) 第二: import mymodule exec('''import sys import os os.chdir('/') sys.pat

概述

首先:

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

总结

以上是编程之家为你收集整理的python – 导入模块时exec行为的区别全部内容,希望文章能够帮你解决python – 导入模块时exec行为的区别所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶