11 Python標準庫簡明教程 II
Table of Contents 1 輸出格式 2 模板 3 處理位元據 4 多線程 5 日誌(Logging) 6 弱引用(Weak References) 7 與List配合使用的工具 8 十進位浮點數據運算
1 輸出格式
repr 模組提供了一個定製版本的repr(),用於得到有大量內容的容器的縮寫形式
>>> import repr>>> repr.repr(set('helloword'))"set(['d', 'e', 'h', 'l', 'o', 'r', ...])"
pprint 模組提供了更多複雜的控制,用於列印內建的以及使用者定義物件,輸出的結果可讀性比較好。
>>> import pprint>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']]]]>>> pprint.pprint(t, width=30)[[[['black', 'cyan'], 'white', ['green', 'red']]]]
textwrap 模組可以格式化段落以適應螢幕寬度
>>> import textwrap>>> doc = """The wrap() method is just like fill() except that it returns... a list of strings instead of one big string with newlines to separate... the wrapped lines.""">>> >>> print textwrap.fill(doc, width = 30)The wrap() method is just likefill() except that it returnsa list of strings instead ofone big string with newlinesto separate the wrapped lines.
locacle 模組可以根據文化和地區決定資料格式:
>>> locale.setlocale(locale.LC_ALL, 'zh_CN.utf8')'zh_CN.utf8'>>> conv = locale.localeconv()>>> x = 1234567.8>>> locale.format("%d", x, grouping=True)'1,234,567'
2 模板
string 模組提供了一個多才多藝的 Template 類,它文法簡單,普通使用者也可以方便地編輯,這使得使用者可以定製 它們的應用。
>>> from string import Template>>> t = Template('${village}folk send $$10 to $cause.')>>> t.substitute(village='Nottingham', case='the ditch fund')'Nottinghamfolk send $10 to the ditch fund.'
注意,$可以開始定義一個點位符,這個點位符將來可以被真正的資料替換。 如果想輸入真正的,可以連續輸入兩個.如果substitute中沒有指定模板中 點位符的值,將返回KeyError.如果使用safe_ substitute,沒有指定的點位符會 被忽略。
>>> t = Template('Return the $item to $owner.')>>> t.substitute(item='value')Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/string.py", line 172, in substitute return self.pattern.sub(convert, self.template) File "/usr/lib/python2.7/string.py", line 162, in convert val = mapping[named]KeyError: 'owner'>>> t.safe_substitute(item='value')'Return the value to $owner.'
Template 子類可以指定限定符,即把$換成其它符號也可以,例如下面這個批量改名的程式。
import timeimport os.pathfrom string import Templatephotofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']class BatchRename(Template): delimiter = '%'fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ')t = BatchRename(fmt)date = time.strftime('%d%b%y')for i, filename in enumerate(photofiles): base, ext = os.path.splitext(filename) newname = t.substitute(d=date, n=i, f=ext) print '{0} --> {1}'.format(filename, newname)
>>> import tempEnter rename style (%d-date %n-seqnum %f-format): Steve_%n%fimg_1074.jpg --> Steve_0.jpgimg_1076.jpg --> Steve_1.jpgimg_1077.jpg --> Steve_2.jpg
3 處理位元據
struct 包提供了 pack() 和 unpack() 函數,處理不同長度的二進位記錄格式的資料。下面的代碼 展示了如何不使用 zipfile 模組處理ZIP檔案的頭資訊。"H"和"I"分別代表兩位元組,四位元組無符號數字。 "<"代表標準大小,小尾端位元組順序。
import structdata = open('tzipfile.zip', 'rb').read()start = 0for i in range(3): # show the first 3 file headers start += 14 fields = struct.unpack('<IIIHH', data[start:start+16]) crc32, comp_size, uncomp_size, filenamesize, extra_size = fields start += 16 filename = data[start:start+filenamesize] start += filenamesize extra = data[start:start+extra_size] print filename, hex(crc32), comp_size, uncomp_size start += extra_size + comp_size # skip to the next header
$ zipinfo tzipfile.zip Archive: tzipfile.zipZip file size: 442 bytes, number of entries: 3-rw-rw-r-- 3.0 unx 0 bx stor 13-Mar-08 14:31 tzipfile.c-rw-rw-r-- 3.0 unx 0 bx stor 13-Mar-08 14:38 f2.c-rw-rw-r-- 3.0 unx 0 bx stor 13-Mar-08 14:38 f3.c3 files, 0 bytes uncompressed, 0 bytes compressed: 0.0%$ python tstruct.py tzipfile.c 0x0 0 0f2.c 0x0 0 0f3.c 0x0 0 0
4 多線程
線程是一種可以將沒有序列信賴的任務分開執行的技術,可以用於提高程式的響應。例如等待使用者輸入時,在後台同時 運行其它任務。
import threading, zipfileclass AsyncZip(threading.Thread): def __init__(self, infile, outfile): threading.Thread.__init__(self) self.infile = infile self.outfile = outfile def run(self): f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) f.write(self.infile) f.close() print 'Finished background zip of: ', self.infilebackground = AsyncZip('mydata.txt', 'myarchive.zip')background.start()print 'The main program continues to run in foreground.'background.join() # Wait for the background task to finishprint 'Main program waited until background was done.'
多線程程式的挑戰在於協調好共用資料和資源的線程。線程模組提取了大量同步原語,例如鎖,事件,條件變數,訊號量。 雖然這些工具非常強大,但是低級的設計錯誤常常導致一些不可重現的錯誤。所以,比較好的方式是使用一個線程訪問 資源,使用 Queue 模組讓其它線程依次得到資料。 5 日誌(Logging)
logging 模組提供了靈活多樣的日誌系統,最簡單的情況是將日誌資訊發送到一個檔案或者 sys.stderr:
>>> import logging>>> logging.debug("Debugging infor")>>> logging.info("Infomation mess")>>> logging.warning("Warning mess")WARNING:root:Warning mess>>> logging.error("Error mess")ERROR:root:Error mess>>> logging.critical('Critical error')CRITICAL:root:Critical error
日誌系統可以由Python直接配置,也可以使用可編輯的設定檔來定製。 6 弱引用(Weak References)
Python會自動進行記憶體管理,當最後一次引用被消除後就會釋放記憶體。 這種機制多數情況下運行良好,但是有時候需要跟蹤對象,看它什麼時候被引用。但是跟蹤對象本身就是對對象的引用。 weakref 模組提供了跟蹤對象,但又不建立引用的方式,當對象不再需要時,會自動從 weakref 表中移除。
>>> import weakref, gc>>> class A:... def __init__(self, value):... self.value = value... def __repr__(self):... return str(self.value)...>>> a = A(10) # create a reference>>> d = weakref.WeakValueDictionary()>>> d['primary'] = a # does not create a reference>>> d['primary'] # fetch the object if it is still alive10>>> del a # remove the one reference>>> gc.collect() # run garbage collection right away0>>> d['primary'] # entry was automatically removedTraceback (most recent call last): File "<stdin>", line 1, in <module> d['primary'] # entry was automatically removed File "C:/python26/lib/weakref.py", line 46, in __getitem__ o = self.data[key]()KeyError: 'primary'
7 與List配合使用的工具
內建的list類型可以滿足許多資料結構的需求,但是有時候出於效能方面的權衡,可以需要一些其它的類似 list的資料結構。 array 模組提取了一個 array() 對象,只儲存同類型資料並且可以以更加緊湊的方式儲存。 下面這個例子可以以每項2位元組的方式儲存無符號位元,而不是list的16位元組。
>>> from array import array>>> a = array('H', [1,2,3])>>> sum(a)6>>> a[1:3]array('H', [2, 3])>>>
collections 模組提供了 deque() 對象,與list非常相似,但是可以更快地從左側添加刪除資料,同時從中間尋找的速度 變慢。這一對象適合於實現隊列和寬度優先搜尋樹。
>>> from collections import deque>>> d = deque(["task1", "task2", "task3"])>>> d.append("task4")>>> print "Handleing", d.popleft()Handleing task1
除此之外,標準庫還提取了例如 bisect 模組用於操作已排序的list.
>>> import bisect>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'python')]>>> bisect.insort(scores, (300, 'ruby'))>>> scores[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'python')]
heapq 模組提供了一些函數,用於在普通lists的基礎上實現堆。值最小的項通常放在位置0。這在經常訪問最小元素, 但是不需要對整個list排序時非常有用.
>>> from heapq import heapify, heappop, heappush>>> data = [1,3,4,6,2,7]>>> heapify(data)>>> heappush(data, -5)>>> [heappop(data) for i in range(3)][-5, 1, 2]
8 十進位浮點數據運算
decimal 模組提供 *Decimal* 資料類型用於十進位浮點數運算。與內建的float相比,這個類在以下方面非常有用: 金融以及其它需要精確十進位表示的應用 控制精度 控制舍入,滿足合法可控的需求 跟蹤重要的十進位位 使用者希望結果和手工計算的相同的應用
例如下面的計算,使用十進位浮點計算和二進位浮點計算結果就不相同
>>> from decimal import *>>> x = Decimal('0.70') * Decimal('1.05')>>> xDecimal('0.7350')>>> x.quantize(Decimal('0.01'))Decimal('0.74')>>> 0.7 * 1.050.735>>> round(.70 * 1.05, 2)0.73>>> 1.999999999+0.00000000000000000000000011.999999999>>> Decimal('1.999999999') + Decimal('0.0000000000000000000000001')Decimal('1.9999999990000000000000001')
原文連結: http://docs.python.org/2/tutorial/stdlib2.html