和HTML网络报告成为可能。
11.3 Working with Binary Data Record Layouts
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 Multi-threading
线程是一种解耦无顺序依赖关系任务的技术。线程有助于提高接收用户输入应用的响应速度,而其他任务在后台运行。相关的用例是运行IO的同时在另一个线程中作耗时计算操作。
以下代码展示高层模块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.')
多线程应用主要的挑战是协调共享数据或者其他资源的多个线程。为了实现这个目标,线程模块提供了一系列同步原语,包括锁,时间,条件变量以及信号。
虽然这些工具很强大,但是很小的设计错误也会导致很难重现的问题。因此,任务协作首选的方案是将所有对资源的访问都集中在一个单线程中,然后使用queue
模块为这个单线程提供来自其他线程的请求。使用Queue
对象进行跨线程通信和协调的应用程序更容易设计,可读性更好,更可靠。
11.5 Logging
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
默认情况下,debug和info级别的信息被抑制,输出目的地是标准错误。其他输出选项包括通过邮件,数据报,套接字以及HTTP服务器的路由信息。新的过滤器可以根据不同的消息优先级选择不同的路由:DEBUG, INFO, WARNING, ERROR
以及CRITICAL
。
日志系统可以直接从Python配置,也可以从用户可编辑的配置文件加载,以便于自定义日志,而无需修改应用程序。
11.6 Weak References
Python自动进行内存管理(针对大多数对象引用计数以及垃圾回收以消除循环)。对象最后的引用删除后,其内存立即释放。
这种方法适用于大多数应用,但是偶尔只需要跟踪对象即可。不幸的是,仅仅跟踪它们也会创建永久的应用。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:/python36/lib/weakref.py", line 46, in __getitem__
o = self.d