11. 標準庫簡要介紹 — 第二部分¶
本部分介紹了支援專業程式設計需求的高階模組。這些模組很少出現在小型指令碼中。
11.1. 輸出格式¶
reprlib
模組提供了 repr()
的一個版本,它專門用於大型或深層巢狀容器的縮寫顯示。
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
pprint
模組對內建物件和使用者定義物件的列印提供了更精密的控制,使其能夠被直譯器讀取。當結果超過一行時,"美化列印器"會新增換行符和縮排,以更清晰地展示資料結構。
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]
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=40))
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.
locale
模組訪問特定文化的資料格式資料庫。locale 的 format 函式的 grouping 屬性提供了直接使用組分隔符格式化數字的方法。
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv() # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format_string("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
11.2. 模板¶
string
模組包含一個多功能的 Template
類,其語法簡化,適合終端使用者編輯。這允許使用者自定義其應用程式而無需更改應用程式。
該格式使用由 $
和有效 Python 識別符號(字母數字字元和下劃線)組成的佔位符名稱。用大括號將佔位符括起來,可以使其後面緊跟更多字母數字字元而無需中間空格。寫 $$
會建立一個轉義的 $
。
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
當字典或關鍵字引數中未提供佔位符時,substitute()
方法會引發 KeyError
。對於郵件合併風格的應用程式,使用者提供的資料可能不完整,safe_substitute()
方法可能更合適 — 如果資料缺失,它會保持佔位符不變。
>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'
Template 子類可以指定自定義分隔符。例如,照片瀏覽器的一個批次重新命名工具可能會選擇使用百分號作為佔位符,例如當前日期、影像序列號或檔案格式。
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
...
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
>>> 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))
img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
模板化的另一個應用是將程式邏輯與多個輸出格式的細節分離。這使得可以為 XML 檔案、純文字報告和 HTML Web 報告替換自定義模板。
11.3. 處理二進位制資料記錄佈局¶
struct
模組提供了 pack()
和 unpack()
函式,用於處理變長二進位制記錄格式。以下示例展示瞭如何在不使用 zipfile
模組的情況下遍歷 ZIP 檔案中的頭部資訊。打包程式碼 "H"
和 "I"
分別表示兩個和四個位元組的無符號數字。"<"
表示它們是標準大小且採用小端位元組序。
import struct
with open('myfile.zip', 'rb') as f:
data = f.read()
start = 0
for 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
11.4. 多執行緒¶
執行緒是一種將非順序依賴任務解耦的技術。執行緒可用於提高接受使用者輸入的應用程式的響應能力,同時其他任務在後臺執行。一個相關的用例是與另一個執行緒中的計算並行執行 I/O。
以下程式碼顯示了高階 threading
模組如何在主程式繼續執行的同時在後臺執行任務。
import threading, zipfile
class 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.infile)
background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')
background.join() # Wait for the background task to finish
print('Main program waited until background was done.')
多執行緒應用程式的主要挑戰是協調共享資料或其他資源的執行緒。為此,threading 模組提供了許多同步原語,包括鎖、事件、條件變數和訊號量。
儘管這些工具功能強大,但微小的設計錯誤可能導致難以重現的問題。因此,任務協調的首選方法是將對資源的所有訪問集中在一個執行緒中,然後使用 queue
模組將其他執行緒的請求傳送到該執行緒。使用 Queue
物件進行執行緒間通訊和協調的應用程式更容易設計、更具可讀性且更可靠。
11.5. 日誌記錄¶
logging
模組提供了一個功能齊全且靈活的日誌系統。最簡單地說,日誌訊息會發送到檔案或 sys.stderr
。
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
這會產生以下輸出:
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
預設情況下,資訊和除錯訊息被抑制,輸出傳送到標準錯誤。其他輸出選項包括透過電子郵件、資料報、套接字或 HTTP 伺服器路由訊息。新的過濾器可以根據訊息優先順序選擇不同的路由:DEBUG
、INFO
、WARNING
、ERROR
和 CRITICAL
。
日誌系統可以直接從 Python 配置,也可以從使用者可編輯的配置檔案載入,以實現自定義日誌記錄而無需更改應用程式。
11.6. 弱引用¶
Python 執行自動記憶體管理(大多數物件的引用計數和垃圾回收以消除迴圈)。記憶體會在對其的最後一個引用被消除後不久釋放。
這種方法適用於大多數應用程式,但偶爾需要僅在其他東西使用物件時才跟蹤它們。不幸的是,僅僅跟蹤它們就會建立一個使它們永久存在的引用。weakref
模組提供了無需建立引用即可跟蹤物件的工具。當不再需要物件時,它會自動從 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 alive
10
>>> del a # remove the one reference
>>> gc.collect() # run garbage collection right away
0
>>> d['primary'] # entry was automatically removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
d['primary'] # entry was automatically removed
File "C:/python314/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
11.7. 列表工具¶
許多資料結構需求都可以透過內建的列表型別來滿足。然而,有時需要具有不同效能權衡的替代實現。
array
模組提供了一個 array
物件,它類似於一個只儲存同構資料並更緊湊地儲存它的列表。以下示例展示了一個儲存為兩個位元組無符號二進位制數字(型別碼 "H"
)的數字陣列,而不是通常的 Python int 物件常規列表的每個條目 16 位元組。
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
collections
模組提供了一個 deque
物件,它類似於一個列表,但左側的新增和彈出操作更快,而中間的查詢操作較慢。這些物件非常適合實現佇列和廣度優先樹搜尋。
>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
node = unsearched.popleft()
for m in gen_moves(node):
if is_goal(m):
return m
unsearched.append(m)
除了替代列表實現之外,該庫還提供了其他工具,例如 bisect
模組,其中包含用於操作排序列表的函式。
>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
heapq
模組提供了基於常規列表實現堆的函式。最低值條目始終保留在位置零。這對於需要反覆訪問最小元素但不希望執行完整列表排序的應用程式很有用。
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data) # rearrange the list into heap order
>>> heappush(data, -5) # add a new entry
>>> [heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]
11.8. 十進位制浮點算術¶
decimal
模組為十進位制浮點算術提供了 Decimal
資料型別。與內建的二進位制浮點 float
實現相比,該類對於以下情況特別有用:
金融應用程式和其他需要精確十進位制表示的用途,
控制精度,
控制舍入以滿足法律或監管要求,
跟蹤有效十進位制位,或
使用者期望結果與手算結果一致的應用程式。
例如,對 70 美分的電話費徵收 5% 的稅,在十進位制浮點和二進位制浮點中會給出不同的結果。如果將結果四捨五入到最近的整數美分,差異就會變得顯著。
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73
Decimal
結果保留尾隨零,從兩位有效乘數自動推斷出四位有效位。Decimal 再現了手算數學,避免了二進位制浮點無法精確表示十進位制量時可能出現的問題。
精確表示使得 Decimal
類能夠執行模數計算和相等性測試,這些對於二進位制浮點是不合適的。
>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995
>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0
False
decimal
模組提供了所需精度的算術。
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')