GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing python.github.io — 11. Python 標準函式庫概覽——第二部份 — Python 3.15.2 說明文件 11. Python 標準函式庫概覽——第二部份¶第二部分涵蓋更多支援專業程式設計所需要的進階模組。這些模組很少出現在小腳本中。 11.1. 輸出格式化 (Output formatting)¶
>>> import reprlib >>> reprlib.repr(set('supercalifragilisticexpialidocious')) "{'a', 'c', 'd', 'e', 'f', 'g', ...}"
>>> import pprint >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', ... 'yellow'], 'blue']]] ... >>> pprint.pprint(t, width=30) [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
>>> 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.
>>> import locale >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') 'English_United States.1252' >>> conv = locale.localeconv() # 取得慣例的對映 >>> 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. 模板化 (Templating)¶
格式化方式是使用佔位符號名稱 (placeholder name),它是由 >>> 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.' 如果在 dictionary 或關鍵字引數中未提供某個佔位符號的值,那麼 >>> 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 的 subclass(子類別)可以指定自訂的分隔符號 (delimiter)。例如,一個相片瀏覽器的批次重新命名功能,可以選擇用百分號作為現在日期、照片序號或檔案格式的佔位符號: >>> 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 網路報表替換自訂的模板。 11.3. 二進制資料記錄編排 (Binary data record layouts)¶
import struct with open('myfile.zip', 'rb') as f: data = f.read() start = 0 for i in range(3): # 顯示前 3 個檔案標頭 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 # 跳到下一個標頭 11.4. 多執行緒 (Multi-threading)¶執行緒是一種用來對非順序相依 (sequentially dependent) 的多個任務進行解耦 (decoupling) 的技術。當其他任務在背景執行時,多執行緒可以用來提升應用程式在接收使用者輸入時的反應能力。一個相關的用例是,運行 I/O 的同時,在另一個執行緒中進行計算。 以下程式碼顯示了高階的 import threading, zipfile class AsyncZip(threading.Thread): def __init__(self, infile, outfile): super().__init__() self.infile = infile self.outfile = outfile def run(self): with zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) as f: f.write(self.infile) 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() # 等待背景任務結束 print('Main program waited until background was done.') 多執行緒應用程式的主要挑戰是,要協調多個彼此共享資料或資源的執行緒。為此,threading 模組提供了多個同步原語 (synchronization primitive),包括鎖 (lock)、事件 (event)、條件變數 (condition variable) 和號誌 (semaphore)。 儘管這些工具很強大,但很小的設計錯誤也可能導致一些難以重現的問題。所以,任務協調的首選方法是,把所有對資源的存取集中到單一的執行緒中,然後使用 11.5. 日誌記錄 (Logging)¶
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 在預設情況,資訊和除錯訊息不會被顯示,其輸出會被發送到標準錯誤 (standard error)。其他輸出選項包括,將訊息轉發到電子郵件、資料報 (datagram)、網路插座 (socket) 或 HTTP 伺服器。新的過濾器可以根據訊息的優先順序,選擇不同的路由 (routing) 方式: 日誌記錄系統可以直接從 Python 配置,也可以透過載入使用者可編輯的配置檔案以進行客製化的日誌記錄,而無須對應用程式做出變更。 11.6. 弱引用 (Weak references)¶Python 會自動進行記憶體管理(對大多數物件進行參照計數 (reference counting) 並使用 garbage collection 來消除循環參照)。當一個參照從記憶體被移除後不久,該記憶體就會被釋出。 此方式對大多數應用程式來說都沒問題,但偶爾也需要在物件仍然被其他物件所使用時持續追蹤它們。可惜的是,儘管只是追蹤它們,也會建立一個使它們永久化 (permanent) 的參照。 >>> 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:/python315/lib/weakref.py", line 46, in __getitem__ o = self.data[key]() KeyError: 'primary' 11.7. 使用於 list 的工具¶許多對於資料結構的需求,可以透過內建的 list(串列)型別來滿足。但是,有時也會根據效能的各種取捨,需要一些替代的實作。
>>> from array import array >>> a = array('H', [4000, 10, 700, 22222]) >>> sum(a) 26932 >>> a[1:3] array('H', [10, 700])
>>> 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) 除了替代的 list 實作以外,函式庫也提供了其他工具,例如 >>> 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')]
>>> from heapq import heapify, heappop, heappush >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> heapify(data) # 將串列重新排列為堆積順序 >>> heappush(data, -5) # 加入新項目 >>> [heappop(data) for i in range(3)] # 取得三個最小的項目 [-5, 0, 1] 11.8. 十進制浮點數運算 (Decimal floating-point arithmetic)¶
例如,要計算 70 美分的手機充電加上 5% 稅金的總價,使用十進制浮點數和二進制浮點數,會算出不同的答案。如果把計算結果四捨五入到最接近的美分,兩者的差異會更顯著: >>> from decimal import * >>> round(Decimal('0.70') * Decimal('1.05'), 2) Decimal('0.74') >>> round(.70 * 1.05, 2) 0.73
準確的表示法使得 >>> 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
>>> getcontext().prec = 36 >>> Decimal(1) / Decimal(7) Decimal('0.142857142857142857142857142857142857') |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |