模块和包管理

1 模块管理

当我们在代码中使用 import moudule_name的语句的时候,python将会在一系列给定的文件夹中查找,如果查找不到将会报错。


In [1]:
import sys
sys.path


Out[1]:
['',
 '/Users/gaufung/Anaconda/anaconda/lib/python27.zip',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/plat-darwin',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/plat-mac',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/lib-tk',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/lib-old',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/lib-dynload',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/site-packages',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/site-packages/Sphinx-1.4.6-py2.7.egg',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/site-packages/aeosa',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg',
 '/Users/gaufung/Anaconda/anaconda/lib/python2.7/site-packages/IPython/extensions',
 '/Users/gaufung/.ipython']

如果想要在继续添加查找的包的文件夹位置,在Linux和Unix操作系统下可以使用一下操作

export PYTHONPATH = $PYTHONPATH:/home/mymodule

使用Python代码添加

Python:n
import sys
module_path='/home/mymodule'
if module_path not in sys.path:
    sys.path.append(module_path)

2 Package

package 是一组包的管理工作,比如一个文件下中有多个模块或者子模块,通常情况下,在该文件下有一个__init__.py文件,表明该文件夹为一个package


In [2]:
import scipy
scipy.__file__


Out[2]:
'/Users/gaufung/Anaconda/anaconda/lib/python2.7/site-packages/scipy/__init__.pyc'

In [4]:
import scipy.version
scipy.version.version


Out[4]:
'0.18.1'