1. 程式人生 > >Python 3 標準庫概覽

Python 3 標準庫概覽

作業系統介面

 
>>> import os >>> os.getcwd() # 返回當前的工作目錄 'C:\\Python34' >>> os.chdir('/server/accesslogs') # 修改當前的工作目錄 >>> os.system('mkdir today') # 執行系統命令 mkdir  0 

 

通常建議使用import os 而非from os import *,這樣可以保證隨作業系統的不同有所變化的 os.open() 不會覆蓋內建函式 open()。

在使用 os 這樣的大型模組時內建的 dir() 和 help() 函式非常有用:

dir(os)

help(os)

針對日常的檔案和目錄管理任務,:mod:shutil 模組提供了一個易於使用的高階介面:

 
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') >>> shutil.move('/build/executables', 'installdir') 

檔案萬用字元

glob模組提供了一個函式用於從目錄萬用字元搜尋中生成檔案列表:

 
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py'] 

命令列引數

通用工具指令碼經常呼叫命令列引數。這些命令列引數以連結串列形式儲存於 sys 模組的 argv 變數。例如在命令列中執行“python demo.py one two three”後可以得到以下輸出結果:

 
>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three'] 

錯誤輸出重定向和程式終止

sys 還有 stdin,stdout 和 stderr 屬性,即使在 stdout 被重定向時,後者也可以用於警告和錯誤資訊。

 
>>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one 

大多數指令碼的定向終止都使用 sys.exit()

字串正則匹配

re模組為高階字串處理提供了正則表示式工具。對於複雜的匹配和處理,正則表示式提供了簡潔、優化的解決方案:

 
>>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat' 

如果只需要簡單的功能,應該首先考慮字串的方法:

 
>>> 'tea for too'.replace('too', 'two') 'tea for two' 

數學

math模組為浮點運算提供了對底層C函式庫的訪問:

 
>>> import math>>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0 

random提供了生成隨機數的工具。

 
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4 

訪問網際網路

用於訪問網際網路以及處理網路通訊協議的幾個模組中,其中最簡單的兩個分別是用於處理從 urls 接收的資料的 urllib.request 以及用於傳送電子郵件的 smtplib:

 
>>> from urllib.request import urlopen >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... line = line.decode('utf-8') # Decoding the binary data to text .... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ... ... Beware the Ides of March. ... """) >>> server.quit() 

第二個例子需要本地有一個正在執行的郵件伺服器。

日期和時間

datetime模組為日期和時間處理同時提供了簡單和複雜的方法。、

支援日期和時間演算法的同時,實現的重點放在更有效的處理和格式化輸出。

該模組還支援時區處理:

 
>>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368 

資料壓縮

以下模組直接支援通用的資料打包和壓縮格式:zlib,gzip,bz2,zipfile,以及tarfile。

 
>>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979 

效能度量

衡量解決同一問題的不同方法之間的效能差異。

例如,使用元組封裝和拆封來交換元素看起來要比使用傳統的方法要誘人的多,timeit 證明了現代的方法更快一些。

 
>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791 

相對於 timeit 的細粒度,:mod:profile 和 pstats 模組提供了針對更大程式碼塊的時間度量工具。

測試模組

開發高質量軟體的方法之一是為每一個函式開發測試程式碼,並且在開發過程中經常進行測試。doctest模組提供了一個工具,掃描模組並根據程式中內嵌的文件字串執行測試。

測試構造如同簡單的將它的輸出結果剪下並貼上到文件字串中。

通過使用者提供的例子,它強化了文件,允許 doctest 模組確認程式碼的結果是否與文件一致:

 
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # 自動驗證嵌入測試 

unittest模組不像 doctest模組那麼容易使用,不過它可以在一個獨立的檔案裡提供一個更全面的測試集:

 
import unittest  class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests