预计阅读本页时间:-
Closing Files and Server Connections
We encountered examples in this category in Chapter 33. As a summary, though, exception processing tools are also commonly used to ensure that system resources are finalized, regardless of whether an error occurs during processing or not.
For example, some servers require connections to be closed in order to terminate a session. Similarly, output files may require close calls to flush their buffers to disk, and input files may consume file descriptors if not closed; although file objects are automatically closed when garbage collected if still open, it’s sometimes difficult to be sure when that will occur.
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
The most general and explicit way to guarantee termination actions for a specific block of code is the try/finally statement:
myfile = open(r'C:\misc\script', 'w')
try:
...process myfile...
finally:
myfile.close()
As we saw in Chapter 33, some objects make this easier in Python 2.6 and 3.0 by providing context managers run by the with/as statement that terminate or close the objects for us automatically:
with open(r'C:\misc\script', 'w') as myfile:
...process myfile...
So which option is better here? As usual, it depends on your programs. Compared to the try/finally, context managers are more implicit, which runs contrary to Python’s general design philosophy. Context managers are also arguably less general—they are available only for select objects, and writing user-defined context managers to handle general termination requirements is more complex than coding a try/finally.
On the other hand, using existing context managers requires less code than using try/finally, as shown by the preceding examples. Moreover, the context manager protocol supports entry actions in addition to exit actions. Although the try/finally is perhaps the more widely applicable technique, context managers may be more appropriate where they are already available, or where their extra complexity is warranted.