模块是Python组织代码的基本方式。Python的脚本都是用扩展名py的文本文件来保存的,一个脚本可以单独运行,也可以导入另一个脚本中运行。我们称导入其他脚本中运行的脚本为模块(module)。

1、脚本的导入方式

模块的名称和脚本名称相同,如果在一个名为operation.py的文件中定义了加减乘除等四种操作运算函数:

operation.py:
#!/usr/bin/python
#-*-coding:utf-8-*-
def jia(a,b):
    return a+b 

def jian(a,b):
    return a-b 

def cheng(a,b):
    return a*b 

def chu(a,b):
    return a/b

可以用下面多种方式来引入模块,使用模块中定义的函数:

(1)import operation导入整个模块

#!/usr/bin/python
#-*-coding:utf-8-*-
import operation
print operation.jia(2,3)

$ python test.py
5
$

(2)from operation import *导入模块中的所有元素

#!/usr/bin/python
#-*-coding:utf-8-*-
from operation import *
print jia(2,3)

$ python test.py
5
$

这样,在每次使用模块中的元素的时候,就不用每次都加上模块名了。

(3)from operation import jia, jian导入模块中指定的元素


#!/usr/bin/python
#-*-coding:utf-8-*-
from operation import jia, jian
print jia(2,3)
print jian(2,3)

$ python test.py
5
-1
$

这样,同样也不用每次使用被引用模块中的元素的时候写模块名,而且区别与上面的导入所有的方式,这种方式会尽可能减少被引入模块中元素和引入脚本中对象名称冲突的可能性。

(4)import operation as op在引入脚本中重命名模块

#!/usr/bin/python
#-*-coding:utf-8-*-
import operation as op
print op.jia(2,3)
print op.jian(2,3)

$ python test.py
5
-1
$

这样,脚本代码的可读性就会提高很多。

2、模块的引入规范

一般在脚本的开头引入所有需要的模块,并且各种模块的顺序建议大致按照如下:

  • python标准模块
  • 第三方模块
  • 程序自定义模块

当然,也可以在函数内部导入模块,这样被导入的模块作用域是局部的。

3、模块的搜索顺序

对于Python脚本中导入的模块,python会在sys.path所指定的路径中,依次顺序需找被导入的模块。sys.path在脚本执行时动态生成,主要是由下面三部分组成,python会在下面三种路径中依次寻找被导入的模块:

  • 脚本执行的位置,即当前路径
  • 环境变量(即.bash_profile)中的PYTHONPATH
  • 安装python时的依赖位置

下面展示了我机器上的sys.path变量的值:

#!/usr/bin/python
#-*-coding:utf-8-*-
import sys
for p in sys.path:
    print p
$ python test.py
/home/ubuntu/recommendation/inverted_index
/usr/lib/python2.7
/usr/lib/python2.7/plat-linux2
/usr/lib/python2.7/lib-tk
/usr/lib/python2.7/lib-old
/usr/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/dist-packages
/usr/lib/python2.7/dist-packages
$

3、对象持久化模块的例子

下面是一个对pickle模块进行封装得到的一个内存对象持久化的模块,能使我们更加方便地使用picle对python内存中的对象进行持久化和恢复。

object_persistence.py:
#!/usr/bin/python
#-*-coding:utf-8-*-
import cPickle as pickle

def dump2file(obj, file_name):
    ''' 
    dump the obj_name object into a file named as file_name on disk.
    '''
    f = open(file_name, "wb", True)
    pickle.dump(obj, f)
    f.close()
    return True

def restore_from_file(file_name):
    ''' 
    restore the object in the file named as file_name on disk, return as the returning value of this function
    '''
    f = open(file_name,"rb")
    obj = pickle.load(f)
    f.close()
    return obj 

if __name__ == "__main__":
    a = {"a":[1,2,3],"b":[4,5,6]}
    dump2file(a,"test_a.dat")
    print "The structure has been dumped to file."
    print restore_from_file("test_a.dat")
    print "Reading finished successfully."

module_try.py:
#!/usr/bin/python
#-*-coding:utf-8-*-
from object_persistence import restore_from_file, dump2file

if __name__ == "__main__":
    #read from the file
    a = {'a': [1, 2, 3], 'b': [4, 5, 6]} 
    if dump2file(a,"test_a.dat"):
        print "The object has been dump to file on disk."
    print "------Restoring and print------"
    print restore_from_file("test_a.dat")
    print "restore over!"

$ python module_try.py 
The object has been dump to file on disk.
------Restoring and print------
{'a': [1, 2, 3], 'b': [4, 5, 6]}
restore over!
$

好了,就到这儿了。^_^