Python中模組及包的使用
阿新 • • 發佈:2018-12-03
模組使用
模組:
模組式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