python 导入模块 import 理解
--python 导入模块 import 理解
-----------------------------------2014/03/18
python 导入一个模块的过程要求有一个叫做“路径搜索”的操作过程,即是在文件系统“预先设定的区域”查找模块文件以加载模块的过程。这个预先设定的区域其实是python搜索路径的一组目录。这个目录保存在sys.path中,如果你想知道python导入模块时会在哪些路径搜索模块,你可以执行以下命令查看搜索路径目录:
>>> import sys
>>> sys.path
['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages']
>>>
我得到的结果就是上面的列表了。如果你想添加其他搜索路径到搜索路径目录,可以执行:
>>> sys.path.append('/usr/src/CamProject')
>>> sys.path
['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages', '/usr/src/CamProject']
可以看到,我把搜索路径'/usr/src/CamProject'添加到路径里面了。(在最后)
如果想放在第一位,可以执行:
>>> sys.path.insert(0,'/usr/src/CamProject')
>>> sys.path
['/usr/src/CamProject', '', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages', '/usr/src/CamProject']
可以看到放在第一位了。
如果我们需要导入的模块是放在文件夹里面,那么,文件夹里面必须要添加__init__.py文件,以使得python能够找到模块的位置。__init__.py可以为空,只要它存在,就表明此目录应被作为一个package处理。当然,__init__.py中也可以设置相应的内容,
本人的__init__.py内容如下:
################################################################################
# __init__.py
# This is here to make python see Profile folder