python 模块导入问题
黄舟
黄舟 2017-04-18 09:28:32
[Python讨论组]

在看到eventlet 文件的时候,有个select.py 文件有这样的几行,这个导入,导入的是哪个文件?

__select = __import__('select')
error = __select.error
from eventlet.greenthread import getcurrent
from eventlet.hubs import get_hub
from eventlet.support import six

这个文件本身的文件名就是select.py ,请问第一行是什么意思?导入的是哪个select 文件?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
阿神

纠正一下,.py文件应该被称作模块(module)

正常情况下,这样确实是导入自己,但我刚去github上看了一下eventletselect.py的源码,它本身并没有error这个对象,那么第二行就不对。

所以,这里引入的selectPython标准模块中的select,该模块中也确实有error对象:

In [5]: import select

In [6]: print select.error
<class 'select.error'>

因此,这两行代码相当于对Python标准模块select进行了继承或重写。

但这里有个问题,正常情况下,如果我们写一个与标准模块名称相同的.py文件,然后引入自己,Python解释器会优先引入.py模块本身,而不是标准模块,我自己也写了一个select.py

__select = __import__('select')
print __select

输出结果如下:

<module 'select' from 'D:\home\codes\codes2\select.py'>

正是该模块当前的路径。

那么怎么样才能引入标准模块呢?只需加几句话:

import sys
sys.path.append(sys.path[0])
sys.path.pop(0)

__select = __import__('select')
print __select

输出结果:

<module 'select' from 'C:\Python27\DLLs\select.pyd'>

默认情况下,当前模块的路径在sys.path[0]中,我们把该路径添加到sys.path列表末尾,并移除0位置的路径,此时,Python解释器在查找模块时,当前模块的优先度低于标准库,因此就会以标准库为先。

evenletselet.py中好像没有那几句,我猜应该是放到其他py文件中了……

PHP中文网

此处应该是python自己的select标准库,不是eventlet的select.py,这里使用__import__的意思应该是怕污染命名空间吧:

One side-effect of using __import__ can be that it returns the imported module and doesn't add anything to the namespace; you can import with it without having then to delete the new name if you didn't want that new name; using import somename will add somename to your namespace, but __import__('somename') instead returns the imported module, which you can then ignore. Werkzeug uses the hook for that reason in one location.
http://stackoverflow.com/a/28...

伊谢尔伦

在这种情况下,第一行基本等价于

import select as __select

就是导入了标准库的 select 库,后面那行也就是个简单的赋值

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号