在看到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
文件?
纠正一下,.py
文件应该被称作模块(module)
。
正常情况下,这样确实是导入自己,但我刚去github
上看了一下eventlet
中select.py
的源码,它本身并没有error
这个对象,那么第二行就不对。
所以,这里引入的select
是Python
标准模块中的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
解释器在查找模块时,当前模块的优先度低于标准库,因此就会以标准库为先。
evenlet
的selet.py
中好像没有那几句,我猜应该是放到其他py
文件中了……
此处应该是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...