[譯]The Python Tutorial#Brief Tour of the Standard Library — Part II
第二部分介紹更多滿足專業(yè)編程需求的高級模塊,這些模塊在小型腳本中很少用到缰泡。
11.1 Output Formatting
reprlib
模塊為大型或者深度嵌套的容器提供了一個定制版本的repr()
函數(shù):
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
pprint
模塊為內(nèi)嵌對象或者用戶自定義對象以解釋器可讀方式打印提供了更精細(xì)的控制词裤。當(dāng)打印結(jié)果超過一行時相满,“打印美化器”添加換行符和縮進菜枷,清晰顯示原有的數(shù)據(jù)結(jié)構(gòu):
>>> 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
模塊格式化文本段落適應(yīng)指定屏幕寬度:
>>> 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.
local
模塊訪問特定文化數(shù)據(jù)格式的數(shù)據(jù)庫。區(qū)域設(shè)置格式函數(shù)的分組屬性提供了使用組分隔符格式化數(shù)字的直接方法:
>>> 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("%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 Templting
string
模塊包括一個功能強大的Template
類吭练,其簡化的語法適用于最終用戶的編輯冕茅。該類允許用戶自定義他們的應(yīng)用,而不用修改應(yīng)用店茶。
格式化使用由$
和有效Python標(biāo)識符(字母數(shù)字字符以及下劃線)組成的占位符蜕便。占位符外圍的花括號允許其后跟更多數(shù)字字母字符而無需中間空格。使用$$
轉(zhuǎn)義$
:
>>> 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.'
當(dāng)參數(shù)字典或者關(guān)鍵字參數(shù)沒有提供對應(yīng)的占位符時贩幻,substitute()
方法拋出KeyError異常轿腺。對于郵件合并風(fēng)格的應(yīng)用程序两嘴,用戶提供的數(shù)據(jù)可能不完全,使用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的子類可以指定自定義的定界符族壳。例如憔辫,圖片瀏覽器的批量重命名工具可能使用百分比號作為占位符,如當(dāng)前日期仿荆,圖片序列碼或者文件格式:
>>> 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
模板的另一種應(yīng)用是將程序邏輯與多種輸出格式的細(xì)節(jié)分開贰您。這樣使得自定義模板替換為XML文件,純文本報告和HTML網(wǎng)絡(luò)報告成為可能赖歌。
11.3 Working with Binary Data Record Layouts
struct
模塊提供了用于處理可變長度二進制記錄格式的pack
以及unpack
枉圃。以下示例展示如何在沒有zipfile
的幫助下遍歷ZIP文件的頭信息。分組代碼“H”和“I”分別表示兩個和四個字節(jié)的無符號數(shù)庐冯。<
表示它們是標(biāo)準(zhǔn)大小和小端字節(jié)順序:
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 Multi-threading
線程是一種解耦無順序依賴關(guān)系任務(wù)的技術(shù)孽亲。線程有助于提高接收用戶輸入應(yīng)用的響應(yīng)速度,而其他任務(wù)在后臺運行展父。相關(guān)的用例是運行IO的同時在另一個線程中作耗時計算操作返劲。
以下代碼展示高層模塊threading
如何在主程序運行的同時在后臺執(zhí)行任務(wù):
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.')
多線程應(yīng)用主要的挑戰(zhàn)是協(xié)調(diào)共享數(shù)據(jù)或者其他資源的多個線程。為了實現(xiàn)這個目標(biāo)栖茉,線程模塊提供了一系列同步原語篮绿,包括鎖,時間吕漂,條件變量以及信號亲配。
雖然這些工具很強大,但是很小的設(shè)計錯誤也會導(dǎo)致很難重現(xiàn)的問題惶凝。因此吼虎,任務(wù)協(xié)作首選的方案是將所有對資源的訪問都集中在一個單線程中,然后使用queue
模塊為這個單線程提供來自其他線程的請求苍鲜。使用Queue
對象進行跨線程通信和協(xié)調(diào)的應(yīng)用程序更容易設(shè)計思灰,可讀性更好,更可靠混滔。
11.5 Logging
logging
模塊提供了功能完備且靈活的日志系統(tǒng)洒疚。最簡單的用法是將日志信息輸出到文件或者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
默認(rèn)情況下,debug和info級別的信息被抑制坯屿,輸出目的地是標(biāo)準(zhǔn)錯誤油湖。其他輸出選項包括通過郵件,數(shù)據(jù)報领跛,套接字以及HTTP服務(wù)器的路由信息肺魁。新的過濾器可以根據(jù)不同的消息優(yōu)先級選擇不同的路由:DEBUG, INFO, WARNING, ERROR
以及CRITICAL
。
日志系統(tǒng)可以直接從Python配置隔节,也可以從用戶可編輯的配置文件加載鹅经,以便于自定義日志,而無需修改應(yīng)用程序怎诫。
11.6 Weak References
Python自動進行內(nèi)存管理(針對大多數(shù)對象引用計數(shù)以及垃圾回收以消除循環(huán))瘾晃。對象最后的引用刪除后,其內(nèi)存立即釋放幻妓。
這種方法適用于大多數(shù)應(yīng)用蹦误,但是偶爾只需要跟蹤對象即可。不幸的是肉津,僅僅跟蹤它們也會創(chuàng)建永久的應(yīng)用强胰。weakref
模塊提供了無需創(chuàng)建引用跟蹤對象的工具。一旦不再需要對象時妹沙,其自動從弱引用表中刪除偶洋,并觸發(fā)回調(diào)。典型的應(yīng)用包括創(chuàng)建成本高的緩存對象:
>>> 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:/python36/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
11.7 Tools for Working with Lists
內(nèi)置列表類型可以滿足許多數(shù)據(jù)結(jié)構(gòu)的需求距糖。然而玄窝,有時候需要不同性能權(quán)衡的替代實現(xiàn)。
array
模塊提供一個array()
對象悍引,就像一個只存儲同類型數(shù)據(jù)恩脂,并且存儲更加緊湊的列表一樣。以下示例展示一個數(shù)字?jǐn)?shù)組趣斤,它以兩個字節(jié)無符號二進制數(shù)(typecode為"H"
)存儲俩块,而不是通常的每個對象16字節(jié)的常規(guī)Python整數(shù)對象列表:
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])
collections
模塊提供deque()
對象,就像一個擁有速度更快的左端添加和移除操作浓领,更慢的中間查找速度的列表一樣玉凯。這些對象適用于實現(xiàn)隊列以及寬度優(yōu)先樹搜索:
>>> 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)
除了可選的列表實現(xiàn)外,庫也提供了其他工具镊逝,比如具有操作有序列表函數(shù)的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
模塊提供了基于常規(guī)隊列實現(xiàn)堆的函數(shù)壮啊。最小值的實體總是放在位置0處。這對于需要重復(fù)訪問最小元素但是不想要對整個列表排序的應(yīng)用很有用:
>>> 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 Floating Point Arithmetic
decimal
模塊為十進制浮點算法提供Decimal
數(shù)據(jù)類型撑蒜。與二進制浮點型的內(nèi)嵌的float
實現(xiàn)相比歹啼,這個類在以下場合及其有用:
- 金融類應(yīng)用以及其他需要精確十進制表示的應(yīng)用;
- 控制精度座菠;
- 控制舍入以滿足法律上或者管控上的需求狸眼;
- 追蹤重要的小數(shù)位數(shù),或者
- 用戶其他輸出與手工計算匹配的應(yīng)用
例如浴滴,計算對70分的電話費取5%的稅拓萌,十進制浮點型盒二進制浮點型結(jié)果不同。當(dāng)結(jié)果需要舍入到最近的整分時升略,它們之間的差異就很重要了:
>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73
十進制結(jié)果保持一個尾隨的0微王,精度自從從兩位延伸到了四位屡限。十進制可以重新進行數(shù)學(xué)運算,就像手工一樣炕倘,并且避免了二進制浮點數(shù)不能精確表示十進制數(shù)時會產(chǎn)生的問題钧大。
精確表示使得Decimal
類可以執(zhí)行求余計算以及不適用于二進制浮點型的比較測試:
>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995
>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False
decimal
模塊提供了必要的高精度算法:
>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')