<p>如<a href="https://stackoverflow.com/users/953022/bluewind">Bluewind</a>所述,您必须确保将上下文管理器的yield部分包装在try:finally语句中,否则任何异常都不会在上下文管理器中得到正确处理。</p>
<p>来自<a href="http://docs.python.org/2.7/library/tempfile.html" rel="nofollow noreferrer">Python 2.7 docs</a></p>
<blockquote>
<p>At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a try...except...finally statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the with statement that the exception has been handled, and execution will resume with the statement immediately following the with statement.</p>
</blockquote>
<p>另外,如果您使用的是Python 3.2+,那么应该检查一下<a href="http://docs.python.org/3.2/library/tempfile.html" rel="nofollow noreferrer">this little gem</a>,它为您很好地包装了上述所有内容</p>
<blockquote>
<p>tempfile.TemporaryDirectory(suffix='', prefix='tmp', dir=None)</p>
<p>This function creates a temporary directory using mkdtemp() (the supplied arguments are passed directly to the underlying function). The resulting object can be used as a context manager (see With Statement Context Managers). On completion of the context (or destruction of the temporary directory object), the newly created temporary directory and all its contents are removed from the filesystem.</p>
<p>The directory name can be retrieved from the name attribute of the returned object.</p>
<p>The directory can be explicitly cleaned up by calling the cleanup() method.</p>
<p>New in version 3.2.</p>
</blockquote>