模块使用

模块:

模块式pyth1.on组织代码的基本方式

一个python脚本可以单独运行,也可以导入另一个脚本中运行,当脚本被导入运行时,我们将其称为模块(module)

所有的点p为文件都可以作为一个模块导入

模块名与脚本的文件名相同,例如我们编写了一个名为hello.pv的脚本则可以在另一个脚本中用import hello.py来导入它

包:

python的模块可以按目录组织为包

创建一个包的步骤:

    创建一个名字为包名字的目录,在该目录下创建一个__init__.py文件,根据需要在该目录下存放脚本文件或已编译的扩展及子包

语法:

import pack.m1,pack.m2,pack.m3

sys.path

举例:

In [1]: import sys

In [2]: sys.path

Out[2]:

['',

'/usr/bin',

'/usr/lib64/python27.zip',

'/usr/lib64/python2.7',

'/usr/lib64/python2.7/plat-linux2',

'/usr/lib64/python2.7/lib-tk',

'/usr/lib64/python2.7/lib-old',

'/usr/lib64/python2.7/lib-dynload',

'/usr/lib64/python2.7/site-packages',

'/usr/lib64/python2.7/site-packages/gtk-2.0',

'/usr/lib/python2.7/site-packages',

'/usr/lib/python2.7/site-packages/IPython/extensions',

'/root/.ipython']



vim /root/.bashrc

最后加个export PYTHONPATH=/root/library



成功加入到Python环境变量中

In [1]: import sys

In [2]: sys.path

Out[2]:

['',

'/usr/bin',

 '/root/library',

'/usr/lib64/python27.zip',

'/usr/lib64/python2.7',

'/usr/lib64/python2.7/plat-linux2',

'/usr/lib64/python2.7/lib-tk',

'/usr/lib64/python2.7/lib-old',

'/usr/lib64/python2.7/lib-dynload',

'/usr/lib64/python2.7/site-packages',

'/usr/lib64/python2.7/site-packages/gtk-2.0',

'/usr/lib/python2.7/site-packages',

'/usr/lib/python2.7/site-packages/IPython/extensions',

'/root/.ipython']



可被其他脚本调用的脚本:

#!/usr/bin/env python

#

def wordCount(s):

    chars = len(s)

    words = len(s.split())

    lines = s.count('\n')

    print lines,words,chars

if __name__=='__main__':  #设置后,本脚本内的函数可被其他脚本调用test.py

    s = open('/etc/passwd').read()

    wordCount(s)

#



[root[@localhost](https://my.oschina.net/u/570656) 20181203]# python words.py

27 52 1324

[root[@localhost](https://my.oschina.net/u/570656) 20181203]# wc /etc/passwd

27   52 1324 /etc/passwd



test.py中导入words.py:

[root[@localhost](https://my.oschina.net/u/570656) 20181203]# cat test.py

#!/usr/bin/env python

import words

#

s="""hello world python"""

words.wordCount(s)



[root[@localhost](https://my.oschina.net/u/570656) 20181203]# python test.py

27 52 1324

[root[@localhost](https://my.oschina.net/u/570656) 20181203]# ls

test.py  words.py  words.pyc   ###调用words后自动生成编译的文件。

模块和包:

模块是一个可以导入的脚本文件

包是一些按目录组织的模块和子包,目录下有__init__.py文件,此文件可以存放包的信息。

导入模块和包的语法:

import,import as

from ... import ...
In [2]: from mode import mode
2 10 158
In [3]: mode.wordCount('abc')
0 1 3



In [4]: import mode.mode
In [5]: mode.mode.wordCount('hello')
0 1 5


In [7]: from mode.mode import wordCount
In [8]: wordCount('aaa')
0 1 3

#重新命名为wc
In [10]: from mode.mode import wordCount as wc
In [11]: wc('aaaddd')
0 1 6
12-04 05:49