素材牛VIP会员
python 模块导入问题
 qi***pu  分类:Python  人气:678  回帖:3  发布于6年前 收藏

在看到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 文件?

 标签:python

讨论这个帖子(3)垃圾回帖将一律封号处理……

Lv1 新人
飘***子 JS工程师 6年前#1

纠正一下,.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文件中了……

Lv6 码匠
素***2 学生 6年前#2

此处应该是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...

Lv2 入门
麦***气 JAVA开发工程师 6年前#3

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

import select as __select

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

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取