
Standard Library(標(biāo)準(zhǔn)庫(kù))
Python里包含了大量有用的模塊,熟悉標(biāo)準(zhǔn)庫(kù)能快速解決很多問(wèn)題。
我們以幾個(gè)常用的庫(kù)中的模塊來(lái)舉例說(shuō)明。
sys module(系統(tǒng)模塊)
sys module包括了一些系統(tǒng)特定的函數(shù)。包括之前學(xué)過(guò)的sys.argv
假設(shè)我們檢查所用Python版本:
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=6, micro=4, releaselevel='final', serial=0)
>>> sys.version_info.major==3
True
通過(guò)sys.version_info馬上能知道我們所用的Python版本號(hào),通過(guò).major知道用的是Python3,且可以用來(lái)做邏輯計(jì)算。
logging module(登錄模塊)
如果想檢查我們的程序是否按預(yù)期設(shè)想在運(yùn)行,把一些調(diào)試信息或重要信息存在某地,那么我們就可以用logging module
import os
import platform
import logging
# platform.platform() --->'Windows-10-10.0.16299-SP0'
if platform.platform().startswith('Windows'):
logging_file = os.path.join(os.getenv('HOMEDRIVE'),
os.getenv('HOMEPATH'),
'test.log')
else:
logging_file = os.path.join(os.getenv('HOME'),
'test.log')
print("Logging to", logging_file)
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s : %(levelname)s : %(message)s',
filename=logging_file,
filemode='w',
)
logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")
Output:
Logging to C:\Users\blgzs_csz\test.log
2014-03-29 09:27:36,660 : DEBUG : Start of the program
2014-03-29 09:27:36,660 : INFO : Doing something
2014-03-29 09:27:36,660 : WARNING : Dying now
#上述后三行在我的PyCharm中沒有顯示出來(lái)。 如果檢查test.log 的內(nèi)容,才會(huì)有這樣后三行的內(nèi)容
Module of the Week Series
在標(biāo)準(zhǔn)庫(kù)中還有很多例如調(diào)試、處理命令行、正則表達(dá)式等等。
要進(jìn)一步深入了解,最好的方法是去讀Doug Hellmann所著的 《Python Module of the Week》 系列以及《Python documentation》
這一章雖然簡(jiǎn)短,但是對(duì)于應(yīng)用Python來(lái)說(shuō)很關(guān)鍵。需要不斷的深入學(xué)習(xí),用help()看過(guò)幾個(gè),但是還不是很透徹,有空要結(jié)合下階段的實(shí)踐和作者推薦的這兩本書才行。